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:
@@ -3,6 +3,9 @@ package editor
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"pad/internal/browser"
|
||||
"pad/internal/io/pool"
|
||||
"pad/internal/io/pool/mock"
|
||||
"pad/internal/ui"
|
||||
)
|
||||
|
||||
@@ -47,13 +50,28 @@ type Logic struct {
|
||||
lastLineYChan chan int // last line Y (Dp, sent as int) feedback from renderer
|
||||
resultChan chan ResultEvent
|
||||
searchQueryChan chan string // search text updates from main goroutine
|
||||
workerPool *pool.WorkerPool
|
||||
mockFS *mock.FileSystem
|
||||
mu sync.Mutex
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// NewLogic creates a new Logic instance.
|
||||
func NewLogic() *Logic {
|
||||
state := NewState()
|
||||
TheState = state
|
||||
|
||||
// Initialize mock filesystem with sample data
|
||||
mockFS := mock.NewFileSystem()
|
||||
populateMockFileSystem(mockFS)
|
||||
|
||||
// Initialize worker pool
|
||||
wp := pool.NewWorkerPool(4)
|
||||
wp.Start()
|
||||
|
||||
// Set browser initial path to mock root
|
||||
state.Browser.CurrentPath = "/"
|
||||
|
||||
return &Logic{
|
||||
state: state,
|
||||
configChan: make(chan ConfigUpdate),
|
||||
@@ -62,6 +80,9 @@ func NewLogic() *Logic {
|
||||
lastLineYChan: make(chan int),
|
||||
resultChan: make(chan ResultEvent),
|
||||
searchQueryChan: make(chan string),
|
||||
workerPool: wp,
|
||||
mockFS: mockFS,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,8 +128,13 @@ func (l *Logic) Scale() float32 {
|
||||
|
||||
// Run runs the logic goroutine loop.
|
||||
func (l *Logic) Run() {
|
||||
// Dispatch initial directory index build on startup
|
||||
l.workerPool.Dispatch(pool.NewBuildIndexTask(l.state.Browser.CurrentPath, l.mockFS))
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-l.done:
|
||||
return
|
||||
case update := <-l.configChan:
|
||||
update.apply(l.state)
|
||||
l.frameChan <- l.state.layout()
|
||||
@@ -123,22 +149,65 @@ func (l *Logic) Run() {
|
||||
}
|
||||
l.frameChan <- l.state.layout()
|
||||
case query := <-l.searchQueryChan:
|
||||
if query != l.state.SearchQuery {
|
||||
l.state.SearchQuery = query
|
||||
if query != l.state.Browser.Query {
|
||||
l.state.Browser.Query = query
|
||||
if l.state.page == BrowserPage {
|
||||
l.state.BrowserScrollOffset = 0 // reset scroll on query change
|
||||
filtered := getFilteredEntriesRaw()
|
||||
l.state.SortedEntries = sortEntries(filtered, l.state.SortMode)
|
||||
browser.HandleSearch(&l.state.Browser, query)
|
||||
}
|
||||
}
|
||||
l.frameChan <- l.state.layout()
|
||||
case res := <-l.workerPool.ResultChan():
|
||||
l.handleWorkerResult(res)
|
||||
case <-l.resultChan:
|
||||
l.frameChan <- l.state.layout()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleWorkerResult processes results from the worker pool.
|
||||
func (l *Logic) handleWorkerResult(res pool.Result) {
|
||||
switch res.TaskType {
|
||||
case pool.TypeBuildIndex:
|
||||
l.applyBuildIndexResult(res)
|
||||
case pool.TypeLoadPages:
|
||||
l.applyLoadPagesResult(res)
|
||||
case pool.TypeReadDir:
|
||||
l.applyReadDirResult(res)
|
||||
}
|
||||
l.frameChan <- l.state.layout()
|
||||
}
|
||||
|
||||
// applyBuildIndexResult applies a completed BuildIndexTask result to browser state.
|
||||
func (l *Logic) applyBuildIndexResult(res pool.Result) {
|
||||
if !res.Success {
|
||||
return
|
||||
}
|
||||
// Convert mock DirEntry results to browser entries
|
||||
if entries, ok := res.Data.([]mock.DirEntry); ok {
|
||||
l.state.Browser.TotalEntries = len(entries)
|
||||
// Build the in-memory index with position maps
|
||||
l.state.Browser.SortIndex = buildBrowserIndex(entries)
|
||||
// Load initial visible pages from the index into the Pages map
|
||||
browser.LoadInitialPages(&l.state.Browser)
|
||||
}
|
||||
}
|
||||
|
||||
// applyLoadPagesResult applies a completed LoadPagesTask result to browser state.
|
||||
func (l *Logic) applyLoadPagesResult(res pool.Result) {
|
||||
_ = res // TODO: implement page loading from worker results
|
||||
}
|
||||
|
||||
// applyReadDirResult applies a completed ReadDirTask result to browser state.
|
||||
func (l *Logic) applyReadDirResult(res pool.Result) {
|
||||
_ = res // TODO: implement directory read result handling
|
||||
}
|
||||
|
||||
// State returns the current state.
|
||||
func (l *Logic) State() *State {
|
||||
return l.state
|
||||
}
|
||||
|
||||
// Done signals the logic goroutine to stop.
|
||||
func (l *Logic) Done() {
|
||||
close(l.done)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
package editor
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"pad/internal/browser"
|
||||
"pad/internal/io/pool/mock"
|
||||
)
|
||||
|
||||
// populateMockFileSystem seeds the mock filesystem with sample data for testing.
|
||||
// Creates a realistic directory structure with subdirectories, various file types,
|
||||
// and varied sizes/dates to exercise the browser functionality.
|
||||
func populateMockFileSystem(fs *mock.FileSystem) {
|
||||
baseTime := time.Date(2026, 5, 15, 10, 0, 0, 0, time.UTC)
|
||||
|
||||
// --- Root directories ---
|
||||
dirs := []string{
|
||||
"/Documents",
|
||||
"/Pictures",
|
||||
"/Music",
|
||||
"/Downloads",
|
||||
"/Projects",
|
||||
"/Projects/pad",
|
||||
"/Projects/goplus",
|
||||
"/Documents/Work",
|
||||
"/Documents/Personal",
|
||||
"/Pictures/Vacation",
|
||||
}
|
||||
for i, d := range dirs {
|
||||
fs.AddDir(d, baseTime.AddDate(0, 0, -i))
|
||||
}
|
||||
|
||||
// --- Root files ---
|
||||
rootFiles := []struct {
|
||||
name string
|
||||
size int64
|
||||
days int
|
||||
}{
|
||||
{"README.md", 2048, -30},
|
||||
{"config.yaml", 512, -60},
|
||||
{"notes.txt", 1024, -15},
|
||||
{"setup.log", 4096, -7},
|
||||
{".gitignore", 128, -90},
|
||||
}
|
||||
for _, f := range rootFiles {
|
||||
fs.AddFile("/"+f.name, make([]byte, f.size), baseTime.AddDate(0, 0, f.days))
|
||||
}
|
||||
|
||||
// --- Documents/Work files ---
|
||||
workFiles := []struct {
|
||||
name string
|
||||
size int64
|
||||
days int
|
||||
}{
|
||||
{"Q1_Report.docx", 524288, -45},
|
||||
{"Q2_Report.docx", 614400, -14},
|
||||
{"Budget_2026.xlsx", 262144, -30},
|
||||
{"Meeting_Notes.txt", 8192, -1},
|
||||
{"Presentation.pptx", 1048576, -21},
|
||||
}
|
||||
for _, f := range workFiles {
|
||||
fs.AddFile("/Documents/Work/"+f.name, make([]byte, f.size), baseTime.AddDate(0, 0, f.days))
|
||||
}
|
||||
|
||||
// --- Documents/Personal files ---
|
||||
personalFiles := []struct {
|
||||
name string
|
||||
size int64
|
||||
days int
|
||||
}{
|
||||
{"Resume.pdf", 32768, -60},
|
||||
{"Tax_Return_2025.pdf", 131072, -90},
|
||||
{"Recipe_Collection.txt", 4096, -120},
|
||||
{"Letter_to_Friend.txt", 2048, -5},
|
||||
}
|
||||
for _, f := range personalFiles {
|
||||
fs.AddFile("/Documents/Personal/"+f.name, make([]byte, f.size), baseTime.AddDate(0, 0, f.days))
|
||||
}
|
||||
|
||||
// --- Projects/pad source files ---
|
||||
padFiles := []struct {
|
||||
name string
|
||||
size int64
|
||||
days int
|
||||
}{
|
||||
{"main.go", 3072, -2},
|
||||
{"state.go", 4096, -2},
|
||||
{"logic.go", 5120, -1},
|
||||
{"browser.go", 2048, -7},
|
||||
{"types.go", 1536, -7},
|
||||
{"index.go", 3584, -7},
|
||||
{"layout.go", 2560, -5},
|
||||
{"handlers.go", 1024, -3},
|
||||
{"go.mod", 256, -30},
|
||||
{"go.sum", 512, -30},
|
||||
}
|
||||
for _, f := range padFiles {
|
||||
fs.AddFile("/Projects/pad/"+f.name, make([]byte, f.size), baseTime.AddDate(0, 0, f.days))
|
||||
}
|
||||
|
||||
// --- Pictures/Vacation files ---
|
||||
vacationFiles := []struct {
|
||||
name string
|
||||
size int64
|
||||
days int
|
||||
}{
|
||||
{"IMG_0001.jpg", 3145728, -180},
|
||||
{"IMG_0002.jpg", 2621440, -180},
|
||||
{"IMG_0003.jpg", 4194304, -179},
|
||||
{"IMG_0004.jpg", 3670016, -179},
|
||||
{"IMG_0005.jpg", 2097152, -178},
|
||||
}
|
||||
for _, f := range vacationFiles {
|
||||
fs.AddFile("/Pictures/Vacation/"+f.name, make([]byte, f.size), baseTime.AddDate(0, 0, f.days))
|
||||
}
|
||||
|
||||
// --- Downloads files ---
|
||||
downloads := []struct {
|
||||
name string
|
||||
size int64
|
||||
days int
|
||||
}{
|
||||
{"installer.dmg", 104857600, -10},
|
||||
{"archive.tar.gz", 52428800, -20},
|
||||
{"patch.diff", 8192, -3},
|
||||
}
|
||||
for _, f := range downloads {
|
||||
fs.AddFile("/Downloads/"+f.name, make([]byte, f.size), baseTime.AddDate(0, 0, f.days))
|
||||
}
|
||||
}
|
||||
|
||||
// sortModeKey converts a browser.SortMode to its JSON key string.
|
||||
func sortModeKey(mode browser.SortMode) string {
|
||||
switch mode {
|
||||
case 0: // SortModeNameAsc
|
||||
return "name_asc"
|
||||
case 1: // SortModeNameDesc
|
||||
return "name_desc"
|
||||
case 2: // SortModeDateAsc
|
||||
return "date_asc"
|
||||
case 3: // SortModeDateDesc
|
||||
return "date_desc"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// modeCount returns the total number of sort modes.
|
||||
func modeCount() int {
|
||||
return 4
|
||||
}
|
||||
|
||||
// buildBrowserIndex converts mock DirEntry results into a browser.DirectoryIndex
|
||||
// with pre-computed position maps for all sort modes.
|
||||
func buildBrowserIndex(entries []mock.DirEntry) *browser.DirectoryIndex {
|
||||
var browserEntries []browser.Entry
|
||||
for _, e := range entries {
|
||||
info, err := e.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
browserEntries = append(browserEntries, browser.Entry{
|
||||
Path: e.Name(),
|
||||
Name: e.Name(),
|
||||
Size: info.Size(),
|
||||
ModTime: info.ModTime(),
|
||||
IsDir: info.IsDir(),
|
||||
})
|
||||
}
|
||||
|
||||
// Build position maps for all sort modes
|
||||
sortOrders := make(map[string][]int)
|
||||
for mode := browser.SortMode(0); mode < browser.SortMode(modeCount()); mode++ {
|
||||
key := sortModeKey(mode)
|
||||
if key != "" {
|
||||
sortOrders[key] = buildPositionMap(browserEntries, mode)
|
||||
}
|
||||
}
|
||||
|
||||
return &browser.DirectoryIndex{
|
||||
Path: "/",
|
||||
EntryCount: len(browserEntries),
|
||||
Entries: browserEntries,
|
||||
SortOrders: sortOrders,
|
||||
}
|
||||
}
|
||||
|
||||
// buildPositionMap creates a sorted index → raw index mapping.
|
||||
func buildPositionMap(entries []browser.Entry, mode browser.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
|
||||
}
|
||||
|
||||
// comparator returns a comparison function for the given SortMode.
|
||||
// Returns negative if a < b, zero if equal, positive if a > b.
|
||||
func comparator(mode browser.SortMode) func(a, b browser.Entry) int {
|
||||
switch mode {
|
||||
case 0: // SortModeNameAsc
|
||||
return func(a, b browser.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 1: // SortModeNameDesc
|
||||
return func(a, b browser.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 2: // SortModeDateAsc
|
||||
return func(a, b browser.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 3: // SortModeDateDesc
|
||||
return func(a, b browser.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:
|
||||
return func(a, b browser.Entry) int { return 0 }
|
||||
}
|
||||
}
|
||||
+17
-270
@@ -1,10 +1,7 @@
|
||||
package editor
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gioui.org/widget"
|
||||
"pad/internal/browser"
|
||||
"pad/internal/ui"
|
||||
)
|
||||
|
||||
@@ -73,25 +70,17 @@ type State struct {
|
||||
LastLineY ui.Dp // last line baseline offset from text origin, from renderer
|
||||
MaxScroll ui.Dp // max scroll offset (content height - viewport height)
|
||||
Elems []ui.Element
|
||||
// Browser state
|
||||
BrowserScrollOffset ui.Dp // pixel-level scroll offset for browser list
|
||||
BrowserListHeight ui.Dp // height of the list region, set during layout
|
||||
SortMode SortMode // sort mode for browser list
|
||||
SortOrderLabel string // label text for sort order toggle
|
||||
SearchQuery string // current search query
|
||||
SearchEditor widget.Editor // Gio editor for search input
|
||||
SortedEntries []ui.ListItem // pre-sorted entries (computed only when sort mode changes)
|
||||
// Browser state (directly embedded per architecture §8)
|
||||
Browser browser.BrowserState // Embedded, not a pointer
|
||||
// Editor state
|
||||
ActiveFilename string // filename shown in editor status bar
|
||||
ActiveFilename string // filename shown in editor status bar
|
||||
}
|
||||
|
||||
func NewState() *State {
|
||||
return &State{
|
||||
scale: 1.0,
|
||||
page: EditorPage,
|
||||
SortMode: SortByDateDesc,
|
||||
SortOrderLabel: "Date ↓",
|
||||
SortedEntries: sortEntries(browserEntries, SortByDateDesc),
|
||||
scale: 1.0,
|
||||
page: EditorPage,
|
||||
Browser: *browser.NewBrowserState(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +101,8 @@ func (s *State) layout() []ui.Element {
|
||||
dpH := ui.ToDp(ui.Px(s.PixelHeight), s.scale)
|
||||
switch s.page {
|
||||
case BrowserPage:
|
||||
s.Elems = BrowserLayout(dpW, dpH, s.SortMode)
|
||||
browser.SetBrowserState(&s.Browser)
|
||||
s.Elems = browser.BrowserLayout(dpW, dpH, &s.Browser)
|
||||
case EditorPage:
|
||||
s.Elems = EditorLayout(dpW, dpH, s.WordWrap)
|
||||
}
|
||||
@@ -138,51 +128,11 @@ func HandleScroll(data any) {
|
||||
}
|
||||
}
|
||||
|
||||
// HandleBrowserScroll updates the browser list scroll offset.
|
||||
// The delta is in pixels; convert to Dp for smooth per-pixel scrolling.
|
||||
// HandleBrowserScroll updates the browser scroll index by the given delta.
|
||||
// Delegates to the browser package's handler.
|
||||
func HandleBrowserScroll(data any) {
|
||||
delta := data.(int) // pixels
|
||||
deltaDp := ui.ToDp(ui.Px(delta), TheState.scale)
|
||||
TheState.BrowserScrollOffset += deltaDp
|
||||
if TheState.BrowserScrollOffset < 0 {
|
||||
TheState.BrowserScrollOffset = 0
|
||||
}
|
||||
maxScroll := computeBrowserMaxScroll()
|
||||
if TheState.BrowserScrollOffset > maxScroll {
|
||||
TheState.BrowserScrollOffset = maxScroll
|
||||
}
|
||||
}
|
||||
|
||||
// computeBrowserMaxScroll returns the maximum scroll offset in Dp
|
||||
// so the last row is fully visible at the bottom of the list.
|
||||
func computeBrowserMaxScroll() ui.Dp {
|
||||
rowHeight := ui.Dp(48)
|
||||
totalRows := len(getFilteredEntries())
|
||||
// Calculate max scroll such that the last row's bottom edge
|
||||
// aligns with the list region's bottom edge.
|
||||
// lastRowBottom = totalRows * rowHeight
|
||||
// We want: lastRowBottom - maxScroll = BrowserListHeight
|
||||
// Therefore: maxScroll = totalRows * rowHeight - BrowserListHeight
|
||||
maxScroll := ui.Dp(totalRows)*rowHeight - TheState.BrowserListHeight
|
||||
if maxScroll < 0 {
|
||||
return 0
|
||||
}
|
||||
return maxScroll
|
||||
}
|
||||
|
||||
// visibleBrowserRows estimates how many browser rows fit in the viewport.
|
||||
func visibleBrowserRows(pixelHeight int, scale float32) int {
|
||||
margin := 10
|
||||
headerHeight := 24
|
||||
searchHeight := 36
|
||||
gap := 3 // margin/2 * 2 in Dp
|
||||
contentHeight := ui.ToDp(ui.Px(pixelHeight), float32(scale)) - ui.Dp(margin*2+headerHeight+searchHeight+gap)
|
||||
rowHeight := ui.Dp(48)
|
||||
rows := int(contentHeight / rowHeight)
|
||||
if rows < 1 {
|
||||
rows = 1
|
||||
}
|
||||
return rows
|
||||
delta := data.(int) // entries
|
||||
browser.HandleScroll(&TheState.Browser, delta)
|
||||
}
|
||||
|
||||
// GoToBrowser switches the app to the browser page.
|
||||
@@ -204,20 +154,10 @@ func OpenFile(data any) {
|
||||
|
||||
// ToggleSortOrder cycles the browser sort mode through four modes.
|
||||
func ToggleSortOrder(data any) {
|
||||
TheState.SortMode = (TheState.SortMode + 1) % 4
|
||||
switch TheState.SortMode {
|
||||
case SortByDateDesc:
|
||||
TheState.SortOrderLabel = "Date ↓"
|
||||
case SortByDateAsc:
|
||||
TheState.SortOrderLabel = "Date ↑"
|
||||
case SortByNameAsc:
|
||||
TheState.SortOrderLabel = "Name ↑"
|
||||
case SortByNameDesc:
|
||||
TheState.SortOrderLabel = "Name ↓"
|
||||
}
|
||||
// Sort once when mode changes, not every frame
|
||||
TheState.SortedEntries = sortEntries(getFilteredEntriesRaw(), TheState.SortMode)
|
||||
TheState.BrowserScrollOffset = 0 // reset scroll on sort change
|
||||
// Cycle through the 4 sort modes
|
||||
TheState.Browser.SortMode = (TheState.Browser.SortMode + 1) % 4
|
||||
// Reset scroll on sort change
|
||||
TheState.Browser.ScrollIndex = 0
|
||||
}
|
||||
|
||||
// EditorLayout computes the element tree for the editor page.
|
||||
@@ -303,196 +243,3 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
|
||||
|
||||
return []ui.Element{statusBar, editor, bottomBar}
|
||||
}
|
||||
|
||||
// getFilteredEntriesRaw returns browser entries filtered by the current search query.
|
||||
// Does not use the SortedEntries cache.
|
||||
func getFilteredEntriesRaw() []ui.ListItem {
|
||||
var filtered []ui.ListItem
|
||||
query := strings.ToLower(TheState.SearchQuery)
|
||||
if query == "" {
|
||||
filtered = browserEntries
|
||||
} else {
|
||||
for _, entry := range browserEntries {
|
||||
if strings.Contains(strings.ToLower(entry.Text), query) {
|
||||
filtered = append(filtered, entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
// getFilteredEntries returns browser entries filtered by the current search query.
|
||||
// If SortedEntries is non-nil (sort mode has been set), returns that instead.
|
||||
func getFilteredEntries() []ui.ListItem {
|
||||
if TheState.SortedEntries != nil {
|
||||
return TheState.SortedEntries
|
||||
}
|
||||
return getFilteredEntriesRaw()
|
||||
}
|
||||
|
||||
// sortEntries sorts the entries according to the given sort mode.
|
||||
func sortEntries(entries []ui.ListItem, mode SortMode) []ui.ListItem {
|
||||
// Make a copy to avoid modifying the original slice
|
||||
sorted := make([]ui.ListItem, len(entries))
|
||||
copy(sorted, entries)
|
||||
|
||||
// Parse date from subtext (format: "2025-01-15 • 4.2 KB")
|
||||
getDate := func(entry ui.ListItem) string {
|
||||
// Extract date part before the first space
|
||||
parts := strings.Split(entry.Subtext, " ")
|
||||
if len(parts) > 0 {
|
||||
return parts[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
switch mode {
|
||||
case SortByDateDesc:
|
||||
sort.Slice(sorted, func(i, j int) bool {
|
||||
return getDate(sorted[i]) > getDate(sorted[j])
|
||||
})
|
||||
case SortByDateAsc:
|
||||
sort.Slice(sorted, func(i, j int) bool {
|
||||
return getDate(sorted[i]) < getDate(sorted[j])
|
||||
})
|
||||
case SortByNameAsc:
|
||||
sort.Slice(sorted, func(i, j int) bool {
|
||||
return strings.ToLower(sorted[i].Text) < strings.ToLower(sorted[j].Text)
|
||||
})
|
||||
case SortByNameDesc:
|
||||
sort.Slice(sorted, func(i, j int) bool {
|
||||
return strings.ToLower(sorted[i].Text) > strings.ToLower(sorted[j].Text)
|
||||
})
|
||||
}
|
||||
return sorted
|
||||
}
|
||||
|
||||
// browserEntries is a static list of sample files for the browser page.
|
||||
// It is longer than the viewport so scrolling can be tested.
|
||||
var browserEntries = []ui.ListItem{
|
||||
{Text: "notes-2025-01-15.txt", Subtext: "2025-01-15 • 4.2 KB"},
|
||||
{Text: "meeting-2025-01-14.txt", Subtext: "2025-01-14 • 1.8 KB"},
|
||||
{Text: "todo-2025-01-14.txt", Subtext: "2025-01-14 • 892 B"},
|
||||
{Text: "ideas-2025-01-13.txt", Subtext: "2025-01-13 • 2.1 KB"},
|
||||
{Text: "diary-2025-01-12.txt", Subtext: "2025-01-12 • 3.5 KB"},
|
||||
{Text: "bookmarks-2025-01-11.txt", Subtext: "2025-01-11 • 6.7 KB"},
|
||||
{Text: "inbox-2025-01-10.txt", Subtext: "2025-01-10 • 12 KB"},
|
||||
{Text: "archive-2025-01-09.txt", Subtext: "2025-01-09 • 28 KB"},
|
||||
{Text: "draft-article.txt", Subtext: "2025-01-08 • 5.3 KB"},
|
||||
{Text: "recipe-cole-sl.txt", Subtext: "2025-01-07 • 1.1 KB"},
|
||||
{Text: "project-plan.txt", Subtext: "2025-01-06 • 8.4 KB"},
|
||||
{Text: "weekly-review.txt", Subtext: "2025-01-05 • 2.9 KB"},
|
||||
{Text: "changelog-v2.txt", Subtext: "2025-01-04 • 15 KB"},
|
||||
{Text: "README.txt", Subtext: "2025-01-03 • 512 B"},
|
||||
{Text: "scratch-pad.txt", Subtext: "2025-01-02 • 736 B"},
|
||||
{Text: "old-notes.txt", Subtext: "2025-01-01 • 3.1 KB"},
|
||||
{Text: "backup-jan.txt", Subtext: "2024-12-31 • 42 KB"},
|
||||
{Text: "annual-review.txt", Subtext: "2024-12-30 • 9.8 KB"},
|
||||
{Text: "december-log.txt", Subtext: "2024-12-29 • 7.2 KB"},
|
||||
{Text: "random-thoughts.txt", Subtext: "2024-12-28 • 1.5 KB"},
|
||||
{Text: "shopping-list.txt", Subtext: "2024-12-27 • 248 B"},
|
||||
{Text: "travel-ideas.txt", Subtext: "2024-12-26 • 2.3 KB"},
|
||||
{Text: "music-queue.txt", Subtext: "2024-12-25 • 4.7 KB"},
|
||||
{Text: "movie-wishlist.txt", Subtext: "2024-12-24 • 890 B"},
|
||||
{Text: "book-read-list.txt", Subtext: "2024-12-23 • 3.6 KB"},
|
||||
{Text: "podcast-notes.txt", Subtext: "2024-12-22 • 5.1 KB"},
|
||||
{Text: "quotes.txt", Subtext: "2024-12-21 • 6.2 KB"},
|
||||
{Text: "vocab.txt", Subtext: "2024-12-20 • 1.9 KB"},
|
||||
{Text: "word-of-day.txt", Subtext: "2024-12-19 • 384 B"},
|
||||
{Text: "memories.txt", Subtext: "2024-12-18 • 11 KB"},
|
||||
}
|
||||
|
||||
// BrowserLayout computes the element tree for the browser (file listing) page.
|
||||
func BrowserLayout(screenWidth, screenHeight ui.Dp, sortMode SortMode) []ui.Element {
|
||||
margin := ui.Dp(10)
|
||||
contentWidth := screenWidth - margin*2
|
||||
|
||||
// --- Header bar: directory name + sort toggle (gray background like editor StatusBar) ---
|
||||
headerHeight := ui.Dp(24)
|
||||
headerRegion := ui.Region{
|
||||
X: margin, Y: margin,
|
||||
W: contentWidth, H: headerHeight,
|
||||
}
|
||||
var sortLabel string
|
||||
switch sortMode {
|
||||
case SortByDateDesc:
|
||||
sortLabel = "Date ↓"
|
||||
case SortByDateAsc:
|
||||
sortLabel = "Date ↑"
|
||||
case SortByNameAsc:
|
||||
sortLabel = "Name ↑"
|
||||
case SortByNameDesc:
|
||||
sortLabel = "Name ↓"
|
||||
}
|
||||
headerBar := ui.NewContainer(
|
||||
headerRegion,
|
||||
ui.Color{R: 230, G: 230, B: 230, A: 255},
|
||||
[]ui.Element{
|
||||
ui.NewLabel("My Documents", 16, 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 ---
|
||||
searchHeight := ui.Dp(36)
|
||||
searchY := headerRegion.Y + headerRegion.H + margin/2
|
||||
searchRegion := ui.Region{
|
||||
X: margin, Y: searchY,
|
||||
W: contentWidth, H: searchHeight,
|
||||
}
|
||||
searchBar := ui.NewGioEditor("search_bar", searchRegion, &TheState.SearchEditor)
|
||||
TheState.SearchEditor.SingleLine = true
|
||||
|
||||
var searchPlaceholder ui.Element
|
||||
if TheState.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 := screenHeight - listY - margin // fill remaining height
|
||||
listRegion := ui.Region{
|
||||
X: margin, Y: listY,
|
||||
W: contentWidth, H: listHeight,
|
||||
}
|
||||
// Store list height for scroll clamping calculation
|
||||
TheState.BrowserListHeight = listHeight
|
||||
// Filter entries by search query (case-insensitive substring match)
|
||||
filteredEntries := getFilteredEntries()
|
||||
// Compute first visible row from Dp scroll offset
|
||||
rowHeight := ui.Dp(48)
|
||||
firstVisibleRow := int(TheState.BrowserScrollOffset / rowHeight)
|
||||
if firstVisibleRow < 0 {
|
||||
firstVisibleRow = 0
|
||||
}
|
||||
if firstVisibleRow > len(filteredEntries) {
|
||||
firstVisibleRow = len(filteredEntries)
|
||||
}
|
||||
visibleEntries := filteredEntries[firstVisibleRow:]
|
||||
list := ui.NewListView(
|
||||
"browser_list",
|
||||
visibleEntries,
|
||||
listRegion,
|
||||
TheState.BrowserScrollOffset, // Dp, not row index
|
||||
-1, // Selected: none
|
||||
[]ui.Interaction{{Gesture: ui.Scroll, Handler: HandleBrowserScroll}},
|
||||
)
|
||||
// Set row filenames so ListView.Draw can wire up click handlers
|
||||
list.RowFilenames = make([]string, len(visibleEntries))
|
||||
for i, entry := range visibleEntries {
|
||||
list.RowFilenames[i] = entry.Text
|
||||
}
|
||||
|
||||
elems := []ui.Element{
|
||||
headerBar,
|
||||
searchBar,
|
||||
}
|
||||
if searchPlaceholder != nil {
|
||||
elems = append(elems, searchPlaceholder)
|
||||
}
|
||||
elems = append(elems, list)
|
||||
return elems
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user