feat: sort markdown files by directory depth

The TUI file list sorted purely by note path, so markdown files in child directories could appear before files in the directory where Glow was launched.

Rank discovered files by path depth first, then preserve the existing path sort within each depth so root-level documents are listed before nested documents.

Fixes #272
This commit is contained in:
Asish Kumar 2026-05-25 03:17:45 +05:30
commit 49129c898a
No known key found for this signature in database
GPG key ID: 0EF072B1E0BA6FBA
2 changed files with 46 additions and 0 deletions

View file

@ -2,11 +2,24 @@ package ui
import (
"cmp"
"path/filepath"
"slices"
"strings"
)
func sortMarkdowns(mds []*markdown) {
slices.SortStableFunc(mds, func(a, b *markdown) int {
if n := cmp.Compare(markdownPathDepth(a.Note), markdownPathDepth(b.Note)); n != 0 {
return n
}
return cmp.Compare(a.Note, b.Note)
})
}
func markdownPathDepth(path string) int {
path = filepath.ToSlash(filepath.Clean(path))
if path == "." {
return 0
}
return strings.Count(path, "/")
}

33
ui/sort_test.go Normal file
View file

@ -0,0 +1,33 @@
package ui
import "testing"
func TestSortMarkdownsOrdersByDirectoryDepth(t *testing.T) {
mds := []*markdown{
{Note: "docs/reference/api.md"},
{Note: "docs/guide.md"},
{Note: "README.md"},
{Note: "CONTRIBUTING.md"},
{Note: "docs/reference/cli.md"},
}
sortMarkdowns(mds)
got := make([]string, 0, len(mds))
for _, md := range mds {
got = append(got, md.Note)
}
want := []string{
"CONTRIBUTING.md",
"README.md",
"docs/guide.md",
"docs/reference/api.md",
"docs/reference/cli.md",
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("expected %v, got %v", want, got)
}
}
}