Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,9 +337,18 @@ compression: most large files do not compress anyway.

Clicking an image, a video, an audio file or a PDF opens it in a viewer,
with Download next to it and the previous and next ones of its folder a
click or an arrow key away (Escape goes back to the folder). Listings show
thumbnails of JPEG, PNG, GIF, WebP and BMP images, and a link to a single
file shows it on the link's page. The same works with a query: `?view` (the
click, an arrow key or (for pictures, on touch screens) a swipe away, in
the order the folder was sorted in; Escape goes back to the folder, and
the next picture is fetched ahead. Listings show thumbnails of JPEG, PNG,
GIF, WebP and BMP images, and a link to a single file shows it on the
link's page.

Folders can be laid out as a list or as a grid of thumbnails, with the
buttons next to Download zip; the grid keeps everything else of the list
(ticking entries, their ⋯ menu, sorting, filtering). Folders whose files
are mostly pictures and videos (two thirds of them, at least three) open
as a grid. A layout chosen with the buttons is remembered for the folder,
in the browser; `?layout=grid` or `?layout=list` asks for one in a link. The same works with a query: `?view` (the
viewer), `?inline` (the file, to be shown in a browser) and `?thumb` (a
thumbnail of at most 256×256 pixels).

Expand Down
65 changes: 65 additions & 0 deletions internal/server/gallery_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package server

import (
"os"
"path/filepath"
"strings"
"testing"
"time"
)

