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
58 changes: 58 additions & 0 deletions internal/web/render_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,61 @@ func TestRenderUnknownPage(t *testing.T) {
t.Errorf("status = %d, want 500", rec.Code)
}
}

// The browser sorts IP columns by comparing these keys as plain strings, so
// their byte order has to be the addresses' numeric order.
func TestIPSortKeyOrdersNumerically(t *testing.T) {
ordered := []string{
"10.0.0.2",
"10.0.0.9",
"10.0.0.10",
"10.0.1.0/16",
"10.0.1.0/24",
"192.168.1.1",
"192.168.1.100",
"255.255.255.255",
// every IPv6 value follows every IPv4 one, including those that are
// numerically below the IPv4-mapped range
"::/0",
"::1",
"::ffff:10.0.0.1",
"2001:db8::1",
"2001:db8::a",
"2001:db8::10",
}
for i := 1; i < len(ordered); i++ {
a, b := ipSortKey(ordered[i-1]), ipSortKey(ordered[i])
if a >= b {
t.Errorf("ipSortKey(%q) = %q is not below ipSortKey(%q) = %q", ordered[i-1], a, ordered[i], b)
}
}
if a, b := ipSortKey("10.0.0.1"), ipSortKey("::ffff:10.0.0.1"); a == b {
t.Errorf("10.0.0.1 and its IPv4-mapped IPv6 form share the key %q", a)
}
if got := ipSortKey("not-an-ip"); got != "not-an-ip" {
t.Errorf("unparseable input: got %q, want it unchanged", got)
}
}

// Every table header that can be sorted is marked for app.js, and the cells
// under an IP column carry the server-built key rather than relying on text.
func TestRenderSortableHeaders(t *testing.T) {
s := &Server{tmpls: parseTemplates(), version: "dev"}
rec := httptest.NewRecorder()
s.render(rec, httptest.NewRequest(http.MethodGet, "/", nil), "subnets", pageData{
Title: "Subnets",
Data: []subnetRow{{ID: 1, CIDR: "10.0.0.0/24", Name: "lan", ScanEnabled: true, ScanIntervalSec: 300, LastScanAt: 1700000000}, {ID: 2, CIDR: "10.0.1.0/24"}},
})
body := rec.Body.String()
for _, want := range []string{
`<th data-sort="key">CIDR</th>`,
`<th data-sort="num" data-first="desc">Last scan</th>`,
`data-v="` + ipSortKey("10.0.0.0/24") + `"`,
`data-v="1700000000"`, // a real scan time sorts by its timestamp
`data-v=""`, // "never" sorts as empty, i.e. last
} {
if !strings.Contains(body, want) {
t.Errorf("subnets page: missing %q", want)
}
}
}
30 changes: 30 additions & 0 deletions internal/web/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"io/fs"
"log/slog"
"net/http"
"net/netip"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -76,10 +77,39 @@ type Server struct {
setupToken string
}

// ipSortKey turns an address or CIDR into a string whose byte order is its
// numeric order, so the browser can sort an IP column with a plain string
// compare (10.0.0.9 before 10.0.0.10, a /16 before the /24 at the same
// base). Anything unparseable sorts as itself.
//
// The key leads with the address family. As16 alone is not enough: it puts
// IPv4 at ::ffff:a.b.c.d, in the middle of IPv6 space, so ::1 would sort
// before every IPv4 address and ::ffff:10.0.0.1 would collide with 10.0.0.1.
func ipSortKey(s string) string {
if p, err := netip.ParsePrefix(s); err == nil {
return fmt.Sprintf("%s/%03d", addrSortKey(p.Addr()), p.Bits())
}
if a, err := netip.ParseAddr(s); err == nil {
return addrSortKey(a)
}
return s
}

// addrSortKey is "4" or "6" followed by the address as 32 hex digits, so
// all of IPv4 orders before all of IPv6 (IPv4-mapped IPv6 counts as IPv6).
func addrSortKey(a netip.Addr) string {
family := "6"
if a.Is4() {
family = "4"
}
return fmt.Sprintf("%s%x", family, a.As16())
}

