Add e2e test harness for testing editor logic without Gio display
- internal/test/e2e/: FrameCapture, Harness, ElementAssertions, helpers - internal/editor/logic.go: Add done channel and Done() method for graceful shutdown - internal/editor/mock_setup.go: Mock filesystem for tests - internal/browser/: Browser layout and search logic - internal/io/: Worker pool for async tasks - Update architecture docs and spec
This commit is contained in:
@@ -0,0 +1,176 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// LoadInitialPages loads the pages required for the current viewport from the
|
||||
// SortIndex into the Pages map. This should be called after the SortIndex is built
|
||||
// or updated.
|
||||
func LoadInitialPages(s *BrowserState) {
|
||||
if s.SortIndex == nil || s.TotalEntries == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Calculate the range of pages to load (visible + prefetch)
|
||||
minPage, maxPage := computeVisiblePageRange(s)
|
||||
|
||||
for i := minPage; i <= maxPage; i++ {
|
||||
if _, ok := s.Pages[i]; !ok {
|
||||
page := loadPageFromIndex(s, i)
|
||||
if page != nil {
|
||||
s.Pages[i] = page
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// loadPageFromIndex creates a Page from the sorted index at the given page index.
|
||||
// Uses position maps to convert sorted indices to raw indices for entry lookup.
|
||||
// Returns nil if the page index is out of bounds.
|
||||
func loadPageFromIndex(s *BrowserState, pageIndex int) *Page {
|
||||
if pageIndex < 0 || pageIndex*PageSize >= s.TotalEntries {
|
||||
return nil
|
||||
}
|
||||
|
||||
if s.SortIndex == nil || len(s.SortIndex.Entries) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
start := pageIndex * PageSize
|
||||
end := start + PageSize
|
||||
if end > s.TotalEntries {
|
||||
end = s.TotalEntries
|
||||
}
|
||||
|
||||
// Get the position map for the current sort mode
|
||||
positionMap := s.getSortedIndices()
|
||||
if positionMap == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Build page entries using sorted order
|
||||
entries := make([]Entry, 0, end-start)
|
||||
for i := start; i < end; i++ {
|
||||
rawIdx := positionMap[i]
|
||||
entries = append(entries, s.SortIndex.Entries[rawIdx])
|
||||
}
|
||||
|
||||
return NewPage(pageIndex, entries)
|
||||
}
|
||||
|
||||
// computeVisiblePageRange returns the min and max page indices that should
|
||||
// be loaded based on the current scroll position and visible count.
|
||||
func computeVisiblePageRange(s *BrowserState) (minPage, maxPage int) {
|
||||
minPage = s.ScrollIndex/PageSize - PrefetchDist
|
||||
if minPage < 0 {
|
||||
minPage = 0
|
||||
}
|
||||
maxPage = (s.ScrollIndex + s.VisibleCount)/PageSize + PrefetchDist
|
||||
return minPage, maxPage
|
||||
}
|
||||
|
||||
// getEntryByIndex returns the entry at the given sorted index, or nil if the page
|
||||
// containing that entry is not loaded. Uses position maps to convert sorted
|
||||
// indices to raw indices for correct sort order.
|
||||
func getEntryByIndex(s *BrowserState, sortedIndex int) (*Entry, bool) {
|
||||
if sortedIndex < 0 || sortedIndex >= s.TotalEntries {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
pageIndex := sortedIndex / PageSize
|
||||
page, ok := s.Pages[pageIndex]
|
||||
if !ok || !page.Loaded {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
offset := sortedIndex % PageSize
|
||||
if offset >= len(page.Entries) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return &page.Entries[offset], true
|
||||
}
|
||||
|
||||
// getSortedIndices returns the position map for the current sort mode.
|
||||
// Returns nil if no sort index is available.
|
||||
func (s *BrowserState) getSortedIndices() []int {
|
||||
if s.SortIndex == nil || s.SortIndex.SortOrders == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
key := sortModeKey(s.SortMode)
|
||||
return s.SortIndex.SortOrders[key]
|
||||
}
|
||||
|
||||
// needsPrefetch determines if a page should be prefetched based on the
|
||||
// current scroll position and visible count.
|
||||
// Returns (true, pagesNeeded) if prefetch is needed.
|
||||
func needsPrefetch(s *BrowserState, pageIndex int) (bool, int) {
|
||||
minPage, maxPage := computeVisiblePageRange(s)
|
||||
|
||||
if pageIndex >= minPage && pageIndex <= maxPage {
|
||||
if page, ok := s.Pages[pageIndex]; !ok || !page.Loaded {
|
||||
return true, 1
|
||||
}
|
||||
}
|
||||
|
||||
return false, 0
|
||||
}
|
||||
|
||||
// navigateToDirectory resets browser state and sets the new current path.
|
||||
func navigateToDirectory(s *BrowserState, path string) {
|
||||
s.CurrentPath = path
|
||||
s.ScrollIndex = 0
|
||||
s.SelectedIndex = -1
|
||||
s.Pages = make(map[int]*Page)
|
||||
s.SearchResults = nil
|
||||
s.Query = ""
|
||||
s.TotalEntries = 0
|
||||
}
|
||||
|
||||
// computeTotalPages returns the total number of pages for the current entry count.
|
||||
func computeTotalPages(s *BrowserState) int {
|
||||
if s.TotalEntries == 0 {
|
||||
return 0
|
||||
}
|
||||
pages := s.TotalEntries / PageSize
|
||||
if s.TotalEntries%PageSize != 0 {
|
||||
pages++
|
||||
}
|
||||
return pages
|
||||
}
|
||||
|
||||
// clampScrollIndex ensures the scroll index stays within valid bounds.
|
||||
func clampScrollIndex(s *BrowserState) {
|
||||
if s.ScrollIndex < 0 {
|
||||
s.ScrollIndex = 0
|
||||
}
|
||||
maxScroll := s.TotalEntries - s.VisibleCount
|
||||
if maxScroll < 0 {
|
||||
maxScroll = 0
|
||||
}
|
||||
if s.ScrollIndex > maxScroll {
|
||||
s.ScrollIndex = maxScroll
|
||||
}
|
||||
}
|
||||
|
||||
// filterEntriesByQuery returns indices of entries matching the query (case-insensitive).
|
||||
// Returns nil for empty query.
|
||||
func filterEntriesByQuery(entries []Entry, query string) []int {
|
||||
if query == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
queryLower := strings.ToLower(query)
|
||||
var results []int
|
||||
|
||||
for i, e := range entries {
|
||||
if strings.Contains(strings.ToLower(e.Name), queryLower) {
|
||||
results = append(results, i)
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// --- Test: Load Page From Index At Offset ---
|
||||
|
||||
func TestLoadPage_FromIndexAtOffset(t *testing.T) {
|
||||
// Create a BrowserState with a populated index
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 250
|
||||
|
||||
// Simulate an index with 250 entries (3 pages)
|
||||
// Use zero-padded names so lexicographic order matches numeric order
|
||||
allEntries := make([]Entry, 250)
|
||||
for i := 0; i < 250; i++ {
|
||||
allEntries[i] = NewEntry(
|
||||
fmt.Sprintf("/path/file%03d.txt", i),
|
||||
fmt.Sprintf("file%03d.txt", i),
|
||||
int64(i*100),
|
||||
time.Time{},
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
// Build position map for the default sort mode (NameAsc)
|
||||
s.SortIndex = &DirectoryIndex{
|
||||
Entries: allEntries,
|
||||
SortOrders: map[string][]int{"name_asc": buildPositionMap(allEntries, SortModeNameAsc)},
|
||||
}
|
||||
|
||||
// Load page 1 (entries 100-199)
|
||||
page := loadPageFromIndex(s, 1)
|
||||
|
||||
if page == nil {
|
||||
t.Fatal("expected page to be loaded, got nil")
|
||||
}
|
||||
if page.Index != 1 {
|
||||
t.Errorf("expected Index=1, got %d", page.Index)
|
||||
}
|
||||
if len(page.Entries) != PageSize {
|
||||
t.Errorf("expected %d entries, got %d", PageSize, len(page.Entries))
|
||||
}
|
||||
// First entry of page 1 should be file100.txt
|
||||
if page.Entries[0].Name != "file100.txt" {
|
||||
t.Errorf("expected first entry name=file100.txt, got %s", page.Entries[0].Name)
|
||||
}
|
||||
// Last entry of page 1 should be file199.txt
|
||||
if page.Entries[99].Name != "file199.txt" {
|
||||
t.Errorf("expected last entry name=file199.txt, got %s", page.Entries[99].Name)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Load Page - Last Page Partial ---
|
||||
|
||||
func TestLoadPage_LastPagePartialFromIndex(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 150 // 1 full page + 50 entries in page 1
|
||||
|
||||
allEntries := make([]Entry, 150)
|
||||
for i := 0; i < 150; i++ {
|
||||
allEntries[i] = NewEntry(
|
||||
fmt.Sprintf("/path/file%d.txt", i),
|
||||
fmt.Sprintf("file%d.txt", i),
|
||||
int64(i*100),
|
||||
time.Time{},
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
// Build position map for the default sort mode (NameAsc)
|
||||
s.SortIndex = &DirectoryIndex{
|
||||
Entries: allEntries,
|
||||
SortOrders: map[string][]int{"name_asc": buildPositionMap(allEntries, SortModeNameAsc)},
|
||||
}
|
||||
|
||||
// Load page 1 (last page, should have only 50 entries)
|
||||
page := loadPageFromIndex(s, 1)
|
||||
|
||||
if page == nil {
|
||||
t.Fatal("expected page to be loaded, got nil")
|
||||
}
|
||||
if page.Index != 1 {
|
||||
t.Errorf("expected Index=1, got %d", page.Index)
|
||||
}
|
||||
if len(page.Entries) != 50 {
|
||||
t.Errorf("expected 50 entries, got %d", len(page.Entries))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Load Page - Out Of Bounds ---
|
||||
|
||||
func TestLoadPage_OutOfBoundsFromIndex(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 150
|
||||
|
||||
allEntries := make([]Entry, 150)
|
||||
for i := 0; i < 150; i++ {
|
||||
allEntries[i] = NewEntry(
|
||||
fmt.Sprintf("/path/file%d.txt", i),
|
||||
fmt.Sprintf("file%d.txt", i),
|
||||
int64(i*100),
|
||||
time.Time{},
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
// Build position map for the default sort mode (NameAsc)
|
||||
s.SortIndex = &DirectoryIndex{
|
||||
Entries: allEntries,
|
||||
SortOrders: map[string][]int{"name_asc": buildPositionMap(allEntries, SortModeNameAsc)},
|
||||
}
|
||||
|
||||
// Requesting page 5 (out of bounds) should return nil
|
||||
page := loadPageFromIndex(s, 5)
|
||||
|
||||
if page != nil {
|
||||
t.Errorf("expected nil for out-of-bounds page, got page with %d entries", len(page.Entries))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Compute Visible Page Range ---
|
||||
|
||||
func TestComputeVisiblePageRange(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.ScrollIndex = 250
|
||||
s.VisibleCount = 20
|
||||
|
||||
minPage, maxPage := computeVisiblePageRange(s)
|
||||
|
||||
// ScrollIndex=250 → page 2
|
||||
// VisibleCount=20 → entries 250-269 → pages 2-2 (partial)
|
||||
// With prefetch: min=0, max=4
|
||||
expectedMin := 0 // (250/100) - 2 = 0
|
||||
expectedMax := 4 // (270/100) + 2 = 4
|
||||
|
||||
if minPage != expectedMin {
|
||||
t.Errorf("expected minPage=%d, got %d", expectedMin, minPage)
|
||||
}
|
||||
if maxPage != expectedMax {
|
||||
t.Errorf("expected maxPage=%d, got %d", expectedMax, maxPage)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Compute Visible Page Range - At Start ---
|
||||
|
||||
func TestComputeVisiblePageRange_AtStart(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.ScrollIndex = 0
|
||||
s.VisibleCount = 10
|
||||
|
||||
minPage, maxPage := computeVisiblePageRange(s)
|
||||
|
||||
// Should clamp min to 0
|
||||
if minPage != 0 {
|
||||
t.Errorf("expected minPage=0, got %d", minPage)
|
||||
}
|
||||
// maxPage should be 0 + 2 = 2
|
||||
if maxPage != 2 {
|
||||
t.Errorf("expected maxPage=2, got %d", maxPage)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Get Entry By Index ---
|
||||
|
||||
func TestGetEntryByIndex(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 250
|
||||
|
||||
// Use zero-padded names so lexicographic order matches numeric order
|
||||
allEntries := make([]Entry, 250)
|
||||
for i := 0; i < 250; i++ {
|
||||
allEntries[i] = NewEntry(
|
||||
fmt.Sprintf("/path/file%03d.txt", i),
|
||||
fmt.Sprintf("file%03d.txt", i),
|
||||
int64(i*100),
|
||||
time.Time{},
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
// Build position map for the default sort mode (NameAsc)
|
||||
s.SortIndex = &DirectoryIndex{
|
||||
Entries: allEntries,
|
||||
SortOrders: map[string][]int{"name_asc": buildPositionMap(allEntries, SortModeNameAsc)},
|
||||
}
|
||||
|
||||
// Load some pages
|
||||
s.Pages[0] = loadPageFromIndex(s, 0)
|
||||
s.Pages[1] = loadPageFromIndex(s, 1)
|
||||
|
||||
// Get entry at index 150 (page 1, offset 50)
|
||||
entry, ok := getEntryByIndex(s, 150)
|
||||
|
||||
if !ok {
|
||||
t.Fatal("expected entry to be found")
|
||||
}
|
||||
if entry.Name != "file150.txt" {
|
||||
t.Errorf("expected entry name=file150.txt, got %s", entry.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Get Entry By Index - Unloaded Page ---
|
||||
|
||||
func TestGetEntryByIndex_UnloadedPage(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 250
|
||||
|
||||
allEntries := make([]Entry, 250)
|
||||
for i := 0; i < 250; i++ {
|
||||
allEntries[i] = NewEntry(
|
||||
fmt.Sprintf("/path/file%d.txt", i),
|
||||
fmt.Sprintf("file%d.txt", i),
|
||||
int64(i*100),
|
||||
time.Time{},
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
// Build position map for the default sort mode (NameAsc)
|
||||
s.SortIndex = &DirectoryIndex{
|
||||
Entries: allEntries,
|
||||
SortOrders: map[string][]int{"name_asc": buildPositionMap(allEntries, SortModeNameAsc)},
|
||||
}
|
||||
|
||||
// Only load page 0
|
||||
s.Pages[0] = loadPageFromIndex(s, 0)
|
||||
|
||||
// Try to get entry at index 150 (page 1, not loaded)
|
||||
_, ok := getEntryByIndex(s, 150)
|
||||
|
||||
if ok {
|
||||
t.Error("expected entry not to be found for unloaded page")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Get Entry By Index - Out Of Bounds ---
|
||||
|
||||
func TestGetEntryByIndex_OutOfBounds(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 100
|
||||
|
||||
_, ok := getEntryByIndex(s, 200)
|
||||
|
||||
if ok {
|
||||
t.Error("expected entry not to be found for out-of-bounds index")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Needs Prefetch ---
|
||||
|
||||
func TestNeedsPrefetch(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.ScrollIndex = 500
|
||||
s.VisibleCount = 20
|
||||
s.TotalEntries = 2000
|
||||
|
||||
// Page 3 is within visible range + prefetch
|
||||
needs, _ := needsPrefetch(s, 3)
|
||||
if !needs {
|
||||
t.Error("expected page 3 to need prefetch")
|
||||
}
|
||||
|
||||
// Page 0 is far away, should not need prefetch
|
||||
needs, _ = needsPrefetch(s, 0)
|
||||
if needs {
|
||||
t.Error("expected page 0 to not need prefetch")
|
||||
}
|
||||
|
||||
// Page 25 is far away, should not need prefetch
|
||||
needs, _ = needsPrefetch(s, 25)
|
||||
if needs {
|
||||
t.Error("expected page 25 to not need prefetch")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Navigate To Directory ---
|
||||
|
||||
func TestNavigateToDirectory(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.CurrentPath = "/old/path"
|
||||
s.ScrollIndex = 100
|
||||
s.SelectedIndex = 5
|
||||
s.Pages[0] = NewPage(0, nil)
|
||||
|
||||
navigateToDirectory(s, "/new/path")
|
||||
|
||||
if s.CurrentPath != "/new/path" {
|
||||
t.Errorf("expected CurrentPath=/new/path, got %s", s.CurrentPath)
|
||||
}
|
||||
if s.ScrollIndex != 0 {
|
||||
t.Errorf("expected ScrollIndex=0, got %d", s.ScrollIndex)
|
||||
}
|
||||
if len(s.Pages) != 0 {
|
||||
t.Errorf("expected Pages to be empty, got %d", len(s.Pages))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Compute Total Pages ---
|
||||
|
||||
func TestComputeTotalPages(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
|
||||
s.TotalEntries = 0
|
||||
if pages := computeTotalPages(s); pages != 0 {
|
||||
t.Errorf("expected 0 pages for 0 entries, got %d", pages)
|
||||
}
|
||||
|
||||
s.TotalEntries = 100
|
||||
if pages := computeTotalPages(s); pages != 1 {
|
||||
t.Errorf("expected 1 page for 100 entries, got %d", pages)
|
||||
}
|
||||
|
||||
s.TotalEntries = 101
|
||||
if pages := computeTotalPages(s); pages != 2 {
|
||||
t.Errorf("expected 2 pages for 101 entries, got %d", pages)
|
||||
}
|
||||
|
||||
s.TotalEntries = 250
|
||||
if pages := computeTotalPages(s); pages != 3 {
|
||||
t.Errorf("expected 3 pages for 250 entries, got %d", pages)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Clamp Scroll Index ---
|
||||
|
||||
func TestClampScrollIndex(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 500
|
||||
s.VisibleCount = 20
|
||||
|
||||
// Normal case
|
||||
s.ScrollIndex = 100
|
||||
clampScrollIndex(s)
|
||||
if s.ScrollIndex != 100 {
|
||||
t.Errorf("expected ScrollIndex=100, got %d", s.ScrollIndex)
|
||||
}
|
||||
|
||||
// Below minimum
|
||||
s.ScrollIndex = -10
|
||||
clampScrollIndex(s)
|
||||
if s.ScrollIndex != 0 {
|
||||
t.Errorf("expected ScrollIndex=0, got %d", s.ScrollIndex)
|
||||
}
|
||||
|
||||
// Above maximum
|
||||
s.ScrollIndex = 1000
|
||||
clampScrollIndex(s)
|
||||
if s.ScrollIndex != 480 {
|
||||
t.Errorf("expected ScrollIndex=480, got %d", s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Filter Entries By Query ---
|
||||
|
||||
func TestFilterEntriesByQuery(t *testing.T) {
|
||||
entries := []Entry{
|
||||
NewEntry("/path/file0.txt", "file0.txt", 0, time.Time{}, false),
|
||||
NewEntry("/path/file1.txt", "file1.txt", 100, time.Time{}, false),
|
||||
NewEntry("/path/file2.txt", "file2.txt", 200, time.Time{}, false),
|
||||
NewEntry("/path/file10.txt", "file10.txt", 1000, time.Time{}, false),
|
||||
NewEntry("/path/file100.txt", "file100.txt", 10000, time.Time{}, false),
|
||||
}
|
||||
|
||||
// Search for "file1" - should match file1.txt, file10.txt, file100.txt
|
||||
results := filterEntriesByQuery(entries, "file1")
|
||||
|
||||
if len(results) != 3 {
|
||||
t.Errorf("expected 3 results for 'file1', got %d", len(results))
|
||||
}
|
||||
|
||||
expectedNames := map[string]bool{"file1.txt": true, "file10.txt": true, "file100.txt": true}
|
||||
for _, idx := range results {
|
||||
if !expectedNames[entries[idx].Name] {
|
||||
t.Errorf("unexpected result: %s", entries[idx].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Filter Entries By Query - Empty Query ---
|
||||
|
||||
func TestFilterEntriesByQuery_EmptyQuery(t *testing.T) {
|
||||
entries := []Entry{
|
||||
NewEntry("/a", "a.txt", 100, time.Time{}, false),
|
||||
NewEntry("/b", "b.txt", 200, time.Time{}, false),
|
||||
}
|
||||
|
||||
results := filterEntriesByQuery(entries, "")
|
||||
|
||||
if len(results) != 0 {
|
||||
t.Errorf("expected 0 results for empty query, got %d", len(results))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Filter Entries By Query - No Match ---
|
||||
|
||||
func TestFilterEntriesByQuery_NoMatch(t *testing.T) {
|
||||
entries := []Entry{
|
||||
NewEntry("/a", "a.txt", 100, time.Time{}, false),
|
||||
NewEntry("/b", "b.txt", 200, time.Time{}, false),
|
||||
}
|
||||
|
||||
results := filterEntriesByQuery(entries, "zzz")
|
||||
|
||||
if len(results) != 0 {
|
||||
t.Errorf("expected 0 results for 'zzz', got %d", len(results))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Filter Entries By Query - Case Insensitive ---
|
||||
|
||||
func TestFilterEntriesByQuery_CaseInsensitive(t *testing.T) {
|
||||
entries := []Entry{
|
||||
NewEntry("/a", "Apple.txt", 100, time.Time{}, false),
|
||||
NewEntry("/b", "banana.txt", 200, time.Time{}, false),
|
||||
}
|
||||
|
||||
results := filterEntriesByQuery(entries, "apple")
|
||||
|
||||
if len(results) != 1 {
|
||||
t.Errorf("expected 1 result for 'apple', got %d", len(results))
|
||||
}
|
||||
if results[0] != 0 {
|
||||
t.Errorf("expected result at index 0, got %d", results[0])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package browser
|
||||
|
||||
// HandleScroll updates the browser scroll index by the given delta (in entries).
|
||||
// Clamps to valid bounds and triggers prefetch/eviction as needed.
|
||||
func HandleScroll(s *BrowserState, delta int) {
|
||||
s.ScrollIndex += delta
|
||||
|
||||
// Clamp to valid bounds
|
||||
clampScrollIndex(s)
|
||||
|
||||
// Trigger eviction of distant pages
|
||||
s.EvictPages()
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DirectoryIndex holds a cached index of a directory's contents.
|
||||
// Per design: index stores raw metadata; sorting is pre-computed via position maps.
|
||||
type DirectoryIndex struct {
|
||||
Path string `json:"path"`
|
||||
Mtime time.Time `json:"mtime"`
|
||||
EntryCount int `json:"entry_count"`
|
||||
Entries []Entry `json:"entries"`
|
||||
SortOrders map[string][]int `json:"sort_orders,omitempty"` // key: "name_asc", "name_desc", etc.
|
||||
}
|
||||
|
||||
// getCachePath returns the path to the cached index file for a directory.
|
||||
func getCachePath(dirPath string) string {
|
||||
// Use .pad/indices/ relative to the directory being indexed
|
||||
indicesDir := filepath.Join(dirPath, ".pad", "indices")
|
||||
// Simple hash: use the directory path itself (URL-encoded style)
|
||||
encoded := strings.NewReplacer("/", "_", "\\", "_").Replace(dirPath)
|
||||
return filepath.Join(indicesDir, fmt.Sprintf("browser_%s.json", encoded))
|
||||
}
|
||||
|
||||
// buildIndex reads the directory and produces an index with pre-computed position maps.
|
||||
// Sorting happens at index build time, not during frame rendering.
|
||||
func buildIndex(dirPath string) (*DirectoryIndex, error) {
|
||||
// Try to load from cache first
|
||||
if cached, ok := loadCachedIndex(dirPath); ok {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
// 1. Read directory entries
|
||||
entries, err := os.ReadDir(dirPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("browser: read dir %s: %w", dirPath, err)
|
||||
}
|
||||
|
||||
// 2. Convert to Entry structs (unsorted)
|
||||
var browserEntries []Entry
|
||||
for _, e := range entries {
|
||||
// Skip hidden directories like .pad
|
||||
if e.Name() == ".pad" || e.Name() == ".git" {
|
||||
continue
|
||||
}
|
||||
info, err := e.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
browserEntries = append(browserEntries, Entry{
|
||||
Path: filepath.Join(dirPath, e.Name()),
|
||||
Name: e.Name(),
|
||||
Size: info.Size(),
|
||||
ModTime: info.ModTime(),
|
||||
IsDir: info.IsDir(),
|
||||
})
|
||||
}
|
||||
|
||||
// 3. Build position maps for all sort modes
|
||||
sortOrders := make(map[string][]int)
|
||||
for mode := SortMode(0); mode < SortMode(modeCount()); mode++ {
|
||||
key := sortModeKey(mode)
|
||||
if key != "" {
|
||||
sortOrders[key] = buildPositionMap(browserEntries, mode)
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Build index (unsorted entries with pre-computed position maps)
|
||||
dirInfo, err := os.Stat(dirPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("browser: stat dir %s: %w", dirPath, err)
|
||||
}
|
||||
|
||||
idx := &DirectoryIndex{
|
||||
Path: dirPath,
|
||||
Mtime: dirInfo.ModTime(),
|
||||
EntryCount: len(browserEntries),
|
||||
Entries: browserEntries,
|
||||
SortOrders: sortOrders,
|
||||
}
|
||||
|
||||
// 5. Write to cache
|
||||
cacheIndex(idx)
|
||||
|
||||
return idx, nil
|
||||
}
|
||||
|
||||
// buildPositionMap creates a sorted index → raw index mapping.
|
||||
// The returned slice maps sorted positions to raw entry indices.
|
||||
// Uses sort.SliceStable for O(n log n) performance on large directories.
|
||||
func buildPositionMap(entries []Entry, mode SortMode) []int {
|
||||
n := len(entries)
|
||||
indices := make([]int, n)
|
||||
for i := range indices {
|
||||
indices[i] = i
|
||||
}
|
||||
|
||||
// Sort indices based on entry comparison
|
||||
cmp := comparator(mode)
|
||||
sort.SliceStable(indices, func(i, j int) bool {
|
||||
a, b := entries[indices[i]], entries[indices[j]]
|
||||
return cmp(a, b) < 0
|
||||
})
|
||||
|
||||
return indices
|
||||
}
|
||||
|
||||
// sortModeKey converts a SortMode to its JSON key string.
|
||||
func sortModeKey(mode SortMode) string {
|
||||
switch mode {
|
||||
case SortModeNameAsc:
|
||||
return "name_asc"
|
||||
case SortModeNameDesc:
|
||||
return "name_desc"
|
||||
case SortModeDateAsc:
|
||||
return "date_asc"
|
||||
case SortModeDateDesc:
|
||||
return "date_desc"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// modeCount returns the total number of sort modes (4).
|
||||
func modeCount() int {
|
||||
return int(SortModeDateDesc) + 1
|
||||
}
|
||||
|
||||
// loadCachedIndex attempts to load a cached index from disk.
|
||||
// Returns the index and true if valid, or nil and false if not.
|
||||
func loadCachedIndex(dirPath string) (*DirectoryIndex, bool) {
|
||||
cachePath := getCachePath(dirPath)
|
||||
|
||||
data, err := os.ReadFile(cachePath)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
var idx DirectoryIndex
|
||||
if err := json.Unmarshal(data, &idx); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Check if directory mtime has changed since cache was written
|
||||
dirInfo, err := os.Stat(dirPath)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// If mtime matches, cache is valid
|
||||
if idx.Mtime.Equal(dirInfo.ModTime()) {
|
||||
return &idx, true
|
||||
}
|
||||
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// cacheIndex writes the directory index to the cache file.
|
||||
func cacheIndex(idx *DirectoryIndex) {
|
||||
cachePath := getCachePath(idx.Path)
|
||||
|
||||
// Ensure directory exists
|
||||
indicesDir := filepath.Dir(cachePath)
|
||||
if err := os.MkdirAll(indicesDir, 0755); err != nil {
|
||||
// Non-fatal; continue without caching
|
||||
return
|
||||
}
|
||||
|
||||
data, err := json.Marshal(idx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Write to temp file first, then rename for atomicity
|
||||
tmpPath := cachePath + ".tmp"
|
||||
if err := os.WriteFile(tmpPath, data, 0644); err != nil {
|
||||
return
|
||||
}
|
||||
os.Rename(tmpPath, cachePath)
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// --- Fixture setup ---
|
||||
|
||||
type testEntry struct {
|
||||
name string
|
||||
isDir bool
|
||||
size int64
|
||||
}
|
||||
|
||||
func setupTestDir(t *testing.T, entries []testEntry) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
|
||||
for _, e := range entries {
|
||||
path := filepath.Join(dir, e.name)
|
||||
if e.isDir {
|
||||
err := os.Mkdir(path, 0755)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create dir %s: %v", e.name, err)
|
||||
}
|
||||
} else {
|
||||
err := os.WriteFile(path, make([]byte, e.size), 0644)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create file %s: %v", e.name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
// --- Test: Build Index - Empty Dir ---
|
||||
|
||||
func TestBuildIndex_EmptyDir(t *testing.T) {
|
||||
dir := setupTestDir(t, nil)
|
||||
|
||||
idx, err := buildIndex(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("buildIndex(empty) returned error: %v", err)
|
||||
}
|
||||
if idx.EntryCount != 0 {
|
||||
t.Errorf("expected EntryCount=0, got %d", idx.EntryCount)
|
||||
}
|
||||
if len(idx.Entries) != 0 {
|
||||
t.Errorf("expected 0 entries, got %d", len(idx.Entries))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Build Index - Unsorted (raw metadata) ---
|
||||
// Per design: index stores raw metadata; sorting happens at page-load time.
|
||||
|
||||
func TestBuildIndex_UnsortedRawMetadata(t *testing.T) {
|
||||
dir := setupTestDir(t, []testEntry{
|
||||
{name: "Zebra.txt", size: 100},
|
||||
{name: "apple.txt", size: 200},
|
||||
{name: "Banana.txt", size: 300},
|
||||
{name: "cherry.txt", size: 400},
|
||||
})
|
||||
|
||||
idx, err := buildIndex(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("buildIndex returned error: %v", err)
|
||||
}
|
||||
|
||||
// Index should contain all entries (order not guaranteed - raw metadata)
|
||||
if len(idx.Entries) != 4 {
|
||||
t.Fatalf("expected 4 entries, got %d", len(idx.Entries))
|
||||
}
|
||||
|
||||
// Verify all entries are present (regardless of order)
|
||||
names := make(map[string]bool)
|
||||
for _, e := range idx.Entries {
|
||||
names[e.Name] = true
|
||||
}
|
||||
for _, want := range []string{"Zebra.txt", "apple.txt", "Banana.txt", "cherry.txt"} {
|
||||
if !names[want] {
|
||||
t.Errorf("expected entry %q not found in index", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Build Index - Dirs and Files Both Present ---
|
||||
// Per design: index stores raw metadata; dir/file ordering happens at page-load time.
|
||||
|
||||
func TestBuildIndex_DirsAndFilesPresent(t *testing.T) {
|
||||
dir := setupTestDir(t, []testEntry{
|
||||
{name: "file.txt", size: 100},
|
||||
{name: "adir", isDir: true},
|
||||
{name: "another.txt", size: 200},
|
||||
{name: "bdir", isDir: true},
|
||||
})
|
||||
|
||||
idx, err := buildIndex(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("buildIndex returned error: %v", err)
|
||||
}
|
||||
|
||||
// Both dirs and files should be present
|
||||
var gotDirs, gotFiles int
|
||||
for _, e := range idx.Entries {
|
||||
if e.IsDir {
|
||||
gotDirs++
|
||||
} else {
|
||||
gotFiles++
|
||||
}
|
||||
}
|
||||
if gotDirs != 2 {
|
||||
t.Errorf("expected 2 directories, got %d", gotDirs)
|
||||
}
|
||||
if gotFiles != 2 {
|
||||
t.Errorf("expected 2 files, got %d", gotFiles)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Build Index - Cache Written ---
|
||||
|
||||
func TestBuildIndex_CacheWritten(t *testing.T) {
|
||||
dir := setupTestDir(t, []testEntry{
|
||||
{name: "test.txt", size: 100},
|
||||
})
|
||||
|
||||
_, err := buildIndex(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("buildIndex returned error: %v", err)
|
||||
}
|
||||
|
||||
// Verify cache file exists
|
||||
cachePath := getCachePath(dir)
|
||||
if _, err := os.Stat(cachePath); os.IsNotExist(err) {
|
||||
t.Errorf("expected cache file at %s, but it does not exist", cachePath)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Build Index - Cache Invalidated On Mtime Change ---
|
||||
|
||||
func TestBuildIndex_CacheInvalidatedOnMtimeChange(t *testing.T) {
|
||||
dir := setupTestDir(t, []testEntry{
|
||||
{name: "test.txt", size: 100},
|
||||
})
|
||||
|
||||
// First build
|
||||
idx1, err := buildIndex(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("first buildIndex returned error: %v", err)
|
||||
}
|
||||
|
||||
// Modify directory (add a file)
|
||||
newFile := filepath.Join(dir, "newfile.txt")
|
||||
if err := os.WriteFile(newFile, []byte("new"), 0644); err != nil {
|
||||
t.Fatalf("failed to create new file: %v", err)
|
||||
}
|
||||
|
||||
// Second build should detect change and rebuild
|
||||
idx2, err := buildIndex(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("second buildIndex returned error: %v", err)
|
||||
}
|
||||
|
||||
if idx2.EntryCount <= idx1.EntryCount {
|
||||
t.Errorf("expected entry count to increase after adding file; before=%d, after=%d",
|
||||
idx1.EntryCount, idx2.EntryCount)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Build Index - Cache Reused When Unchanged ---
|
||||
|
||||
func TestBuildIndex_CacheReusedWhenUnchanged(t *testing.T) {
|
||||
dir := setupTestDir(t, []testEntry{
|
||||
{name: "test.txt", size: 100},
|
||||
})
|
||||
|
||||
// First build
|
||||
idx1, err := buildIndex(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("first buildIndex returned error: %v", err)
|
||||
}
|
||||
|
||||
// Second build (no changes)
|
||||
idx2, err := buildIndex(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("second buildIndex returned error: %v", err)
|
||||
}
|
||||
|
||||
if idx1.EntryCount != idx2.EntryCount {
|
||||
t.Errorf("expected same entry count; first=%d, second=%d",
|
||||
idx1.EntryCount, idx2.EntryCount)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Build Index - Large Directory ---
|
||||
|
||||
func TestBuildIndex_LargeDirectory(t *testing.T) {
|
||||
const count = 10000
|
||||
entries := make([]testEntry, count)
|
||||
for i := 0; i < count; i++ {
|
||||
entries[i] = testEntry{
|
||||
name: fmt.Sprintf("file_%05d.txt", i),
|
||||
size: int64(i * 10),
|
||||
}
|
||||
}
|
||||
dir := setupTestDir(t, entries)
|
||||
|
||||
start := time.Now()
|
||||
idx, err := buildIndex(dir)
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("buildIndex returned error: %v", err)
|
||||
}
|
||||
if idx.EntryCount != count {
|
||||
t.Errorf("expected %d entries, got %d", count, idx.EntryCount)
|
||||
}
|
||||
|
||||
// Time budget: 5 seconds for 10k entries
|
||||
if elapsed > 5*time.Second {
|
||||
t.Errorf("buildIndex took %v, expected < 5s", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"pad/internal/ui"
|
||||
)
|
||||
|
||||
// BrowserLayout computes the element tree for the browser (file listing) page.
|
||||
// Pure function: (screen dimensions, browser state) → []ui.Element
|
||||
func BrowserLayout(screenW, screenH ui.Dp, state *BrowserState) []ui.Element {
|
||||
margin := ui.Dp(10)
|
||||
contentWidth := screenW - margin*2
|
||||
|
||||
// --- Header bar: directory path + sort toggle ---
|
||||
headerHeight := ui.Dp(24)
|
||||
headerRegion := ui.Region{
|
||||
X: margin, Y: margin,
|
||||
W: contentWidth, H: headerHeight,
|
||||
}
|
||||
sortLabel := sortModeLabel(state.SortMode)
|
||||
headerBar := ui.NewContainer(
|
||||
headerRegion,
|
||||
ui.Color{R: 230, G: 230, B: 230, A: 255},
|
||||
[]ui.Element{
|
||||
ui.NewLabel(state.CurrentPath, 14, ui.Region{X: 0, Y: 0, W: contentWidth, H: headerHeight}, ui.AlignStart, "", nil),
|
||||
ui.NewLabel(sortLabel, 12, ui.Region{X: 0, Y: 0, W: contentWidth, H: headerHeight}, ui.AlignEnd, "sort",
|
||||
[]ui.Interaction{{Gesture: ui.Tap, Handler: ToggleSortOrder}}),
|
||||
},
|
||||
)
|
||||
|
||||
// --- Search bar (Gio editor) ---
|
||||
searchHeight := ui.Dp(36)
|
||||
searchY := headerRegion.Y + headerRegion.H + margin/2
|
||||
searchRegion := ui.Region{
|
||||
X: margin, Y: searchY,
|
||||
W: contentWidth, H: searchHeight,
|
||||
}
|
||||
state.SearchEditor.SingleLine = true
|
||||
searchBar := ui.NewGioEditor("search_bar", searchRegion, &state.SearchEditor)
|
||||
|
||||
var searchPlaceholder ui.Element
|
||||
if state.SearchEditor.Len() == 0 {
|
||||
searchPlaceholder = ui.NewLabel("Search…", 14,
|
||||
ui.Region{X: margin + ui.Dp(8), Y: searchY + ui.Dp(8), W: contentWidth - ui.Dp(16), H: searchHeight - ui.Dp(16)},
|
||||
ui.AlignStart, "", nil)
|
||||
}
|
||||
|
||||
// --- ListView ---
|
||||
listY := searchY + searchHeight + margin/2
|
||||
listHeight := screenH - listY - margin
|
||||
listRegion := ui.Region{
|
||||
X: margin, Y: listY,
|
||||
W: contentWidth, H: listHeight,
|
||||
}
|
||||
|
||||
// Compute visible entries
|
||||
visibleEntries := computeVisibleEntries(state)
|
||||
|
||||
// Create a scroll handler that captures the current browser state
|
||||
scrollHandler := func(data any) {
|
||||
delta := data.(int) // entries
|
||||
HandleScroll(state, delta)
|
||||
}
|
||||
|
||||
listView := ui.NewListView(
|
||||
"browser_list",
|
||||
visibleEntries,
|
||||
listRegion,
|
||||
ui.Dp(state.ScrollIndex)*ui.Dp(48), // scroll offset in pixels
|
||||
state.SelectedIndex,
|
||||
[]ui.Interaction{{Gesture: ui.Scroll, Handler: scrollHandler}},
|
||||
)
|
||||
|
||||
elems := []ui.Element{headerBar, searchBar}
|
||||
if searchPlaceholder != nil {
|
||||
elems = append(elems, searchPlaceholder)
|
||||
}
|
||||
elems = append(elems, listView)
|
||||
return elems
|
||||
}
|
||||
|
||||
// sortModeLabel returns the display label for the given sort mode.
|
||||
func sortModeLabel(mode SortMode) string {
|
||||
switch mode {
|
||||
case SortModeNameAsc:
|
||||
return "Name ↑"
|
||||
case SortModeNameDesc:
|
||||
return "Name ↓"
|
||||
case SortModeDateAsc:
|
||||
return "Date ↑"
|
||||
case SortModeDateDesc:
|
||||
return "Date ↓"
|
||||
default:
|
||||
return "Name ↑"
|
||||
}
|
||||
}
|
||||
|
||||
// ToggleSortOrder cycles the browser sort mode through four modes.
|
||||
func ToggleSortOrder(data any) {
|
||||
if currentBrowserState == nil {
|
||||
return
|
||||
}
|
||||
currentBrowserState.SortMode = (currentBrowserState.SortMode + 1) % 4
|
||||
currentBrowserState.ScrollIndex = 0 // reset scroll on sort change
|
||||
}
|
||||
|
||||
// currentBrowserState is set by the editor before calling BrowserLayout.
|
||||
// Used by handlers that need access to the browser state.
|
||||
var currentBrowserState *BrowserState
|
||||
|
||||
// SetBrowserState sets the global browser state reference for handlers.
|
||||
func SetBrowserState(s *BrowserState) {
|
||||
currentBrowserState = s
|
||||
}
|
||||
|
||||
// computeVisibleEntries builds the list of ui.ListItem entries that should be
|
||||
// rendered based on the current scroll position and visible count.
|
||||
func computeVisibleEntries(state *BrowserState) []ui.ListItem {
|
||||
if state.TotalEntries == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
startIndex := state.ScrollIndex
|
||||
endIndex := startIndex + state.VisibleCount
|
||||
if endIndex > state.TotalEntries {
|
||||
endIndex = state.TotalEntries
|
||||
}
|
||||
|
||||
var items []ui.ListItem
|
||||
for idx := startIndex; idx < endIndex; idx++ {
|
||||
entry, ok := getEntryByIndex(state, idx)
|
||||
if !ok {
|
||||
// Page not loaded yet; add placeholder
|
||||
items = append(items, ui.ListItem{
|
||||
Text: "...",
|
||||
Subtext: "Loading...",
|
||||
})
|
||||
continue
|
||||
}
|
||||
item := entry.ToListItem()
|
||||
item.Selected = (idx == state.SelectedIndex)
|
||||
items = append(items, item)
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pad/internal/ui"
|
||||
)
|
||||
|
||||
// --- Helper: create a browser state with known entries ---
|
||||
|
||||
func makeTestState(t *testing.T, entryCount int, scrollIndex int, visibleCount int) *BrowserState {
|
||||
t.Helper()
|
||||
s := NewBrowserState()
|
||||
s.CurrentPath = "/test/path"
|
||||
s.ScrollIndex = scrollIndex
|
||||
s.VisibleCount = visibleCount
|
||||
s.TotalEntries = entryCount
|
||||
|
||||
entries := make([]Entry, entryCount)
|
||||
for i := 0; i < entryCount; i++ {
|
||||
entries[i] = NewEntry(
|
||||
fmt.Sprintf("/test/path/file%d.txt", i),
|
||||
fmt.Sprintf("file%d.txt", i),
|
||||
int64(i*100),
|
||||
time.Time{},
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
// Build position map for the default sort mode (NameAsc)
|
||||
s.SortIndex = &DirectoryIndex{
|
||||
Entries: entries,
|
||||
SortOrders: map[string][]int{"name_asc": buildPositionMap(entries, SortModeNameAsc)},
|
||||
}
|
||||
|
||||
// Load pages
|
||||
for pageIdx := 0; pageIdx <= entryCount/PageSize; pageIdx++ {
|
||||
p := loadPageFromIndex(s, pageIdx)
|
||||
if p != nil {
|
||||
s.Pages[pageIdx] = p
|
||||
}
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// --- Helper: find ListView from elements ---
|
||||
|
||||
func findListView(elements []ui.Element) (ui.ListView, bool) {
|
||||
for _, el := range elements {
|
||||
if lv, ok := el.(ui.ListView); ok {
|
||||
return lv, true
|
||||
}
|
||||
}
|
||||
return ui.ListView{}, false
|
||||
}
|
||||
|
||||
// --- Test: Browser Layout - Element Count ---
|
||||
|
||||
func TestBrowserLayout_ElementCount(t *testing.T) {
|
||||
s := makeTestState(t, 200, 0, 20)
|
||||
|
||||
elements := BrowserLayout(ui.Dp(800), ui.Dp(1200), s)
|
||||
|
||||
// Should produce: header + search bar + list view = 3 elements
|
||||
if len(elements) < 3 {
|
||||
t.Errorf("expected at least 3 elements, got %d", len(elements))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Browser Layout - Header Region ---
|
||||
|
||||
func TestBrowserLayout_HeaderRegion(t *testing.T) {
|
||||
s := makeTestState(t, 200, 0, 20)
|
||||
|
||||
elements := BrowserLayout(ui.Dp(800), ui.Dp(1200), s)
|
||||
|
||||
// First element should be the header container
|
||||
if len(elements) == 0 {
|
||||
t.Fatal("no elements returned")
|
||||
}
|
||||
|
||||
header := elements[0]
|
||||
region := header.Region()
|
||||
|
||||
// Header should be near the top
|
||||
if region.Y > ui.Dp(50) {
|
||||
t.Errorf("expected header Y <= 50, got %d", int(region.Y))
|
||||
}
|
||||
|
||||
// Header should span most of the width
|
||||
if region.W < ui.Dp(700) {
|
||||
t.Errorf("expected header W >= 700, got %d", int(region.W))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Browser Layout - List Region ---
|
||||
|
||||
func TestBrowserLayout_ListRegion(t *testing.T) {
|
||||
s := makeTestState(t, 200, 0, 20)
|
||||
|
||||
elements := BrowserLayout(ui.Dp(800), ui.Dp(1200), s)
|
||||
|
||||
listView, found := findListView(elements)
|
||||
if !found {
|
||||
t.Fatal("ListView element not found in layout")
|
||||
}
|
||||
|
||||
region := listView.Region()
|
||||
|
||||
// List should be below the header and search bar
|
||||
if region.Y < ui.Dp(50) {
|
||||
t.Errorf("expected list Y >= 50, got %d", int(region.Y))
|
||||
}
|
||||
|
||||
// List should have significant height
|
||||
if region.H < ui.Dp(500) {
|
||||
t.Errorf("expected list H >= 500, got %d", int(region.H))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Browser Layout - Visible Entries Count ---
|
||||
|
||||
func TestBrowserLayout_VisibleEntriesCount(t *testing.T) {
|
||||
s := makeTestState(t, 500, 100, 20)
|
||||
|
||||
elements := BrowserLayout(ui.Dp(800), ui.Dp(1200), s)
|
||||
|
||||
listView, found := findListView(elements)
|
||||
if !found {
|
||||
t.Fatal("ListView element not found in layout")
|
||||
}
|
||||
|
||||
// Should only render visible entries (approximately VisibleCount)
|
||||
// Allow some tolerance for partial pages
|
||||
maxExpected := s.VisibleCount + PageSize
|
||||
if len(listView.Items) > maxExpected {
|
||||
t.Errorf("expected at most %d visible items, got %d", maxExpected, len(listView.Items))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Browser Layout - Empty Directory ---
|
||||
|
||||
func TestBrowserLayout_EmptyDirectory(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.CurrentPath = "/empty/dir"
|
||||
s.TotalEntries = 0
|
||||
|
||||
elements := BrowserLayout(ui.Dp(800), ui.Dp(1200), s)
|
||||
|
||||
if len(elements) < 3 {
|
||||
t.Errorf("expected at least 3 elements for empty dir, got %d", len(elements))
|
||||
}
|
||||
|
||||
listView, found := findListView(elements)
|
||||
if !found {
|
||||
t.Fatal("ListView element not found in layout")
|
||||
}
|
||||
|
||||
if len(listView.Items) != 0 {
|
||||
t.Errorf("expected 0 items for empty directory, got %d", len(listView.Items))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Browser Layout - Single Entry ---
|
||||
|
||||
func TestBrowserLayout_SingleEntry(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.CurrentPath = "/test"
|
||||
s.TotalEntries = 1
|
||||
s.VisibleCount = 20
|
||||
|
||||
entries := []Entry{
|
||||
NewEntry("/test/only.txt", "only.txt", 1024, time.Time{}, false),
|
||||
}
|
||||
s.Pages[0] = NewPage(0, entries)
|
||||
|
||||
elements := BrowserLayout(ui.Dp(800), ui.Dp(1200), s)
|
||||
|
||||
listView, found := findListView(elements)
|
||||
if !found {
|
||||
t.Fatal("ListView element not found in layout")
|
||||
}
|
||||
|
||||
if len(listView.Items) != 1 {
|
||||
t.Errorf("expected 1 item, got %d", len(listView.Items))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Browser Layout - Partial Page ---
|
||||
|
||||
func TestBrowserLayout_PartialPage(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.CurrentPath = "/test"
|
||||
s.TotalEntries = 150 // 1 full page + 50 in second page
|
||||
s.ScrollIndex = 120 // Near the end
|
||||
s.VisibleCount = 20
|
||||
|
||||
entries := make([]Entry, 150)
|
||||
for i := 0; i < 150; i++ {
|
||||
entries[i] = NewEntry(
|
||||
fmt.Sprintf("/test/file%d.txt", i),
|
||||
fmt.Sprintf("file%d.txt", i),
|
||||
int64(i*100),
|
||||
time.Time{},
|
||||
false,
|
||||
)
|
||||
}
|
||||
s.Pages[0] = NewPage(0, entries[:100])
|
||||
s.Pages[1] = NewPage(1, entries[100:])
|
||||
|
||||
elements := BrowserLayout(ui.Dp(800), ui.Dp(1200), s)
|
||||
|
||||
listView, found := findListView(elements)
|
||||
if !found {
|
||||
t.Fatal("ListView element not found in layout")
|
||||
}
|
||||
|
||||
// Should have entries from the partial page
|
||||
if len(listView.Items) == 0 {
|
||||
t.Error("expected items from partial page")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Browser Layout - Unloaded Page Shows Placeholder ---
|
||||
|
||||
func TestBrowserLayout_UnloadedPage(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.CurrentPath = "/test"
|
||||
s.TotalEntries = 500
|
||||
s.ScrollIndex = 250
|
||||
s.VisibleCount = 20
|
||||
|
||||
// Only load page 0, not page 2 or 3
|
||||
entries := make([]Entry, 100)
|
||||
s.Pages[0] = NewPage(0, entries)
|
||||
|
||||
elements := BrowserLayout(ui.Dp(800), ui.Dp(1200), s)
|
||||
|
||||
// Layout should not crash with unloaded pages
|
||||
if len(elements) < 3 {
|
||||
t.Errorf("expected at least 3 elements, got %d", len(elements))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Browser Layout - With Search Query ---
|
||||
|
||||
func TestBrowserLayout_WithSearchQuery(t *testing.T) {
|
||||
s := makeTestState(t, 100, 0, 20)
|
||||
s.Query = "file1"
|
||||
|
||||
// Set up search results
|
||||
for i := 0; i < s.TotalEntries; i++ {
|
||||
if i == 1 || i == 10 || i == 11 || i == 12 || i == 13 || i == 14 || i == 15 || i == 16 || i == 17 || i == 18 || i == 19 {
|
||||
s.SearchResults = append(s.SearchResults, i)
|
||||
}
|
||||
}
|
||||
|
||||
elements := BrowserLayout(ui.Dp(800), ui.Dp(1200), s)
|
||||
|
||||
// Should still produce valid layout
|
||||
if len(elements) < 3 {
|
||||
t.Errorf("expected at least 3 elements with search, got %d", len(elements))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Browser Layout - Screen Dimensions ---
|
||||
|
||||
func TestBrowserLayout_ScreenDimensions(t *testing.T) {
|
||||
s := makeTestState(t, 100, 0, 20)
|
||||
|
||||
// Test with different screen sizes
|
||||
for _, w := range []ui.Dp{400, 800, 1200} {
|
||||
for _, h := range []ui.Dp{600, 1200, 1800} {
|
||||
elements := BrowserLayout(w, h, s)
|
||||
|
||||
if len(elements) < 3 {
|
||||
t.Errorf("layout failed for %dx%d: expected >= 3 elements, got %d", int(w), int(h), len(elements))
|
||||
}
|
||||
|
||||
// All elements should fit within screen
|
||||
for _, el := range elements {
|
||||
region := el.Region()
|
||||
if region.X+region.W > w {
|
||||
t.Errorf("element exceeds screen width at %dx%d", int(w), int(h))
|
||||
}
|
||||
if region.Y+region.H > h {
|
||||
t.Errorf("element exceeds screen height at %dx%d", int(w), int(h))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// --- Test: Scroll Clamp Minimum ---
|
||||
|
||||
func TestScrollClamp_Minimum(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 500
|
||||
s.VisibleCount = 20
|
||||
|
||||
// Set scroll index below minimum
|
||||
s.ScrollIndex = -10
|
||||
|
||||
// Apply scroll clamp
|
||||
HandleScroll(s, -5)
|
||||
|
||||
// ScrollIndex should be clamped to 0
|
||||
if s.ScrollIndex != 0 {
|
||||
t.Errorf("expected ScrollIndex=0 (clamped), got %d", s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Scroll Clamp Maximum ---
|
||||
|
||||
func TestScrollClamp_Maximum(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 500
|
||||
s.VisibleCount = 20
|
||||
|
||||
// Set scroll index above maximum
|
||||
s.ScrollIndex = 1000
|
||||
|
||||
// Apply scroll clamp
|
||||
HandleScroll(s, 100)
|
||||
|
||||
// ScrollIndex should be clamped to max (TotalEntries - VisibleCount)
|
||||
maxScroll := s.TotalEntries - s.VisibleCount
|
||||
if s.ScrollIndex != maxScroll {
|
||||
t.Errorf("expected ScrollIndex=%d (clamped to max), got %d", maxScroll, s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Scroll Delta Computation ---
|
||||
|
||||
func TestScrollDelta_Computation(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 1000
|
||||
s.VisibleCount = 20
|
||||
s.ScrollIndex = 100
|
||||
|
||||
// Scroll down by 5 entries (positive delta)
|
||||
HandleScroll(s, 5)
|
||||
|
||||
if s.ScrollIndex != 105 {
|
||||
t.Errorf("expected ScrollIndex=105 after scrolling down 5, got %d", s.ScrollIndex)
|
||||
}
|
||||
|
||||
// Scroll up by 3 entries (negative delta)
|
||||
HandleScroll(s, -3)
|
||||
|
||||
if s.ScrollIndex != 102 {
|
||||
t.Errorf("expected ScrollIndex=102 after scrolling up 3, got %d", s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Scroll Prefetch Triggered ---
|
||||
|
||||
func TestScroll_PrefetchTriggered(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 2000
|
||||
s.VisibleCount = 20
|
||||
s.ScrollIndex = 500 // Page 5
|
||||
|
||||
// Load some pages around current position
|
||||
entries := make([]Entry, 2000)
|
||||
for i := 0; i < 2000; i++ {
|
||||
entries[i] = NewEntry("/test/file.txt", "file.txt", 100, s.TapTimestamp, false)
|
||||
}
|
||||
// Build position map for the default sort mode (NameAsc)
|
||||
s.SortIndex = &DirectoryIndex{
|
||||
Entries: entries,
|
||||
SortOrders: map[string][]int{"name_asc": buildPositionMap(entries, SortModeNameAsc)},
|
||||
}
|
||||
for pageIdx := 3; pageIdx <= 7; pageIdx++ {
|
||||
p := loadPageFromIndex(s, pageIdx)
|
||||
if p != nil {
|
||||
s.Pages[pageIdx] = p
|
||||
}
|
||||
}
|
||||
|
||||
// Record current page count
|
||||
pagesBefore := len(s.Pages)
|
||||
|
||||
// Scroll to trigger prefetch
|
||||
HandleScroll(s, 200) // Scroll to page 7+
|
||||
|
||||
// After scroll, prefetch should have been triggered
|
||||
// (exact behavior depends on implementation)
|
||||
// For now, verify that scroll happened correctly
|
||||
if s.ScrollIndex <= 500 {
|
||||
t.Errorf("expected ScrollIndex > 500 after scrolling, got %d", s.ScrollIndex)
|
||||
}
|
||||
|
||||
// Page count may have increased due to prefetch
|
||||
if len(s.Pages) < pagesBefore {
|
||||
t.Errorf("expected page count to not decrease after scroll, before=%d, after=%d", pagesBefore, len(s.Pages))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Scroll Eviction Triggered ---
|
||||
|
||||
func TestScroll_EvictionTriggered(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 5000
|
||||
s.VisibleCount = 20
|
||||
s.ScrollIndex = 0
|
||||
|
||||
// Load pages at various positions
|
||||
entries := make([]Entry, 5000)
|
||||
for i := 0; i < 5000; i++ {
|
||||
entries[i] = NewEntry("/test/file.txt", "file.txt", 100, s.TapTimestamp, false)
|
||||
}
|
||||
// Build position map for the default sort mode (NameAsc)
|
||||
s.SortIndex = &DirectoryIndex{
|
||||
Entries: entries,
|
||||
SortOrders: map[string][]int{"name_asc": buildPositionMap(entries, SortModeNameAsc)},
|
||||
}
|
||||
for pageIdx := 0; pageIdx <= 10; pageIdx++ {
|
||||
p := loadPageFromIndex(s, pageIdx)
|
||||
if p != nil {
|
||||
s.Pages[pageIdx] = p
|
||||
}
|
||||
}
|
||||
|
||||
// Scroll far away from initial position
|
||||
HandleScroll(s, 4000) // Scroll to page 40+
|
||||
|
||||
// Pages far from current position should be evicted
|
||||
// Check that page 0 was evicted (it's far from page 40)
|
||||
if page, exists := s.Pages[0]; exists && page.Loaded {
|
||||
t.Error("expected page 0 to be evicted after scrolling far away")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Scroll With Search Results ---
|
||||
|
||||
func TestScroll_WithSearchResults(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 100
|
||||
s.VisibleCount = 20
|
||||
s.ScrollIndex = 0
|
||||
|
||||
// Set up search results
|
||||
s.SearchResults = []int{5, 15, 25, 35, 45}
|
||||
|
||||
// Scroll should work normally even with search results
|
||||
HandleScroll(s, 10)
|
||||
|
||||
if s.ScrollIndex != 10 {
|
||||
t.Errorf("expected ScrollIndex=10, got %d", s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Scroll To Beginning ---
|
||||
|
||||
func TestScroll_ToBeginning(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 1000
|
||||
s.VisibleCount = 20
|
||||
s.ScrollIndex = 500
|
||||
|
||||
// Scroll all the way to the beginning
|
||||
HandleScroll(s, -500)
|
||||
|
||||
if s.ScrollIndex != 0 {
|
||||
t.Errorf("expected ScrollIndex=0 at beginning, got %d", s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Scroll To End ---
|
||||
|
||||
func TestScroll_ToEnd(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 1000
|
||||
s.VisibleCount = 20
|
||||
s.ScrollIndex = 0
|
||||
|
||||
// Scroll all the way to the end
|
||||
HandleScroll(s, 1000)
|
||||
|
||||
maxScroll := s.TotalEntries - s.VisibleCount
|
||||
if s.ScrollIndex != maxScroll {
|
||||
t.Errorf("expected ScrollIndex=%d at end, got %d", maxScroll, s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Scroll With Small Directory ---
|
||||
|
||||
func TestScroll_SmallDirectory(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 10 // Smaller than VisibleCount
|
||||
s.VisibleCount = 20
|
||||
s.ScrollIndex = 0
|
||||
|
||||
// Try to scroll down (should be clamped)
|
||||
HandleScroll(s, 100)
|
||||
|
||||
// ScrollIndex should be 0 (can't scroll beyond available entries)
|
||||
if s.ScrollIndex != 0 {
|
||||
t.Errorf("expected ScrollIndex=0 for small directory, got %d", s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Scroll Prefetch Triggered On Page Boundary ---
|
||||
|
||||
func TestScroll_PrefetchTriggeredOnPageBoundary(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 500
|
||||
s.VisibleCount = 20
|
||||
s.ScrollIndex = 90 // Near page boundary (page 0 ends at 100)
|
||||
|
||||
// Load page 0
|
||||
entries := make([]Entry, 500)
|
||||
for i := 0; i < 500; i++ {
|
||||
entries[i] = NewEntry("/test/file.txt", "file.txt", 100, s.TapTimestamp, false)
|
||||
}
|
||||
// Build position map for the default sort mode (NameAsc)
|
||||
s.SortIndex = &DirectoryIndex{
|
||||
Entries: entries,
|
||||
SortOrders: map[string][]int{"name_asc": buildPositionMap(entries, SortModeNameAsc)},
|
||||
}
|
||||
s.Pages[0] = loadPageFromIndex(s, 0)
|
||||
|
||||
// Scroll across page boundary
|
||||
HandleScroll(s, 15) // Should cross into page 1
|
||||
|
||||
// Verify scroll happened
|
||||
if s.ScrollIndex != 105 {
|
||||
t.Errorf("expected ScrollIndex=105, got %d", s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package browser
|
||||
|
||||
import "strings"
|
||||
|
||||
// HandleSearch filters entries by the given query string.
|
||||
// It performs case-insensitive substring matching across all loaded pages.
|
||||
// When query is empty, search results are cleared.
|
||||
// When results are found, ScrollIndex is set to the first match.
|
||||
func HandleSearch(s *BrowserState, query string) {
|
||||
s.Query = query
|
||||
|
||||
// Empty query clears search results; leave ScrollIndex unchanged.
|
||||
if query == "" {
|
||||
s.SearchResults = nil
|
||||
return
|
||||
}
|
||||
|
||||
var results []int
|
||||
queryLower := strings.ToLower(query)
|
||||
|
||||
// Iterate over all loaded pages in order (map iteration is non-deterministic).
|
||||
totalPages := (s.TotalEntries + PageSize - 1) / PageSize
|
||||
for pageIdx := 0; pageIdx < totalPages; pageIdx++ {
|
||||
page, ok := s.Pages[pageIdx]
|
||||
if !ok || !page.Loaded {
|
||||
continue
|
||||
}
|
||||
// Compute the global start index for this page.
|
||||
startIdx := pageIdx * PageSize
|
||||
for i, entry := range page.Entries {
|
||||
globalIdx := startIdx + i
|
||||
if strings.Contains(strings.ToLower(entry.Name), queryLower) {
|
||||
results = append(results, globalIdx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
s.SearchResults = results
|
||||
|
||||
// Jump to first result if any matches found.
|
||||
if len(results) > 0 {
|
||||
s.ScrollIndex = results[0]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// --- Helper: create a browser state with named entries for search testing ---
|
||||
|
||||
func makeSearchState(t *testing.T, entries []Entry) *BrowserState {
|
||||
t.Helper()
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = len(entries)
|
||||
s.VisibleCount = 20
|
||||
s.CurrentPath = "/test"
|
||||
|
||||
// Distribute entries across pages
|
||||
for pageIdx := 0; pageIdx <= (len(entries)-1)/PageSize; pageIdx++ {
|
||||
start := pageIdx * PageSize
|
||||
end := start + PageSize
|
||||
if end > len(entries) {
|
||||
end = len(entries)
|
||||
}
|
||||
s.Pages[pageIdx] = NewPage(pageIdx, entries[start:end])
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// --- Test: Search - Empty Query ---
|
||||
|
||||
func TestSearch_EmptyQuery(t *testing.T) {
|
||||
s := makeSearchState(t, []Entry{
|
||||
NewEntry("/a", "alpha.txt", 100, time.Time{}, false),
|
||||
NewEntry("/b", "beta.txt", 200, time.Time{}, false),
|
||||
NewEntry("/c", "gamma.txt", 300, time.Time{}, false),
|
||||
})
|
||||
|
||||
// First, set a non-empty query and results to simulate prior search
|
||||
s.Query = "alpha"
|
||||
s.SearchResults = []int{0}
|
||||
|
||||
// Clear the search
|
||||
HandleSearch(s, "")
|
||||
|
||||
if s.Query != "" {
|
||||
t.Errorf("expected Query to be empty, got %q", s.Query)
|
||||
}
|
||||
if s.SearchResults != nil {
|
||||
t.Errorf("expected SearchResults to be nil after empty query, got %v", s.SearchResults)
|
||||
}
|
||||
// Scroll should not change when clearing search
|
||||
if s.ScrollIndex != 0 {
|
||||
t.Errorf("expected ScrollIndex=0, got %d", s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Case Insensitive ---
|
||||
|
||||
func TestSearch_CaseInsensitive(t *testing.T) {
|
||||
s := makeSearchState(t, []Entry{
|
||||
NewEntry("/a", "Apple.txt", 100, time.Time{}, false),
|
||||
NewEntry("/b", "banana.txt", 200, time.Time{}, false),
|
||||
NewEntry("/c", "CHERRY.txt", 300, time.Time{}, false),
|
||||
NewEntry("/d", "date.txt", 400, time.Time{}, false),
|
||||
})
|
||||
|
||||
HandleSearch(s, "apple")
|
||||
|
||||
if len(s.SearchResults) != 1 {
|
||||
t.Errorf("expected 1 result for 'apple', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
if len(s.SearchResults) > 0 && s.SearchResults[0] != 0 {
|
||||
t.Errorf("expected first result at index 0 (Apple.txt), got %d", s.SearchResults[0])
|
||||
}
|
||||
|
||||
// Uppercase query should also match lowercase entries
|
||||
HandleSearch(s, "BANANA")
|
||||
|
||||
if len(s.SearchResults) != 1 {
|
||||
t.Errorf("expected 1 result for 'BANANA', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
if len(s.SearchResults) > 0 && s.SearchResults[0] != 1 {
|
||||
t.Errorf("expected first result at index 1 (banana.txt), got %d", s.SearchResults[0])
|
||||
}
|
||||
|
||||
// Mixed case
|
||||
HandleSearch(s, "ChErRy")
|
||||
|
||||
if len(s.SearchResults) != 1 {
|
||||
t.Errorf("expected 1 result for 'ChErRy', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Partial Match ---
|
||||
|
||||
func TestSearch_PartialMatch(t *testing.T) {
|
||||
s := makeSearchState(t, []Entry{
|
||||
NewEntry("/a", "abc.dat", 100, time.Time{}, false),
|
||||
NewEntry("/b", "xabc.dat", 200, time.Time{}, false),
|
||||
NewEntry("/c", "abcdef.dat", 300, time.Time{}, false),
|
||||
NewEntry("/d", "xyz.dat", 400, time.Time{}, false),
|
||||
NewEntry("/e", "bca.dat", 500, time.Time{}, false),
|
||||
})
|
||||
|
||||
HandleSearch(s, "abc")
|
||||
|
||||
// "abc" should match: abc.dat (0), xabc.dat (1), abcdef.dat (2)
|
||||
// Should NOT match: xyz.dat (3), bca.dat (4)
|
||||
if len(s.SearchResults) != 3 {
|
||||
t.Errorf("expected 3 results for 'abc', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
|
||||
expectedIndices := map[int]bool{0: true, 1: true, 2: true}
|
||||
for _, idx := range s.SearchResults {
|
||||
if !expectedIndices[idx] {
|
||||
t.Errorf("unexpected result at index %d", idx)
|
||||
}
|
||||
}
|
||||
|
||||
// Test single character partial match
|
||||
HandleSearch(s, "x")
|
||||
|
||||
// "x" should match: xabc.dat (1), xyz.dat (3)
|
||||
// Should NOT match: abc.dat (0), abcdef.dat (2), bca.dat (4)
|
||||
expectedIndices = map[int]bool{1: true, 3: true}
|
||||
if len(s.SearchResults) != len(expectedIndices) {
|
||||
t.Errorf("expected %d results for 'x', got %d: %v", len(expectedIndices), len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - No Match ---
|
||||
|
||||
func TestSearch_NoMatch(t *testing.T) {
|
||||
s := makeSearchState(t, []Entry{
|
||||
NewEntry("/a", "alpha.txt", 100, time.Time{}, false),
|
||||
NewEntry("/b", "beta.txt", 200, time.Time{}, false),
|
||||
NewEntry("/c", "gamma.txt", 300, time.Time{}, false),
|
||||
})
|
||||
|
||||
HandleSearch(s, "zzz")
|
||||
|
||||
if len(s.SearchResults) != 0 {
|
||||
t.Errorf("expected 0 results for 'zzz', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
// Scroll should not change when there are no results
|
||||
if s.ScrollIndex != 0 {
|
||||
t.Errorf("expected ScrollIndex=0 when no match, got %d", s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Jump To First ---
|
||||
|
||||
func TestSearch_JumpToFirst(t *testing.T) {
|
||||
s := makeSearchState(t, []Entry{
|
||||
NewEntry("/0", "alpha.txt", 100, time.Time{}, false),
|
||||
NewEntry("/1", "beta.txt", 200, time.Time{}, false),
|
||||
NewEntry("/2", "gamma.txt", 300, time.Time{}, false),
|
||||
NewEntry("/3", "delta.txt", 400, time.Time{}, false),
|
||||
NewEntry("/4", "epsilon.txt", 500, time.Time{}, false),
|
||||
})
|
||||
|
||||
// Start with scroll at position 0
|
||||
s.ScrollIndex = 0
|
||||
|
||||
// Search for "delta" — should jump to index 3
|
||||
HandleSearch(s, "delta")
|
||||
|
||||
if len(s.SearchResults) != 1 {
|
||||
t.Fatalf("expected 1 result for 'delta', got %d", len(s.SearchResults))
|
||||
}
|
||||
if s.ScrollIndex != 3 {
|
||||
t.Errorf("expected ScrollIndex=3 (jumped to first match), got %d", s.ScrollIndex)
|
||||
}
|
||||
|
||||
// Verify query is stored
|
||||
if s.Query != "delta" {
|
||||
t.Errorf("expected Query='delta', got %q", s.Query)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Large Directory ---
|
||||
|
||||
func TestSearch_LargeDirectory(t *testing.T) {
|
||||
// Create 10k entries for performance testing
|
||||
const count = 10000
|
||||
entries := make([]Entry, count)
|
||||
for i := 0; i < count; i++ {
|
||||
entries[i] = NewEntry(
|
||||
fmt.Sprintf("/test/file_%05d.txt", i),
|
||||
fmt.Sprintf("file_%05d.txt", i),
|
||||
int64(i*100),
|
||||
time.Time{},
|
||||
false,
|
||||
)
|
||||
}
|
||||
// Sprinkle some entries with "special" in the name
|
||||
for i := 0; i < 50; i++ {
|
||||
idx := i * 200 // spread across the dataset
|
||||
entries[idx] = NewEntry(
|
||||
fmt.Sprintf("/test/special_%03d.txt", i),
|
||||
fmt.Sprintf("special_%03d.txt", i),
|
||||
int64(i*100),
|
||||
time.Time{},
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
s := makeSearchState(t, entries)
|
||||
|
||||
start := time.Now()
|
||||
HandleSearch(s, "special")
|
||||
elapsed := time.Since(start)
|
||||
|
||||
// Should find all 50 "special" entries
|
||||
if len(s.SearchResults) != 50 {
|
||||
t.Errorf("expected 50 results for 'special', got %d", len(s.SearchResults))
|
||||
}
|
||||
|
||||
// Time budget: 100ms for searching 10k entries
|
||||
if elapsed > 100*time.Millisecond {
|
||||
t.Errorf("search took %v, expected < 100ms", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Across Page Boundaries ---
|
||||
|
||||
func TestSearch_AcrossPageBoundaries(t *testing.T) {
|
||||
// Create entries spanning multiple pages
|
||||
entries := make([]Entry, 300)
|
||||
for i := 0; i < 300; i++ {
|
||||
name := fmt.Sprintf("file_%03d.txt", i)
|
||||
// Every 50th file gets "match" in the name
|
||||
if i%50 == 0 {
|
||||
name = fmt.Sprintf("match_%03d.txt", i)
|
||||
}
|
||||
entries[i] = NewEntry(
|
||||
fmt.Sprintf("/test/%s", name),
|
||||
name,
|
||||
int64(i*100),
|
||||
time.Time{},
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
s := makeSearchState(t, entries)
|
||||
|
||||
HandleSearch(s, "match")
|
||||
|
||||
// Should find entries at indices 0, 50, 100, 150, 200, 250
|
||||
// These span pages 0, 0, 1, 1, 2, 2
|
||||
expectedCount := 6
|
||||
if len(s.SearchResults) != expectedCount {
|
||||
t.Errorf("expected %d results spanning pages, got %d: %v", expectedCount, len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
|
||||
expectedIndices := []int{0, 50, 100, 150, 200, 250}
|
||||
for i, expected := range expectedIndices {
|
||||
if i >= len(s.SearchResults) || s.SearchResults[i] != expected {
|
||||
t.Errorf("result[%d] = %d, want %d", i, s.SearchResults[i], expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Special Characters ---
|
||||
|
||||
func TestSearch_SpecialCharacters(t *testing.T) {
|
||||
s := makeSearchState(t, []Entry{
|
||||
NewEntry("/a", "file.name.dat", 100, time.Time{}, false),
|
||||
NewEntry("/b", "file-name.dat", 200, time.Time{}, false),
|
||||
NewEntry("/c", "file_name.dat", 300, time.Time{}, false),
|
||||
NewEntry("/d", "file(name).dat", 400, time.Time{}, false),
|
||||
})
|
||||
|
||||
// Dot should match all entries (all have .dat extension)
|
||||
HandleSearch(s, ".")
|
||||
if len(s.SearchResults) != 4 {
|
||||
t.Errorf("expected 4 results for '.', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
|
||||
// Hyphen should match "file-name.dat" only
|
||||
HandleSearch(s, "-")
|
||||
if len(s.SearchResults) != 1 {
|
||||
t.Errorf("expected 1 result for '-', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
if len(s.SearchResults) > 0 && s.SearchResults[0] != 1 {
|
||||
t.Errorf("expected result at index 1, got %d", s.SearchResults[0])
|
||||
}
|
||||
|
||||
// Underscore should match "file_name.dat" only
|
||||
HandleSearch(s, "_")
|
||||
if len(s.SearchResults) != 1 {
|
||||
t.Errorf("expected 1 result for '_', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
|
||||
// Parentheses should match "file(name).dat" only
|
||||
HandleSearch(s, "(")
|
||||
if len(s.SearchResults) != 1 {
|
||||
t.Errorf("expected 1 result for '(', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Clears Previous Results ---
|
||||
|
||||
func TestSearch_ClearsPreviousResults(t *testing.T) {
|
||||
s := makeSearchState(t, []Entry{
|
||||
NewEntry("/a", "alpha.txt", 100, time.Time{}, false),
|
||||
NewEntry("/b", "beta.txt", 200, time.Time{}, false),
|
||||
NewEntry("/c", "gamma.txt", 300, time.Time{}, false),
|
||||
})
|
||||
|
||||
// First search
|
||||
HandleSearch(s, "alpha")
|
||||
if len(s.SearchResults) != 1 {
|
||||
t.Fatalf("expected 1 result for 'alpha', got %d", len(s.SearchResults))
|
||||
}
|
||||
|
||||
// Second search should replace results, not append
|
||||
HandleSearch(s, "beta")
|
||||
if len(s.SearchResults) != 1 {
|
||||
t.Errorf("expected 1 result after new search, got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
if s.SearchResults[0] != 1 {
|
||||
t.Errorf("expected result at index 1, got %d", s.SearchResults[0])
|
||||
}
|
||||
if s.Query != "beta" {
|
||||
t.Errorf("expected Query='beta', got %q", s.Query)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Only Loaded Pages ---
|
||||
|
||||
func TestSearch_OnlyLoadedPages(t *testing.T) {
|
||||
// Create state with only some pages loaded
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 300
|
||||
s.VisibleCount = 20
|
||||
s.CurrentPath = "/test"
|
||||
|
||||
// Only load page 0 with entries containing "searchme"
|
||||
entries0 := make([]Entry, PageSize)
|
||||
for i := 0; i < PageSize; i++ {
|
||||
name := fmt.Sprintf("file_%03d.txt", i)
|
||||
if i < 5 {
|
||||
name = fmt.Sprintf("searchme_%03d.txt", i)
|
||||
}
|
||||
entries0[i] = NewEntry(fmt.Sprintf("/test/%s", name), name, int64(i*100), time.Time{}, false)
|
||||
}
|
||||
s.Pages[0] = NewPage(0, entries0)
|
||||
|
||||
// Page 1 and 2 are NOT loaded — search should only find results in loaded pages
|
||||
HandleSearch(s, "searchme")
|
||||
|
||||
// Should only find the 5 entries in page 0 (loaded pages only)
|
||||
if len(s.SearchResults) != 5 {
|
||||
t.Errorf("expected 5 results (only from loaded pages), got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Directory Entries ---
|
||||
|
||||
func TestSearch_DirectoryEntries(t *testing.T) {
|
||||
s := makeSearchState(t, []Entry{
|
||||
NewEntry("/a", "mydir", 0, time.Time{}, true),
|
||||
NewEntry("/b", "myfile.txt", 100, time.Time{}, false),
|
||||
NewEntry("/c", "mydir2", 0, time.Time{}, true),
|
||||
NewEntry("/d", "other.txt", 200, time.Time{}, false),
|
||||
})
|
||||
|
||||
// Search should match both files and directories
|
||||
HandleSearch(s, "mydir")
|
||||
|
||||
if len(s.SearchResults) != 2 {
|
||||
t.Errorf("expected 2 results for 'mydir', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Numeric Names ---
|
||||
|
||||
func TestSearch_NumericNames(t *testing.T) {
|
||||
s := makeSearchState(t, []Entry{
|
||||
NewEntry("/a", "123.txt", 100, time.Time{}, false),
|
||||
NewEntry("/b", "456.txt", 200, time.Time{}, false),
|
||||
NewEntry("/c", "1234.txt", 300, time.Time{}, false),
|
||||
NewEntry("/d", "789.txt", 400, time.Time{}, false),
|
||||
})
|
||||
|
||||
HandleSearch(s, "123")
|
||||
|
||||
// Should match "123.txt" (0) and "1234.txt" (2)
|
||||
if len(s.SearchResults) != 2 {
|
||||
t.Errorf("expected 2 results for '123', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Empty Directory ---
|
||||
|
||||
func TestSearch_EmptyDirectory(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 0
|
||||
s.VisibleCount = 20
|
||||
|
||||
HandleSearch(s, "anything")
|
||||
|
||||
if len(s.SearchResults) != 0 {
|
||||
t.Errorf("expected 0 results for empty directory, got %d", len(s.SearchResults))
|
||||
}
|
||||
if s.ScrollIndex != 0 {
|
||||
t.Errorf("expected ScrollIndex=0, got %d", s.ScrollIndex)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test: Search - Whitespace Handling ---
|
||||
|
||||
func TestSearch_WhitespaceHandling(t *testing.T) {
|
||||
s := makeSearchState(t, []Entry{
|
||||
NewEntry("/a", "hello world.txt", 100, time.Time{}, false),
|
||||
NewEntry("/b", "helloworld.txt", 200, time.Time{}, false),
|
||||
NewEntry("/c", "hello.txt", 300, time.Time{}, false),
|
||||
})
|
||||
|
||||
// Search with spaces
|
||||
HandleSearch(s, "hello world")
|
||||
if len(s.SearchResults) != 1 {
|
||||
t.Errorf("expected 1 result for 'hello world', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
|
||||
// Search single word
|
||||
HandleSearch(s, "hello")
|
||||
if len(s.SearchResults) != 3 {
|
||||
t.Errorf("expected 3 results for 'hello', got %d: %v", len(s.SearchResults), s.SearchResults)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SortMode defines how entries should be sorted.
|
||||
type SortMode int
|
||||
|
||||
const (
|
||||
SortModeNameAsc SortMode = iota // Name ascending (A-Z)
|
||||
SortModeNameDesc // Name descending (Z-A)
|
||||
SortModeDateAsc // Date ascending (oldest first)
|
||||
SortModeDateDesc // Date descending (newest first)
|
||||
// Total sort modes: 4
|
||||
)
|
||||
|
||||
// sortEntries sorts entries in-place according to the given SortMode.
|
||||
// Directories and files are interleaved naturally. Case-insensitive
|
||||
// comparison is used for name-based sorting. Equal keys are broken
|
||||
// by name (ascending).
|
||||
func sortEntries(entries []Entry, mode SortMode) {
|
||||
if len(entries) <= 1 {
|
||||
return
|
||||
}
|
||||
|
||||
cmp := comparator(mode)
|
||||
|
||||
sort.SliceStable(entries, func(i, j int) bool {
|
||||
return cmp(entries[i], entries[j]) < 0
|
||||
})
|
||||
}
|
||||
|
||||
// comparator returns a comparison function for the given SortMode.
|
||||
// Returns negative if a < b, zero if equal, positive if a > b.
|
||||
func comparator(mode SortMode) func(a, b Entry) int {
|
||||
switch mode {
|
||||
case SortModeNameAsc:
|
||||
return func(a, b Entry) int {
|
||||
if c := strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name)); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(a.Name, b.Name)
|
||||
}
|
||||
case SortModeNameDesc:
|
||||
return func(a, b Entry) int {
|
||||
if c := strings.Compare(strings.ToLower(b.Name), strings.ToLower(a.Name)); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(b.Name, a.Name)
|
||||
}
|
||||
case SortModeDateAsc:
|
||||
return func(a, b Entry) int {
|
||||
if c := a.ModTime.Compare(b.ModTime); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
|
||||
}
|
||||
case SortModeDateDesc:
|
||||
return func(a, b Entry) int {
|
||||
if c := b.ModTime.Compare(a.ModTime); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
|
||||
}
|
||||
default:
|
||||
// Invalid mode: no-op (preserve order)
|
||||
return func(a, b Entry) int { return 0 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// --- Test helpers ---
|
||||
|
||||
func newUnsortedEntries() []Entry {
|
||||
return []Entry{
|
||||
{Name: "Zebra.txt", Size: 1000, ModTime: time.Date(2024, 1, 15, 0, 0, 0, 0, time.UTC), IsDir: false},
|
||||
{Name: "apple.txt", Size: 500, ModTime: time.Date(2024, 3, 1, 0, 0, 0, 0, time.UTC), IsDir: false},
|
||||
{Name: "MyDir", Size: 0, ModTime: time.Date(2024, 2, 10, 0, 0, 0, 0, time.UTC), IsDir: true},
|
||||
{Name: "banana.txt", Size: 2000, ModTime: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), IsDir: false},
|
||||
{Name: "Cherry.txt", Size: 1500, ModTime: time.Date(2024, 2, 20, 0, 0, 0, 0, time.UTC), IsDir: false},
|
||||
{Name: "adir", Size: 0, ModTime: time.Date(2024, 1, 10, 0, 0, 0, 0, time.UTC), IsDir: true},
|
||||
{Name: "123.txt", Size: 300, ModTime: time.Date(2024, 4, 1, 0, 0, 0, 0, time.UTC), IsDir: false},
|
||||
}
|
||||
}
|
||||
|
||||
// --- Sort Mode: Name Ascending ---
|
||||
|
||||
func TestSort_NameAscending(t *testing.T) {
|
||||
entries := newUnsortedEntries()
|
||||
sortEntries(entries, SortModeNameAsc)
|
||||
|
||||
// Directories and files interleaved by name
|
||||
// Expected: 123.txt, adir, apple.txt, banana.txt, Cherry.txt, MyDir, Zebra.txt
|
||||
wantNames := []string{"123.txt", "adir", "apple.txt", "banana.txt", "Cherry.txt", "MyDir", "Zebra.txt"}
|
||||
for i, want := range wantNames {
|
||||
if entries[i].Name != want {
|
||||
t.Errorf("entries[%d].Name = %q, want %q", i, entries[i].Name, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSort_NameAscending_DirsInterleaved(t *testing.T) {
|
||||
entries := newUnsortedEntries()
|
||||
sortEntries(entries, SortModeNameAsc)
|
||||
|
||||
// Directories should be interleaved with files at their alphabetical position
|
||||
// adir should be between 123.txt and apple.txt
|
||||
adirIdx := -1
|
||||
for i, e := range entries {
|
||||
if e.Name == "adir" {
|
||||
adirIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if adirIdx <= 0 || adirIdx >= len(entries)-1 {
|
||||
t.Errorf("adir at idx %d should be between 123.txt and apple.txt", adirIdx)
|
||||
}
|
||||
// Verify neighbors
|
||||
if entries[adirIdx-1].Name != "123.txt" {
|
||||
t.Errorf("expected 123.txt before adir, got %s", entries[adirIdx-1].Name)
|
||||
}
|
||||
if entries[adirIdx+1].Name != "apple.txt" {
|
||||
t.Errorf("expected apple.txt after adir, got %s", entries[adirIdx+1].Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSort_NameAscending_CaseInsensitive(t *testing.T) {
|
||||
entries := newUnsortedEntries()
|
||||
sortEntries(entries, SortModeNameAsc)
|
||||
|
||||
// "apple.txt" should come before "Cherry.txt" (case-insensitive)
|
||||
appleIdx := -1
|
||||
cherryIdx := -1
|
||||
for i, e := range entries {
|
||||
if e.Name == "apple.txt" {
|
||||
appleIdx = i
|
||||
}
|
||||
if e.Name == "Cherry.txt" {
|
||||
cherryIdx = i
|
||||
}
|
||||
}
|
||||
if appleIdx >= cherryIdx {
|
||||
t.Errorf("apple.txt (idx %d) should come before Cherry.txt (idx %d)", appleIdx, cherryIdx)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSort_NameAscending_NumericFirst(t *testing.T) {
|
||||
entries := newUnsortedEntries()
|
||||
sortEntries(entries, SortModeNameAsc)
|
||||
|
||||
// "123.txt" should be the first entry (numbers sort before letters)
|
||||
if entries[0].Name != "123.txt" {
|
||||
t.Errorf("expected 123.txt first, got %s", entries[0].Name)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Sort Mode: Name Descending ---
|
||||
|
||||
func TestSort_NameDescending(t *testing.T) {
|
||||
entries := newUnsortedEntries()
|
||||
sortEntries(entries, SortModeNameDesc)
|
||||
|
||||
// Directories and files interleaved by name (reverse)
|
||||
// Expected: Zebra.txt, MyDir, Cherry.txt, banana.txt, apple.txt, adir, 123.txt
|
||||
wantNames := []string{"Zebra.txt", "MyDir", "Cherry.txt", "banana.txt", "apple.txt", "adir", "123.txt"}
|
||||
for i, want := range wantNames {
|
||||
if entries[i].Name != want {
|
||||
t.Errorf("entries[%d].Name = %q, want %q", i, entries[i].Name, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Sort Mode: Date Ascending ---
|
||||
|
||||
func TestSort_DateAscending(t *testing.T) {
|
||||
entries := newUnsortedEntries()
|
||||
sortEntries(entries, SortModeDateAsc)
|
||||
|
||||
// Directories and files interleaved by date
|
||||
// banana.txt: 2024-01-01, adir: 2024-01-10, Zebra.txt: 2024-01-15, MyDir: 2024-02-10, Cherry.txt: 2024-02-20, apple.txt: 2024-03-01, 123.txt: 2024-04-01
|
||||
wantNames := []string{"banana.txt", "adir", "Zebra.txt", "MyDir", "Cherry.txt", "apple.txt", "123.txt"}
|
||||
for i, want := range wantNames {
|
||||
if entries[i].Name != want {
|
||||
t.Errorf("entries[%d].Name = %q, want %q", i, entries[i].Name, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSort_DateAscending_DirsInterleaved(t *testing.T) {
|
||||
entries := newUnsortedEntries()
|
||||
sortEntries(entries, SortModeDateAsc)
|
||||
|
||||
// Directories should be interleaved with files at their date position
|
||||
// adir (2024-01-10) should be between banana.txt (2024-01-01) and Zebra.txt (2024-01-15)
|
||||
adirIdx := -1
|
||||
for i, e := range entries {
|
||||
if e.Name == "adir" {
|
||||
adirIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if adirIdx <= 0 || adirIdx >= len(entries)-1 {
|
||||
t.Errorf("adir at idx %d should be between banana.txt and Zebra.txt", adirIdx)
|
||||
}
|
||||
if entries[adirIdx-1].Name != "banana.txt" {
|
||||
t.Errorf("expected banana.txt before adir, got %s", entries[adirIdx-1].Name)
|
||||
}
|
||||
if entries[adirIdx+1].Name != "Zebra.txt" {
|
||||
t.Errorf("expected Zebra.txt after adir, got %s", entries[adirIdx+1].Name)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Sort Mode: Date Descending ---
|
||||
|
||||
func TestSort_DateDescending(t *testing.T) {
|
||||
entries := newUnsortedEntries()
|
||||
sortEntries(entries, SortModeDateDesc)
|
||||
|
||||
// Directories and files interleaved by date (reverse)
|
||||
wantNames := []string{"123.txt", "apple.txt", "Cherry.txt", "MyDir", "Zebra.txt", "adir", "banana.txt"}
|
||||
for i, want := range wantNames {
|
||||
if entries[i].Name != want {
|
||||
t.Errorf("entries[%d].Name = %q, want %q", i, entries[i].Name, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Sort Mode: Size Ascending (REMOVED - only 4 sort modes: name +/-, date +/-) ---
|
||||
// Size-based sorting has been removed from the browser to keep sort modes minimal.
|
||||
// The sortEntries function still exists for potential future use.
|
||||
|
||||
// --- Sort Mode: Size Descending (REMOVED - only 4 sort modes: name +/-, date +/-) ---
|
||||
// Size-based sorting has been removed from the browser to keep sort modes minimal.
|
||||
// The sortEntries function still exists for potential future use.
|
||||
|
||||
// --- Edge Cases ---
|
||||
|
||||
func TestSort_EmptySlice(t *testing.T) {
|
||||
var entries []Entry
|
||||
sortEntries(entries, SortModeNameAsc)
|
||||
if len(entries) != 0 {
|
||||
t.Errorf("expected empty slice, got %d entries", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSort_SingleEntry(t *testing.T) {
|
||||
entries := []Entry{{Name: "only.txt", Size: 100, IsDir: false}}
|
||||
sortEntries(entries, SortModeNameAsc)
|
||||
if len(entries) != 1 || entries[0].Name != "only.txt" {
|
||||
t.Errorf("single entry sort failed: %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSort_AllDirectories(t *testing.T) {
|
||||
entries := []Entry{
|
||||
{Name: "Zdir", IsDir: true},
|
||||
{Name: "adir", IsDir: true},
|
||||
{Name: "Mdir", IsDir: true},
|
||||
}
|
||||
sortEntries(entries, SortModeNameAsc)
|
||||
wantNames := []string{"adir", "Mdir", "Zdir"}
|
||||
for i, want := range wantNames {
|
||||
if entries[i].Name != want {
|
||||
t.Errorf("entries[%d].Name = %q, want %q", i, entries[i].Name, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSort_AllFiles(t *testing.T) {
|
||||
entries := []Entry{
|
||||
{Name: "Zebra.txt", IsDir: false},
|
||||
{Name: "apple.txt", IsDir: false},
|
||||
{Name: "Mango.txt", IsDir: false},
|
||||
}
|
||||
sortEntries(entries, SortModeNameAsc)
|
||||
wantNames := []string{"apple.txt", "Mango.txt", "Zebra.txt"}
|
||||
for i, want := range wantNames {
|
||||
if entries[i].Name != want {
|
||||
t.Errorf("entries[%d].Name = %q, want %q", i, entries[i].Name, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSort_StableEqualKeys(t *testing.T) {
|
||||
// When two entries have equal sort keys, order should be deterministic
|
||||
entries := []Entry{
|
||||
{Name: "bbb.txt", Size: 100, ModTime: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), IsDir: false},
|
||||
{Name: "aaa.txt", Size: 100, ModTime: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), IsDir: false},
|
||||
}
|
||||
sortEntries(entries, SortModeNameAsc)
|
||||
// Same name — should maintain stable order
|
||||
if entries[0].Name != "aaa.txt" {
|
||||
t.Errorf("expected aaa.txt first on equal name, got %s", entries[0].Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSort_NoSideEffectsOnOriginalOrder(t *testing.T) {
|
||||
// Sorting should not corrupt entry data
|
||||
entries := newUnsortedEntries()
|
||||
originalNames := make([]string, len(entries))
|
||||
for i, e := range entries {
|
||||
originalNames[i] = e.Name
|
||||
}
|
||||
|
||||
sortEntries(entries, SortModeNameAsc)
|
||||
|
||||
// All original entries should still be present
|
||||
names := make(map[string]bool)
|
||||
for _, e := range entries {
|
||||
names[e.Name] = true
|
||||
}
|
||||
for _, name := range originalNames {
|
||||
if !names[name] {
|
||||
t.Errorf("entry %q lost during sort", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSort_InvalidMode(t *testing.T) {
|
||||
entries := newUnsortedEntries()
|
||||
originalLen := len(entries)
|
||||
|
||||
// Invalid mode should not panic and should leave entries intact
|
||||
sortEntries(entries, SortMode(-99))
|
||||
|
||||
if len(entries) != originalLen {
|
||||
t.Errorf("invalid mode changed entry count: %d -> %d", originalLen, len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSort_LargeSlice(t *testing.T) {
|
||||
const count = 10000
|
||||
entries := make([]Entry, count)
|
||||
for i := 0; i < count; i++ {
|
||||
entries[i] = Entry{
|
||||
Name: fmt.Sprintf("file_%05d.txt", i),
|
||||
Size: int64(i * 10),
|
||||
ModTime: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(i) * time.Hour),
|
||||
IsDir: i%100 == 0,
|
||||
}
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
sortEntries(entries, SortModeNameAsc)
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if elapsed > 5*time.Second {
|
||||
t.Errorf("sort took %v, expected < 5s", elapsed)
|
||||
}
|
||||
|
||||
// Verify directories are interleaved (not separated)
|
||||
// With 100 entries per 100 entries being dirs, they should be mixed
|
||||
hasDirBeforeFile := false
|
||||
hasFileBeforeDir := false
|
||||
for i := 0; i < len(entries)-1; i++ {
|
||||
if entries[i].IsDir && !entries[i+1].IsDir {
|
||||
hasDirBeforeFile = true
|
||||
}
|
||||
if !entries[i].IsDir && entries[i+1].IsDir {
|
||||
hasFileBeforeDir = true
|
||||
}
|
||||
}
|
||||
if !hasDirBeforeFile || !hasFileBeforeDir {
|
||||
t.Errorf("directories should be interleaved with files, not separated")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gioui.org/widget"
|
||||
"pad/internal/ui"
|
||||
)
|
||||
|
||||
// Entry represents a single file or directory in the browser.
|
||||
type Entry struct {
|
||||
Path string // Relative path from configured directory
|
||||
Name string // Display name (basename)
|
||||
Size int64 // File size in bytes (0 for directories)
|
||||
ModTime time.Time // Last modification time
|
||||
IsDir bool // True if this is a directory
|
||||
IsFirst bool // True if this is the first entry for its letter section
|
||||
}
|
||||
|
||||
// Page represents a chunk of directory entries loaded from disk.
|
||||
type Page struct {
|
||||
Index int // Page number (0-based)
|
||||
Entries []Entry // Entries in this page
|
||||
Loaded bool // True if page data is in memory
|
||||
Dirty bool // True if page needs refresh (external change detected)
|
||||
}
|
||||
|
||||
// BrowserState holds all mutable browser state owned by the logic goroutine.
|
||||
type BrowserState struct {
|
||||
// Navigation
|
||||
CurrentPath string // Currently browsed directory (relative to root)
|
||||
ScrollIndex int // Index of first visible entry (not pixel offset)
|
||||
VisibleCount int // Number of entries currently visible
|
||||
|
||||
// Lazy loading
|
||||
Pages map[int]*Page // Loaded pages by page index
|
||||
TotalEntries int // Total entry count (from cached index)
|
||||
Loading bool // True if a page load is in flight
|
||||
|
||||
// Sorted index (position maps for each sort mode)
|
||||
SortIndex *DirectoryIndex // Cached index with position maps
|
||||
SortMode SortMode // Current sort mode
|
||||
|
||||
// Search
|
||||
Query string // Current search query
|
||||
SearchResults []int // Indices of matching entries (empty = no filter)
|
||||
SearchEditor widget.Editor // Gio editor for search input
|
||||
|
||||
// Alphabetical index
|
||||
ActiveLetter string // Currently pressed letter (for highlighting)
|
||||
LetterOffsets map[string]int // First entry index for each letter
|
||||
|
||||
// Interaction
|
||||
SelectedIndex int // Currently selected entry (-1 = none)
|
||||
TapTimestamp time.Time // For double-tap detection
|
||||
}
|
||||
|
||||
const (
|
||||
PageSize = 100 // Entries per page (tunable; ~5KB per page in memory)
|
||||
PrefetchDist = 2 // Pages to prefetch beyond visible region
|
||||
)
|
||||
|
||||
// NewEntry creates a new Entry from the given parameters.
|
||||
func NewEntry(path, name string, size int64, modTime time.Time, isDir bool) Entry {
|
||||
return Entry{
|
||||
Path: path,
|
||||
Name: name,
|
||||
Size: size,
|
||||
ModTime: modTime,
|
||||
IsDir: isDir,
|
||||
}
|
||||
}
|
||||
|
||||
// NewPage creates a new Page with the given index and entries.
|
||||
func NewPage(index int, entries []Entry) *Page {
|
||||
return &Page{
|
||||
Index: index,
|
||||
Entries: entries,
|
||||
Loaded: true,
|
||||
}
|
||||
}
|
||||
|
||||
// NewBrowserState creates a new BrowserState with default values.
|
||||
func NewBrowserState() *BrowserState {
|
||||
return &BrowserState{
|
||||
Pages: make(map[int]*Page),
|
||||
LetterOffsets: make(map[string]int),
|
||||
SelectedIndex: -1,
|
||||
SortMode: SortModeNameAsc, // Default sort mode
|
||||
}
|
||||
}
|
||||
|
||||
// ToListItem converts an Entry to a ui.ListItem for rendering.
|
||||
func (e *Entry) ToListItem() ui.ListItem {
|
||||
subtext := formatSize(e.Size)
|
||||
if e.IsDir {
|
||||
subtext = "Directory"
|
||||
}
|
||||
return ui.ListItem{
|
||||
Text: e.Name,
|
||||
Subtext: subtext,
|
||||
}
|
||||
}
|
||||
|
||||
// formatSize returns a human-readable file size string.
|
||||
func formatSize(bytes int64) string {
|
||||
switch {
|
||||
case bytes < 1024:
|
||||
return fmt.Sprintf("%d B", bytes)
|
||||
case bytes < 1024*1024:
|
||||
return fmt.Sprintf("%.1f KB", float64(bytes)/1024)
|
||||
case bytes < 1024*1024*1024:
|
||||
return fmt.Sprintf("%.1f MB", float64(bytes)/(1024*1024))
|
||||
default:
|
||||
return fmt.Sprintf("%.1f GB", float64(bytes)/(1024*1024*1024))
|
||||
}
|
||||
}
|
||||
|
||||
// EvictPages removes pages that are far from the current scroll position.
|
||||
func (s *BrowserState) EvictPages() {
|
||||
minPage := s.ScrollIndex/PageSize - PrefetchDist
|
||||
maxPage := (s.ScrollIndex + s.VisibleCount)/PageSize + PrefetchDist
|
||||
for idx, page := range s.Pages {
|
||||
if idx < minPage || idx > maxPage {
|
||||
page.Entries = nil // Release memory
|
||||
page.Loaded = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset clears all browser state for navigation.
|
||||
func (s *BrowserState) Reset() {
|
||||
s.Pages = make(map[int]*Page)
|
||||
s.ScrollIndex = 0
|
||||
s.SelectedIndex = -1
|
||||
s.SearchResults = nil
|
||||
s.Query = ""
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewEntry(t *testing.T) {
|
||||
now := time.Now()
|
||||
e := NewEntry("/test/file.txt", "file.txt", 1024, now, false)
|
||||
|
||||
if e.Path != "/test/file.txt" {
|
||||
t.Errorf("expected Path=/test/file.txt, got %s", e.Path)
|
||||
}
|
||||
if e.Name != "file.txt" {
|
||||
t.Errorf("expected Name=file.txt, got %s", e.Name)
|
||||
}
|
||||
if e.Size != 1024 {
|
||||
t.Errorf("expected Size=1024, got %d", e.Size)
|
||||
}
|
||||
if e.IsDir {
|
||||
t.Error("expected IsDir=false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEntryDirectory(t *testing.T) {
|
||||
e := NewEntry("/test/dir", "dir", 0, time.Time{}, true)
|
||||
|
||||
if !e.IsDir {
|
||||
t.Error("expected IsDir=true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPage(t *testing.T) {
|
||||
entries := []Entry{
|
||||
NewEntry("/a", "a", 100, time.Time{}, false),
|
||||
NewEntry("/b", "b", 200, time.Time{}, false),
|
||||
}
|
||||
p := NewPage(0, entries)
|
||||
|
||||
if p.Index != 0 {
|
||||
t.Errorf("expected Index=0, got %d", p.Index)
|
||||
}
|
||||
if !p.Loaded {
|
||||
t.Error("expected Loaded=true")
|
||||
}
|
||||
if len(p.Entries) != 2 {
|
||||
t.Errorf("expected 2 entries, got %d", len(p.Entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPageSizeConstant(t *testing.T) {
|
||||
if PageSize != 100 {
|
||||
t.Errorf("expected PageSize=100, got %d", PageSize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewBrowserState(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
|
||||
if s.ScrollIndex != 0 {
|
||||
t.Errorf("expected ScrollIndex=0, got %d", s.ScrollIndex)
|
||||
}
|
||||
if s.SelectedIndex != -1 {
|
||||
t.Errorf("expected SelectedIndex=-1, got %d", s.SelectedIndex)
|
||||
}
|
||||
if s.Pages == nil {
|
||||
t.Error("expected Pages to be initialized")
|
||||
}
|
||||
if s.LetterOffsets == nil {
|
||||
t.Error("expected LetterOffsets to be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEntryToListItem(t *testing.T) {
|
||||
e := NewEntry("/test/file.txt", "file.txt", 1024, time.Time{}, false)
|
||||
item := e.ToListItem()
|
||||
|
||||
if item.Text != "file.txt" {
|
||||
t.Errorf("expected Text=file.txt, got %s", item.Text)
|
||||
}
|
||||
if item.Subtext != "1.0 KB" {
|
||||
t.Errorf("expected Subtext=1.0 KB, got %s", item.Subtext)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEntryToListItemDirectory(t *testing.T) {
|
||||
e := NewEntry("/test/dir", "dir", 0, time.Time{}, true)
|
||||
item := e.ToListItem()
|
||||
|
||||
if item.Subtext != "Directory" {
|
||||
t.Errorf("expected Subtext=Directory, got %s", item.Subtext)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatSize(t *testing.T) {
|
||||
tests := []struct {
|
||||
size int64
|
||||
expected string
|
||||
}{
|
||||
{0, "0 B"},
|
||||
{500, "500 B"},
|
||||
{1024, "1.0 KB"},
|
||||
{1024*1024, "1.0 MB"},
|
||||
{1024 * 1024 * 1024, "1.0 GB"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
result := formatSize(tt.size)
|
||||
if result != tt.expected {
|
||||
t.Errorf("formatSize(%d) = %s, want %s", tt.size, result, tt.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrowserStateEvictPages(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.ScrollIndex = 500 // Page 5
|
||||
s.VisibleCount = 10
|
||||
|
||||
// With ScrollIndex=500, PageSize=100:
|
||||
// minPage = 5 - 2 = 3
|
||||
// maxPage = (500+10)/100 + 2 = 7
|
||||
// Pages 3-7 should be kept, others evicted
|
||||
|
||||
// Add pages at various positions
|
||||
s.Pages[0] = NewPage(0, nil) // Should be evicted (far)
|
||||
s.Pages[3] = NewPage(3, nil) // Should be kept (at min boundary)
|
||||
s.Pages[5] = NewPage(5, nil) // Should be kept (visible)
|
||||
s.Pages[7] = NewPage(7, nil) // Should be kept (at max boundary)
|
||||
s.Pages[10] = NewPage(10, nil) // Should be evicted (far)
|
||||
|
||||
s.EvictPages()
|
||||
|
||||
if s.Pages[0].Loaded {
|
||||
t.Error("expected page 0 to be evicted")
|
||||
}
|
||||
if !s.Pages[3].Loaded {
|
||||
t.Error("expected page 3 to be kept")
|
||||
}
|
||||
if !s.Pages[5].Loaded {
|
||||
t.Error("expected page 5 to be kept")
|
||||
}
|
||||
if !s.Pages[7].Loaded {
|
||||
t.Error("expected page 7 to be kept")
|
||||
}
|
||||
if s.Pages[10].Loaded {
|
||||
t.Error("expected page 10 to be evicted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrowserStateReset(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.ScrollIndex = 100
|
||||
s.SelectedIndex = 5
|
||||
s.Pages[0] = NewPage(0, nil)
|
||||
s.Query = "test"
|
||||
s.SearchResults = []int{1, 2, 3}
|
||||
|
||||
s.Reset()
|
||||
|
||||
if s.ScrollIndex != 0 {
|
||||
t.Errorf("expected ScrollIndex=0, got %d", s.ScrollIndex)
|
||||
}
|
||||
if s.SelectedIndex != -1 {
|
||||
t.Errorf("expected SelectedIndex=-1, got %d", s.SelectedIndex)
|
||||
}
|
||||
if len(s.Pages) != 0 {
|
||||
t.Errorf("expected Pages to be empty, got %d", len(s.Pages))
|
||||
}
|
||||
if s.Query != "" {
|
||||
t.Errorf("expected Query=\"\", got %q", s.Query)
|
||||
}
|
||||
if s.SearchResults != nil {
|
||||
t.Error("expected SearchResults to be nil")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadPage_FromIndex verifies page loading at correct offset
|
||||
func TestLoadPage_FromIndex(t *testing.T) {
|
||||
// Create a page with known entries
|
||||
entries := make([]Entry, 100)
|
||||
for i := 0; i < 100; i++ {
|
||||
entries[i] = NewEntry(fmt.Sprintf("/path/file%d.txt", i), fmt.Sprintf("file%d.txt", i), int64(i*100), time.Time{}, false)
|
||||
}
|
||||
page := NewPage(0, entries)
|
||||
|
||||
if page.Index != 0 {
|
||||
t.Errorf("expected Index=0, got %d", page.Index)
|
||||
}
|
||||
if len(page.Entries) != 100 {
|
||||
t.Errorf("expected 100 entries, got %d", len(page.Entries))
|
||||
}
|
||||
// Verify first entry
|
||||
if page.Entries[0].Name != "file0.txt" {
|
||||
t.Errorf("expected first entry name=file0.txt, got %s", page.Entries[0].Name)
|
||||
}
|
||||
// Verify last entry
|
||||
if page.Entries[99].Name != "file99.txt" {
|
||||
t.Errorf("expected last entry name=file99.txt, got %s", page.Entries[99].Name)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadPage_LastPagePartial verifies partial page at end of list
|
||||
func TestLoadPage_LastPagePartial(t *testing.T) {
|
||||
// A last page with fewer than PageSize entries
|
||||
entries := []Entry{
|
||||
NewEntry("/path/last1.txt", "last1.txt", 100, time.Time{}, false),
|
||||
NewEntry("/path/last2.txt", "last2.txt", 200, time.Time{}, false),
|
||||
}
|
||||
page := NewPage(99, entries) // High page index
|
||||
|
||||
if page.Index != 99 {
|
||||
t.Errorf("expected Index=99, got %d", page.Index)
|
||||
}
|
||||
if len(page.Entries) != 2 {
|
||||
t.Errorf("expected 2 entries, got %d", len(page.Entries))
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadPage_OutOfBounds verifies bounds checking
|
||||
func TestLoadPage_OutOfBounds(t *testing.T) {
|
||||
s := NewBrowserState()
|
||||
s.TotalEntries = 150 // 2 pages (0 and 1)
|
||||
|
||||
// Requesting page 5 (out of bounds) should not panic
|
||||
// The actual bounds check would be in the browser.go loading logic
|
||||
// For now, verify that the state doesn't crash when accessing non-existent pages
|
||||
_, exists := s.Pages[5]
|
||||
if exists {
|
||||
t.Error("expected page 5 to not exist")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user