func TestGallery(t *testing.T) {
f := newFixture(t)
html := []string{"Accept", "text/html"}
// Pictures named against the order they were taken in.
for i, name := range []string{"c.jpg", "b.png", "a.jpg"} {
f.write(t, "photos/"+name, "not really a picture")
mod := time.Date(2026, 1, 1+i, 0, 0, 0, 0, time.UTC)
if err := os.Chtimes(filepath.Join(f.dir, "photos", name), mod, mod); err != nil {
t.Fatal(err)
}
}
f.write(t, "photos/notes.txt", "notes")
f.write(t, "docs/a.txt", "a")
f.write(t, "docs/b.pdf", "b")
f.write(t, "docs/c.jpg", "c")

// Folders of mostly pictures and videos are a grid, others a list.
_, body := f.do(t, "GET", "/photos/", html...)
if !strings.Contains(body, `<table class="files grid" id="entries" data-layout="grid" data-auto>`) ||
!strings.Contains(body, `<a class="btn" href="?layout=grid" data-layout="grid" title="Grid" aria-label="Grid" aria-current="true">`) {
t.Errorf("photos: %s", body)
}
_, body = f.do(t, "GET", "/docs/", html...)
if !strings.Contains(body, `<table class="files" id="entries" data-layout="list" data-auto>`) {
t.Errorf("docs: %s", body)
}
// As asked, and kept when sorting.
_, body = f.do(t, "GET", "/photos/?layout=list&sort=modified", html...)
if !strings.Contains(body, `<table class="files" id="entries" data-layout="list">`) ||
!strings.Contains(body, `href="?sort=modified&amp;order=desc&amp;layout=list"`) ||
!strings.Contains(body, `href="?layout=grid&amp;sort=modified"`) {
t.Errorf("asked for a list: %s", body)
}
// The viewer goes through the folder in the order it was listed in.
_, body = f.do(t, "GET", "/photos/?sort=modified&order=desc", html...)
if !strings.Contains(body, `href="/photos/a.jpg?view&amp;sort=modified&amp;order=desc"`) {
t.Errorf("viewer links: %s", body)
}
_, body = f.do(t, "GET", "/photos/b.png?view&sort=modified&order=desc", html...)
for _, want := range []string{
`id="prev" href="/photos/a.jpg?view&amp;sort=modified&amp;order=desc"`,
`id="next" href="/photos/c.jpg?view&amp;sort=modified&amp;order=desc"`,
`<link rel="prefetch" href="/photos/c.jpg?inline" as="image">`,
`data-folder="/photos/?sort=modified&amp;order=desc"`,
"2 of 3",
} {
if !strings.Contains(body, want) {
t.Errorf("viewer lacks %s", want)
}
}
_, body = f.do(t, "GET", "/photos/b.png?view", html...)
if !strings.Contains(body, `id="prev" href="/photos/a.jpg?view"`) || !strings.Contains(body, `data-folder="/photos/"`) {
t.Errorf("by name: %s", body)
}
}
108 changes: 86 additions & 22 deletions internal/server/listing.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,25 +144,30 @@ func (s *Server) usageOf(name string) (*usage, error) {

type listing struct {
page
Path string
Action string // where this folder's forms post to
Home string // where the first crumb leads
Crumbs []crumb
Parent string
Items []listItem
Upload *uploadForm
Mkdir bool
Sort string
Desc bool
Summary string
Uploaded int
Created *listItem
Renamed *listItem
Restored *listItem
Deleted int // entries just deleted
Trashed bool // they went to the trash
Undo *undo
Moved *moved // entries just moved or copied elsewhere
Path string
Action string // where this folder's forms post to
Home string // where the first crumb leads
Crumbs []crumb
Parent string
Items []listItem
Upload *uploadForm
Mkdir bool
Sort string
Desc bool
// Layout lays the entries out as a "list", or as a "grid" of
// thumbnails; LayoutAuto is set when it was picked from what the
// folder holds rather than asked for (see layoutOf).
Layout string
LayoutAuto bool
Summary string
Uploaded int
Created *listItem
Renamed *listItem
Restored *listItem
Deleted int // entries just deleted
Trashed bool // they went to the trash
Undo *undo
Moved *moved // entries just moved or copied elsewhere
// TrashKeep says how long deleted entries stay in the trash; "" if
// they are deleted at once.
TrashKeep string
Expand Down Expand Up @@ -295,12 +300,70 @@ func (l listing) PickHint() string {
return acts[0]
}

// SortHref links a column header: a second click reverses the order.
// SortHref links a column header: a second click reverses the order. A
// layout asked for stays.
func (l listing) SortHref(col string) string {
q := "?sort=" + col
if l.Sort == col && !l.Desc {
return "?sort=" + col + "&order=desc"
q += "&order=desc"
}
return "?sort=" + col
if !l.LayoutAuto {
q += "&layout=" + l.Layout
}
return q
}

// LayoutHref links the layout: list or grid, in the same order.
func (l listing) LayoutHref(layout string) string {
q := "?layout=" + layout
if s := sortQuery(l.Sort, l.Desc); s != "" {
q += "&" + s
}
return q
}

// ViewQuery opens an entry in the viewer, which goes through the folder in
// its order.
func (l listing) ViewQuery() string {
if s := sortQuery(l.Sort, l.Desc); s != "" {
return "?view&" + s
}
return "?view"
}

// sortQuery is the query of an order other than by name, "" for that.
func sortQuery(col string, desc bool) string {
q := ""
if col != "name" {
q = "sort=" + col
}
if desc {
q += "&order=desc"
}
return strings.TrimPrefix(q, "&")
}

// layoutOf picks how to lay out items: as ?layout= asks, or else as a grid
// of thumbnails when pictures and videos are most of the files in it.
func layoutOf(c fiber.Ctx, items []listItem) (layout string, auto bool) {
switch q := c.Query("layout"); q {
case "grid", "list":
return q, false
}
media, files := 0, 0
for _, it := range items {
if it.IsDir {
continue
}
files++
if it.Thumb || it.Preview == "image" || it.Preview == "video" {
media++
}
}
if media >= 3 && 3*media >= 2*files {
return "grid", true
}
return "list", true
}

// SortState is a column's aria-sort value.
Expand Down Expand Up @@ -376,6 +439,7 @@ func (s *Server) serveDir(c fiber.Ctx, dir *os.File, urlPath, realPath string, w
}
data.Sort, data.Desc = sortOrder(c)
sortItems(data.Items, data.Sort, data.Desc)
data.Layout, data.LayoutAuto = layoutOf(c, data.Items)

switch {
case rel == "/":
Expand Down
33 changes: 25 additions & 8 deletions internal/server/preview.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,13 @@ type viewerPage struct {
Prev, Next *viewerLink
}

type viewerLink struct{ Name, Href string }
// viewerLink leads to another file of the folder in the viewer; Src is the
// file itself, for pictures, to fetch ahead.
type viewerLink struct{ Name, Href, Src string }

// serveViewer shows the file f at urlPath in a page of its own, with links
// to the previous and next files of its folder that can be shown too.
// to the previous and next files of its folder that can be shown too, in
// the order the folder was listed in (?sort and ?order).
func (s *Server) serveViewer(c fiber.Ctx, f *os.File, info fs.FileInfo, urlPath string, at fileAt) error {
name := path.Base(urlPath)
ctype, kind := inlineType(f, name)
Expand All @@ -174,14 +177,19 @@ func (s *Server) serveViewer(c fiber.Ctx, f *os.File, info fs.FileInfo, urlPath
if ctype != "" {
v.Kind = kind
}
v.Position, v.Prev, v.Next = s.around(path.Dir(urlPath), name, at)
col, desc := sortOrder(c)
if q := sortQuery(col, desc); q != "" {
v.Folder += "?" + q
}
v.Position, v.Prev, v.Next = s.around(path.Dir(urlPath), name, at, col, desc)
return s.render(c, fiber.StatusOK, "viewer", v)
}

// around places the file name in its folder dirPath among the files that
// can be shown, as the folder lists them: its position, and the files
// before and after it. Folders the visitor may not list place it nowhere.
func (s *Server) around(dirPath, name string, at fileAt) (string, *viewerLink, *viewerLink) {
// can be shown, as the folder lists them by col: its position, and the
// files before and after it. Folders the visitor may not list place it
// nowhere.
func (s *Server) around(dirPath, name string, at fileAt, col string, desc bool) (string, *viewerLink, *viewerLink) {
d, _, dirReal, err := s.lookup(dirPath, at.allow)
if err != nil {
return "", nil, nil
Expand All @@ -192,7 +200,11 @@ func (s *Server) around(dirPath, name string, at fileAt) (string, *viewerLink, *
return "", nil, nil
}
shown := slices.DeleteFunc(items, func(it listItem) bool { return it.IsDir || it.Preview == "" })
sortItems(shown, "name", false)
sortItems(shown, col, desc)
view := "?view"
if q := sortQuery(col, desc); q != "" {
view += "&" + q
}
i := slices.IndexFunc(shown, func(it listItem) bool { return it.Name == name })
if i < 0 {
return "", nil, nil
Expand All @@ -201,7 +213,12 @@ func (s *Server) around(dirPath, name string, at fileAt) (string, *viewerLink, *
if j < 0 || j >= len(shown) {
return nil
}
return &viewerLink{Name: shown[j].Name, Href: escapePath(at.base+path.Join(path.Dir(at.rel), shown[j].Name)) + "?view"}
href := escapePath(at.base + path.Join(path.Dir(at.rel), shown[j].Name))
l := &viewerLink{Name: shown[j].Name, Href: href + view}
if shown[j].Preview == "image" {
l.Src = href + "?inline"
}
return l
}
return strconv.Itoa(i+1) + " of " + strconv.Itoa(len(shown)), link(i - 1), link(i + 1)
}
1 change: 1 addition & 0 deletions internal/server/share.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ func (s *Server) serveSharedDir(c fiber.Ctx, dir *os.File, view *shareView, urlP
}
data.Sort, data.Desc = sortOrder(c)
sortItems(data.Items, data.Sort, data.Desc)
data.Layout, data.LayoutAuto = layoutOf(c, data.Items)
return s.render(c, fiber.StatusOK, "listing", data)
}

Expand Down
49 changes: 48 additions & 1 deletion internal/server/templates/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
}

// The viewer: arrows go to the previous and next file, Escape back to the
// folder.
// folder; on touch screens, so do swipes across a picture.
const stage = $("#stage");
if (stage) {
document.addEventListener("keydown", e => {
Expand All @@ -72,6 +72,51 @@
if (to) location.assign(to.href);
else if (e.key === "Escape") location.assign(stage.dataset.folder);
});
if (stage.dataset.kind === "image") {
let start = null;
stage.addEventListener("pointerdown", e => {
if (e.pointerType !== "mouse") start = { x: e.clientX, y: e.clientY };
});
stage.addEventListener("pointerup", e => {
if (!start) return;
const dx = e.clientX - start.x;
const dy = e.clientY - start.y;
start = null;
if (Math.abs(dx) < 60 || Math.abs(dy) > Math.abs(dx) / 2) return;
const to = dx < 0 ? $("#next") : $("#prev");
if (to) location.assign(to.href);
});
stage.addEventListener("pointercancel", () => { start = null; });
}
}

// The list or grid of a folder: a choice made here is remembered for the
// folder, on this device.
const entries = $("#entries");
if (entries) {
const key = "goftp-layout:" + location.pathname;
const apply = layout => {
entries.classList.toggle("grid", layout === "grid");
entries.dataset.layout = layout;
for (const b of $$(".layout-toggle [data-layout]")) {
if (b.dataset.layout === layout) b.setAttribute("aria-current", "true");
else b.removeAttribute("aria-current");
}
};
let saved = null;
try {
saved = localStorage.getItem(key);
} catch {}
if ("auto" in entries.dataset && (saved === "grid" || saved === "list")) apply(saved);
for (const b of $$(".layout-toggle [data-layout]")) {
b.addEventListener("click", e => {
e.preventDefault();
apply(b.dataset.layout);
try {
localStorage.setItem(key, b.dataset.layout);
} catch {}
});
}
}

// Filtering the listing; "/" jumps to the filter, Escape clears it.
Expand Down Expand Up @@ -544,6 +589,8 @@
const update = () => {
const n = boxes.filter(b => b.checked).length;
for (const b of boxes) b.closest("tr").classList.toggle("ticked", b.checked);
// In the grid, every box shows once one is ticked.
if (entries) entries.classList.toggle("picking", n > 0);
picked.hidden = n === 0;
count.textContent = `${n} picked`;
clear.hidden = n === 0;
Expand Down
Loading
Loading