From eb11fc30b355b32d4ee780ec4e7c2dbc8407eefb Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Wed, 18 Nov 2026 19:56:54 +0100 Subject: [PATCH] Name the element a change is in and let the diff show the lines around it Each group of changes gets a bar with its place in the settings (like router.firewall.rules[3], and the rule's zones) and buttons to show more lines above and below, or all that are hidden. Co-Authored-By: Claude Sonnet 5.5 --- pkgs/router-webui/diff.go | 216 ++++++++++++++++++++--- pkgs/router-webui/diff_test.go | 162 ++++++++++++++--- pkgs/router-webui/static/diff.js | 41 +++++ pkgs/router-webui/static/style.css | 9 +- pkgs/router-webui/templates/changes.html | 2 +- pkgs/router-webui/templates/layout.html | 1 + 6 files changed, 375 insertions(+), 56 deletions(-) create mode 100644 pkgs/router-webui/static/diff.js diff --git a/pkgs/router-webui/diff.go b/pkgs/router-webui/diff.go index bd3cd4d..6e6be68 100644 --- a/pkgs/router-webui/diff.go +++ b/pkgs/router-webui/diff.go @@ -2,17 +2,27 @@ package main import ( "encoding/json" + "fmt" "os" + "regexp" "strings" ) -// DiffRow is a line of a diff: Op is ' ' (unchanged, near a change), '-' -// (removed), '+' (added) or '.' (lines left out). Old and New are the line -// numbers in the two texts (0 where the line is not in that text). +// DiffRow is a line of a diff: Op is ' ' (unchanged), '-' (removed), '+' +// (added) or '.' (a bar above a group of lines: see diffView). Old and New are +// the line numbers in the two texts (0 where the line is not in that text). type DiffRow struct { Op byte Old, New int Text string + Hidden bool // unchanged and far from a change: shown when the page is asked to + + // Of a bar: where the group below it is in the settings (Path, and Label + // naming the element), how many hidden lines follow it (N) and which way + // there is more to show: Up (above the next change), Down (below the last). + Path, Label string + N int + Up, Down bool } // Class names the row for the page: add, del, ctx or gap. @@ -40,20 +50,29 @@ func (r DiffRow) Mark() string { // hunk headers: " " unchanged lines near a change, "-" removed, "+" added. // It returns "" when the texts are equal. func diffLines(a, b string) string { + all, keep := diffAll(a, b) var out strings.Builder - for _, r := range diffRows(a, b) { - if r.Op == '.' { - out.WriteString("…\n") + skipped := false + for k, l := range all { + if !keep[k] { + skipped = true continue } - out.WriteString(string(r.Op) + " " + r.Text + "\n") + if skipped { + out.WriteString("…\n") + skipped = false + } + out.WriteString(string(l.Op) + " " + l.Text + "\n") } return out.String() } -// diffRows is the diff of two texts with two lines of context around each -// change; nil when they are equal. -func diffRows(a, b string) []DiffRow { +// diffContext is how many unchanged lines are shown around a change. +const diffContext = 2 + +// diffAll is every line of the two texts in diff order, and which of them are +// a change or near one; nil when the texts are equal. +func diffAll(a, b string) ([]DiffRow, []bool) { x, y := strings.Split(a, "\n"), strings.Split(b, "\n") // Longest common subsequence table. lcs := make([][]int, len(x)+1) @@ -74,25 +93,23 @@ func diffRows(a, b string) []DiffRow { for i < len(x) || j < len(y) { switch { case i < len(x) && j < len(y) && x[i] == y[j]: - all = append(all, DiffRow{' ', i + 1, j + 1, x[i]}) + all = append(all, DiffRow{Op: ' ', Old: i + 1, New: j + 1, Text: x[i]}) i++ j++ case i < len(x) && (j == len(y) || lcs[i+1][j] >= lcs[i][j+1]): - all = append(all, DiffRow{'-', i + 1, 0, x[i]}) + all = append(all, DiffRow{Op: '-', Old: i + 1, Text: x[i]}) i++ default: - all = append(all, DiffRow{'+', 0, j + 1, y[j]}) + all = append(all, DiffRow{Op: '+', New: j + 1, Text: y[j]}) j++ } } - // Keep two lines of context around changes. - const ctx = 2 keep := make([]bool, len(all)) changed := false for k, l := range all { if l.Op != ' ' { changed = true - for d := -ctx; d <= ctx; d++ { + for d := -diffContext; d <= diffContext; d++ { if k+d >= 0 && k+d < len(all) { keep[k+d] = true } @@ -100,24 +117,171 @@ func diffRows(a, b string) []DiffRow { } } if !changed { + return nil, nil + } + return all, keep +} + +// diffView is the diff for the page: all lines, the ones far from a change +// marked Hidden, and a bar before each group of changed lines (and after the +// last) that names where in the settings the group is and offers the lines +// hidden next to it. nil when the texts are equal. +func diffView(a, b string) []DiffRow { + all, keep := diffAll(a, b) + if all == nil { return nil } + oldPaths, newPaths := jsonPaths(a), jsonPaths(b) + var oldDoc, newDoc any + json.Unmarshal([]byte(a), &oldDoc) + json.Unmarshal([]byte(b), &newDoc) + // where is the settings path of a changed line, and its element's name. + where := func(l DiffRow) (string, string) { + if l.Op == '+' && l.New-1 < len(newPaths) { + p := newPaths[l.New-1] + return pathName(p), pathLabel(newDoc, p) + } + if l.Op == '-' && l.Old-1 < len(oldPaths) { + p := oldPaths[l.Old-1] + return pathName(p), pathLabel(oldDoc, p) + } + return "", "" + } var rows []DiffRow - skipped := false - for k, l := range all { - if !keep[k] { - skipped = true + for k := 0; k < len(all); { + start := k + hidden := !keep[k] + for k < len(all) && keep[k] == !hidden { + k++ + } + if hidden { + bar := DiffRow{Op: '.', N: k - start, Down: start > 0, Up: k < len(all)} + if k < len(all) { + bar.Path, bar.Label = firstChange(all[k:], keep[k:], where) + } + rows = append(rows, bar) + for _, l := range all[start:k] { + l.Hidden = true + rows = append(rows, l) + } continue } - if skipped { - rows = append(rows, DiffRow{Op: '.'}) - skipped = false + if start == 0 { + bar := DiffRow{Op: '.'} + bar.Path, bar.Label = firstChange(all[start:k], keep[start:k], where) + rows = append(rows, bar) } - rows = append(rows, l) + rows = append(rows, all[start:k]...) } return rows } +// firstChange is where the first changed line of the lines that are kept is. +func firstChange(rows []DiffRow, keep []bool, where func(DiffRow) (string, string)) (string, string) { + for i, l := range rows { + if !keep[i] { + break + } + if l.Op != ' ' { + return where(l) + } + } + return "", "" +} + +// pathSeg is a step into the settings: a key, or an index into an array. +type pathSeg struct { + key string + index int + array bool // index is meant +} + +var jsonKey = regexp.MustCompile(`^"((?:[^"\\]|\\.)*)":`) + +// jsonPaths is, for each line of indented JSON, the path of the object or +// array the line is in (a line that opens one is in its parent). +func jsonPaths(text string) [][]pathSeg { + type frame struct { + seg pathSeg + array bool // the frame is an array + next int // index of the next element + } + var stack []frame + lines := strings.Split(text, "\n") + paths := make([][]pathSeg, len(lines)) + for i, line := range lines { + t := strings.TrimSpace(line) + for _, f := range stack { + if f.seg != (pathSeg{}) { + paths[i] = append(paths[i], f.seg) + } + } + switch { + case strings.HasPrefix(t, "}") || strings.HasPrefix(t, "]"): + if len(stack) > 0 { + stack = stack[:len(stack)-1] + } + case strings.HasSuffix(t, "{") || strings.HasSuffix(t, "["): + var seg pathSeg + if m := jsonKey.FindStringSubmatch(t); m != nil { + seg = pathSeg{key: m[1]} + } else if n := len(stack); n > 0 && stack[n-1].array { + seg = pathSeg{index: stack[n-1].next, array: true} + stack[n-1].next++ + } + stack = append(stack, frame{seg: seg, array: strings.HasSuffix(t, "[")}) + default: + if n := len(stack); n > 0 && stack[n-1].array { + stack[n-1].next++ + } + } + } + return paths +} + +// pathName writes a path like router.firewall.rules[3]. +func pathName(p []pathSeg) string { + var b strings.Builder + for _, s := range p { + if s.array { + fmt.Fprintf(&b, "[%d]", s.index) + continue + } + if b.Len() > 0 { + b.WriteByte('.') + } + b.WriteString(s.key) + } + return b.String() +} + +// pathLabel names the element at a path when it says what it is: a rule or a +// forward has a from and a to ("lan → family"). +func pathLabel(doc any, p []pathSeg) string { + v := doc + for _, s := range p { + switch c := v.(type) { + case map[string]any: + v = c[s.key] + case []any: + if !s.array || s.index >= len(c) { + return "" + } + v = c[s.index] + default: + return "" + } + } + if m, ok := v.(map[string]any); ok { + from, _ := m["from"].(string) + to, _ := m["to"].(string) + if from != "" && to != "" { + return from + " → " + to + } + } + return "" +} + // pretty re-indents JSON with sorted keys, so two spellings of the same // settings compare equal. func pretty(data []byte) string { @@ -134,9 +298,9 @@ func (s System) pendingChanges() string { return diffLines(s.pendingTexts()) } -// pendingRows is the same as rows, for the page. +// pendingRows is the same for the page (see diffView). func (s System) pendingRows() []DiffRow { - return diffRows(s.pendingTexts()) + return diffView(s.pendingTexts()) } // pendingTexts are the confirmed settings and the saved ones, normalized; two diff --git a/pkgs/router-webui/diff_test.go b/pkgs/router-webui/diff_test.go index 3746236..7549096 100644 --- a/pkgs/router-webui/diff_test.go +++ b/pkgs/router-webui/diff_test.go @@ -1,35 +1,143 @@ package main -import "testing" +import ( + "net/url" + "os" + "strings" + "testing" +) -func TestDiffRows(t *testing.T) { - if diffRows("a\nb", "a\nb") != nil { - t.Fatal("equal texts have rows") +func TestDiffLines(t *testing.T) { + if diffLines("a\nb", "a\nb") != "" { + t.Fatal("equal texts have a diff") } - rows := diffRows("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11", "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\neleven\n12") - var got []string - for _, r := range rows { - got = append(got, r.Class()+r.Mark()) - } - want := []string{"gap", "ctx", "ctx", "del-", "add+", "add+"} - if len(got) != len(want) { - t.Fatalf("rows %v", got) - } - for i := range want { - if got[i] != want[i] { - t.Fatalf("rows %v, want %v", got, want) - } - } - // The numbers are those of each side. - del, add := rows[3], rows[4] - if del.Old != 11 || del.New != 0 || del.Text != "11" || add.Old != 0 || add.New != 11 || add.Text != "eleven" { - t.Fatalf("%+v %+v", del, add) - } - if rows[5].New != 12 { - t.Fatalf("%+v", rows[5]) - } - // The text form is what it always was. if d := diffLines("a\nb", "a\nc"); d != " a\n- b\n+ c\n" { t.Fatalf("%q", d) } } + +func TestDiffView(t *testing.T) { + if diffView("a\nb", "a\nb") != nil { + t.Fatal("equal texts have rows") + } + rows := diffView("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11", "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\neleven\n12") + var got []string + for _, r := range rows { + s := r.Class() + r.Mark() + if r.Hidden { + s += "?" + } + got = append(got, s) + } + // A bar above the 8 hidden lines, then the changes with two lines of context. + want := []string{"gap", "ctx?", "ctx?", "ctx?", "ctx?", "ctx?", "ctx?", "ctx?", "ctx?", "ctx", "ctx", "del-", "add+", "add+"} + if strings.Join(got, " ") != strings.Join(want, " ") { + t.Fatalf("rows %v, want %v", got, want) + } + if bar := rows[0]; bar.N != 8 || !bar.Up || bar.Down { + t.Fatalf("the bar above %+v", bar) + } + // The numbers are those of each side, hidden lines included. + if r := rows[1]; r.Old != 1 || r.New != 1 { + t.Fatalf("%+v", r) + } + del, add := rows[11], rows[12] + if del.Old != 11 || del.New != 0 || del.Text != "11" || add.Old != 0 || add.New != 11 || add.Text != "eleven" { + t.Fatalf("%+v %+v", del, add) + } + + // Hidden lines between and after changes: a bar each, with the ways to show more. + rows = diffView("a\n1\n2\n3\n4\n5\n6\nb\n7\n8\n9\n10\n11", "A\n1\n2\n3\n4\n5\n6\nB\n7\n8\n9\n10\n11") + var bars []DiffRow + for _, r := range rows { + if r.Op == '.' { + bars = append(bars, r) + } + } + if len(bars) != 3 || bars[0].N != 0 || bars[1].N != 2 || !bars[1].Up || !bars[1].Down || bars[2].N != 3 || bars[2].Up || !bars[2].Down { + t.Fatalf("%+v", bars) + } +} + +const settingsText = `{ + "router": { + "firewall": { + "rules": [ + { + "from": "lan", + "to": "family" + }, + { + "from": "family", + "sources": [ + "10.0.0.1" + ], + "to": "lan" + } + ] + }, + "wan": {} + } +}` + +func TestJSONPaths(t *testing.T) { + lines := strings.Split(settingsText, "\n") + want := map[string]string{ + `"router": {`: "", + `"firewall": {`: "router", + `"rules": [`: "router.firewall", + `"from": "lan",`: "router.firewall.rules[0]", + `"sources": [`: "router.firewall.rules[1]", + `"10.0.0.1"`: "router.firewall.rules[1].sources", + `"to": "lan"`: "router.firewall.rules[1]", + `"wan": {}`: "router", + } + paths := jsonPaths(settingsText) + for i, line := range lines { + if w, ok := want[strings.TrimSpace(line)]; ok && pathName(paths[i]) != w { + t.Errorf("line %q is in %q, want %q", strings.TrimSpace(line), pathName(paths[i]), w) + } + } +} + +func TestDiffViewNamesTheElement(t *testing.T) { + after := strings.Replace(settingsText, `"10.0.0.1"`, `"10.0.0.1", + "10.0.0.2"`, 1) + var bar DiffRow + for _, r := range diffView(settingsText, after) { + if r.Op == '.' && r.Path != "" { + bar = r + break + } + } + if bar.Path != "router.firewall.rules[1].sources" || bar.Label != "" { + t.Fatalf("the bar names %q %q", bar.Path, bar.Label) + } + // A change in the rule itself names the rule and what it is about. + after = strings.Replace(settingsText, `"to": "lan"`, `"to": "lan", + "log": true`, 1) + bar = DiffRow{} + for _, r := range diffView(settingsText, after) { + if r.Op == '.' && r.Path != "" { + bar = r + break + } + } + if bar.Path != "router.firewall.rules[1]" || bar.Label != "family → lan" { + t.Fatalf("the bar names %q %q", bar.Path, bar.Label) + } +} + +func TestChangesPageShowsWhereAndMore(t *testing.T) { + a, sys := newTestApp(t) + h := a.routes() + cookie := do(h, "POST", "/login", url.Values{"password": {"hunter2hunter2"}}, nil).Result().Cookies()[0] + os.WriteFile(sys.confirmedPath(), []byte(`{"router":{"firewall":{"rules":[{"from":"lan","to":"family"}]},"a":1,"b":2,"c":3,"d":4,"e":5,"f":6}}`), 0o600) + os.WriteFile(sys.settingsPath(), []byte(`{"router":{"firewall":{"rules":[{"from":"lan","sources":["1.2.3.4"],"to":"family"}]},"a":1,"b":2,"c":3,"d":4,"e":5,"f":6}}`), 0o600) + body := do(h, "GET", "/changes", nil, cookie).Body.String() + for _, want := range []string{`router.firewall.rules[0]`, `lan → family`, `1.2.3.4`, `data-more="down"`, `class="drow ctx hid"`} { + if !strings.Contains(body, want) { + t.Errorf("the changes page lacks %q:\n%s", want, body) + } + } +} diff --git a/pkgs/router-webui/static/diff.js b/pkgs/router-webui/static/diff.js new file mode 100644 index 0000000..1037090 --- /dev/null +++ b/pkgs/router-webui/static/diff.js @@ -0,0 +1,41 @@ +// The bars of a diff (the Changes page) show the lines hidden next to a change: +// a bar sits above its hidden lines (.hid), which follow it up to the next line +// that is shown. "down" shows the first ones (below the change above the bar, and +// the bar moves after them), "up" the last ones (above the change below the bar). +(function () { + var STEP = 10; + + function hiddenAfter(bar) { + var rows = []; + for (var el = bar.nextElementSibling; el && el.classList.contains("hid"); el = el.nextElementSibling) rows.push(el); + return rows; + } + + document.addEventListener("click", function (e) { + var btn = e.target.closest ? e.target.closest("[data-more]") : null; + var bar = btn && btn.closest(".diff .gap"); + if (!bar) return; + e.preventDefault(); + var rows = hiddenAfter(bar); + var how = btn.getAttribute("data-more"); + var shown; + if (how === "down") { + shown = rows.slice(0, STEP); + shown.forEach(function (r) { r.classList.remove("hid"); }); + if (shown.length) bar.after(shown[shown.length - 1]); + } else if (how === "up") { + shown = rows.slice(-STEP); + shown.forEach(function (r) { r.classList.remove("hid"); }); + } else { + rows.forEach(function (r) { r.classList.remove("hid"); }); + } + var left = hiddenAfter(bar).length; + if (!left) { + // Nothing more to show: the bar stays only to say where the changes are. + bar.querySelectorAll("[data-more]").forEach(function (b) { b.remove(); }); + } else { + var all = bar.querySelector('[data-more="all"]'); + if (all) all.textContent = "Show " + left + " lines"; + } + }); +})(); diff --git a/pkgs/router-webui/static/style.css b/pkgs/router-webui/static/style.css index 58ff0a1..f3f452c 100644 --- a/pkgs/router-webui/static/style.css +++ b/pkgs/router-webui/static/style.css @@ -72,8 +72,13 @@ th[title] { cursor: help; text-decoration: underline dotted; text-underline-offs .diff .add .ln { background: color-mix(in srgb, var(--good) 28%, var(--surface)); } .diff .del { background: color-mix(in srgb, var(--bad) 14%, var(--surface)); } .diff .del .ln { background: color-mix(in srgb, var(--bad) 28%, var(--surface)); } -.diff .gap { background: var(--head); color: var(--muted); padding: .1rem 0; } -.diff .gaptext { padding-left: 7.5rem; user-select: none; } +.diff .hid { display: none; } +.diff .gap { background: var(--head); color: var(--muted); padding: .15rem 0; align-items: center; } +.diff .gap .more { flex: none; width: 7.6rem; padding: 0 .5rem; display: flex; gap: .6rem; justify-content: flex-end; user-select: none; } +.diff .gap .more:empty { display: none; } +.diff .gap button.link { font: inherit; text-decoration: none; padding: 0 .15rem; } +.diff .gap .path { padding: 0 .75rem; color: var(--fg); } +.diff .gap .path:first-child { padding-left: 8.2rem; } .dialog-question { margin: 0; font-size: 1.05rem; } .dialog-actions { display: flex; gap: .5rem; justify-content: flex-end; margin-top: 1.25rem; } .upload-card.wide { width: min(48rem, 100%); } diff --git a/pkgs/router-webui/templates/changes.html b/pkgs/router-webui/templates/changes.html index 05e4e59..28756db 100644 --- a/pkgs/router-webui/templates/changes.html +++ b/pkgs/router-webui/templates/changes.html @@ -5,7 +5,7 @@ Nothing is applied until you press Apply.

{{with .TokenEdit}}

{{.}}

{{end}}
-{{range .Rows}}{{if eq .Class "gap"}}
…
{{else}}
{{if .Old}}{{.Old}}{{end}}{{if .New}}{{.New}}{{end}}{{.Mark}}{{.Text}}
{{end}}{{end}} +{{range .Rows}}{{if eq .Class "gap"}}
{{if .Down}}{{end}}{{if .Up}}{{end}}{{if .N}}{{end}}{{if .Path}}{{.Path}}{{with .Label}} {{.}}{{end}}{{end}}
{{else}}
{{if .Old}}{{.Old}}{{end}}{{if .New}}{{.New}}{{end}}{{.Mark}}{{.Text}}
{{end}}{{end}}
diff --git a/pkgs/router-webui/templates/layout.html b/pkgs/router-webui/templates/layout.html index 1619eca..cee4b96 100644 --- a/pkgs/router-webui/templates/layout.html +++ b/pkgs/router-webui/templates/layout.html @@ -47,5 +47,6 @@ +