var funcMap = template.FuncMap{
"fields": func(s string) []string {
return strings.Fields(s)
},
"ipKey": ipSortKey,
"relTime": func(u int64) string {
if u == 0 {
return "never"
Expand Down
174 changes: 174 additions & 0 deletions internal/web/static/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,180 @@
bindFilter();
bindConfirms();
bindRowEdit();
bindSort();
bindClip();
}

// A td.clip cell cuts long text off with an ellipsis. The full text is in
// its title, but a tooltip needs a mouse, so any cell that is actually
// truncated becomes a keyboard- and touch-operable toggle: click, Enter or
// Space expands it to wrap in place, and again collapses it. Cells that
// fit are left alone, so they add no tab stops.
//
// The cell deliberately keeps its table-cell role: the text is only cut
// off visually, so a screen reader already reads all of it in its column,
// and turning the cell into a button would take that away.
//
// Controls inside the cell (links, the inline-edit input) keep their own
// behaviour, so a click on one of them is not a toggle.
function isClipToggle(e, td) {
return td.classList.contains('clipped') && !e.target.closest('a, input, button, select, textarea');
}

function bindClip() {
const cells = Array.prototype.slice.call(document.querySelectorAll('td.clip'));
if (!cells.length) return;

function measure() {
cells.forEach(function (td) {
if (td.classList.contains('expanded')) return;
const cut = td.scrollWidth > td.clientWidth;
td.classList.toggle('clipped', cut);
if (cut) td.tabIndex = 0;
else td.removeAttribute('tabindex');
});
}

function toggle(td) {
if (!td.classList.toggle('expanded')) measure();
}

cells.forEach(function (td) {
td.addEventListener('click', function (e) {
if (isClipToggle(e, td)) toggle(td);
});
td.addEventListener('keydown', function (e) {
if (e.target !== td || (e.key !== 'Enter' && e.key !== ' ')) return;
e.preventDefault();
toggle(td);
});
});

// Whether a cell is cut off depends on its column's width and its own
// content, and both move without any window resize: the web font
// swapping in after first paint (font-display: swap), the filter hiding
// rows, a row entering edit mode (which swaps the text for an input).
// So re-measure when the fonts settle, whenever a clip cell changes
// size, and after any click or typing on the page, not only on resize.
let timer = null;
function schedule() {
clearTimeout(timer);
timer = setTimeout(measure, 150);
}
window.addEventListener('resize', schedule);
document.addEventListener('click', schedule);
document.addEventListener('input', schedule);
if (document.fonts) {
// A font that fails to load changes nothing to measure; the resize
// paths below still cover every later layout change.
document.fonts.ready.then(measure).catch(function () { /* nothing to re-measure */ });
}
if (typeof ResizeObserver === 'function') {
const observer = new ResizeObserver(schedule);
cells.forEach(function (td) { observer.observe(td); });
}
measure();
}

// Click-to-sort for every table whose header cells carry data-sort:
// "text" (natural, case-insensitive), "num", or "key" (exact code-unit
// order, for the server-built IP sort keys, which a natural compare would
// misread as numbers). A cell sorts by its data-v attribute when it has
// one (timestamps, IP keys, raw counts) and by its text otherwise. Empty
// values always sink to the bottom. The choice is remembered per table for
// the browser session, so saving a row edit doesn't reshuffle the list.
//
// sortValue reads one cell's sort value: null when empty (or not a number
// in a numeric column), so the caller can sink it.
function sortValue(tr, col, numeric) {
const td = tr.cells[col];
if (!td) return null;
const raw = (td.dataset.v === undefined ? td.textContent : td.dataset.v).trim();
if (raw === '') return null;
if (!numeric) return raw;
const n = Number.parseFloat(raw);
return Number.isNaN(n) ? null : n;
}

function compareExact(a, b) {
if (a < b) return -1;
return a > b ? 1 : 0;
}

function sortArrow(dir) {
return dir > 0 ? '\u2191' : '\u2193';
}

// nextSortDir: an unsorted column starts in its preferred direction
// (data-first="desc" for times), a sorted one flips.
function nextSortDir(th) {
const current = th.getAttribute('aria-sort');
if (current === null) return th.dataset.first === 'desc' ? -1 : 1;
return current === 'ascending' ? -1 : 1;
}

function bindSort() {
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });

document.querySelectorAll('table').forEach(function (table, tableIndex) {
const body = table.tBodies[0];
const heads = Array.prototype.slice.call(table.querySelectorAll('thead th[data-sort]'));
if (!body || !heads.length || body.querySelector('td.empty-row')) return;
const storeKey = 'sort:' + location.pathname + '#' + tableIndex;

function apply(th, dir) {
const col = th.cellIndex;
const numeric = th.dataset.sort === 'num';
const exact = th.dataset.sort === 'key';
const rows = Array.prototype.map.call(body.rows, function (tr, i) {
return { tr: tr, v: sortValue(tr, col, numeric), i: i };
});
rows.sort(function (a, b) {
if (a.v === null || b.v === null) {
if (a.v === b.v) return a.i - b.i;
return a.v === null ? 1 : -1;
}
let c;
if (numeric) c = a.v - b.v;
else if (exact) c = compareExact(a.v, b.v);
else c = collator.compare(a.v, b.v);
return c === 0 ? a.i - b.i : c * dir;
});
rows.forEach(function (r) { body.appendChild(r.tr); });

heads.forEach(function (h) {
const on = h === th;
h.classList.toggle('sorted', on);
if (on) h.setAttribute('aria-sort', dir > 0 ? 'ascending' : 'descending');
else h.removeAttribute('aria-sort');
h.querySelector('.arrow').textContent = on ? sortArrow(dir) : '';
});
try { sessionStorage.setItem(storeKey, col + ':' + dir); } catch (e) { /* private mode */ }
}

heads.forEach(function (th) {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'th-sort';
while (th.firstChild) btn.appendChild(th.firstChild);
const arrow = document.createElement('span');
arrow.className = 'arrow';
arrow.setAttribute('aria-hidden', 'true');
btn.appendChild(arrow);
th.appendChild(btn);
btn.addEventListener('click', function () {
apply(th, nextSortDir(th));
});
});

let saved = null;
try { saved = sessionStorage.getItem(storeKey); } catch (e) { /* private mode */ }
if (saved) {
const parts = saved.split(':');
const th = heads.find(function (h) { return h.cellIndex === Number(parts[0]); });
if (th) apply(th, parts[1] === '-1' ? -1 : 1);
}
});
}

function bindRowEdit() {
Expand Down
Loading