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 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 19:56:54 +01:00
co-authored by Claude Sonnet 5.5
parent f31262df31
commit eb11fc30b3
6 changed files with 375 additions and 56 deletions
+190 -26
View File
@@ -2,17 +2,27 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt"
"os" "os"
"regexp"
"strings" "strings"
) )
// DiffRow is a line of a diff: Op is ' ' (unchanged, near a change), '-' // DiffRow is a line of a diff: Op is ' ' (unchanged), '-' (removed), '+'
// (removed), '+' (added) or '.' (lines left out). Old and New are the line // (added) or '.' (a bar above a group of lines: see diffView). Old and New are
// numbers in the two texts (0 where the line is not in that text). // the line numbers in the two texts (0 where the line is not in that text).
type DiffRow struct { type DiffRow struct {
Op byte Op byte
Old, New int Old, New int
Text string 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. // 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. // hunk headers: " " unchanged lines near a change, "-" removed, "+" added.
// It returns "" when the texts are equal. // It returns "" when the texts are equal.
func diffLines(a, b string) string { func diffLines(a, b string) string {
all, keep := diffAll(a, b)
var out strings.Builder var out strings.Builder
for _, r := range diffRows(a, b) { skipped := false
if r.Op == '.' { for k, l := range all {
out.WriteString("…\n") if !keep[k] {
skipped = true
continue 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() return out.String()
} }
// diffRows is the diff of two texts with two lines of context around each // diffContext is how many unchanged lines are shown around a change.
// change; nil when they are equal. const diffContext = 2
func diffRows(a, b string) []DiffRow {
// 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") x, y := strings.Split(a, "\n"), strings.Split(b, "\n")
// Longest common subsequence table. // Longest common subsequence table.
lcs := make([][]int, len(x)+1) lcs := make([][]int, len(x)+1)
@@ -74,25 +93,23 @@ func diffRows(a, b string) []DiffRow {
for i < len(x) || j < len(y) { for i < len(x) || j < len(y) {
switch { switch {
case i < len(x) && j < len(y) && x[i] == y[j]: 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++ i++
j++ j++
case i < len(x) && (j == len(y) || lcs[i+1][j] >= lcs[i][j+1]): 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++ i++
default: default:
all = append(all, DiffRow{'+', 0, j + 1, y[j]}) all = append(all, DiffRow{Op: '+', New: j + 1, Text: y[j]})
j++ j++
} }
} }
// Keep two lines of context around changes.
const ctx = 2
keep := make([]bool, len(all)) keep := make([]bool, len(all))
changed := false changed := false
for k, l := range all { for k, l := range all {
if l.Op != ' ' { if l.Op != ' ' {
changed = true changed = true
for d := -ctx; d <= ctx; d++ { for d := -diffContext; d <= diffContext; d++ {
if k+d >= 0 && k+d < len(all) { if k+d >= 0 && k+d < len(all) {
keep[k+d] = true keep[k+d] = true
} }
@@ -100,24 +117,171 @@ func diffRows(a, b string) []DiffRow {
} }
} }
if !changed { 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 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 var rows []DiffRow
skipped := false for k := 0; k < len(all); {
for k, l := range all { start := k
if !keep[k] { hidden := !keep[k]
skipped = true for k < len(all) && keep[k] == !hidden {
continue k++
} }
if skipped { if hidden {
rows = append(rows, DiffRow{Op: '.'}) bar := DiffRow{Op: '.', N: k - start, Down: start > 0, Up: k < len(all)}
skipped = false 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) rows = append(rows, l)
} }
continue
}
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, all[start:k]...)
}
return rows 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 // pretty re-indents JSON with sorted keys, so two spellings of the same
// settings compare equal. // settings compare equal.
func pretty(data []byte) string { func pretty(data []byte) string {
@@ -134,9 +298,9 @@ func (s System) pendingChanges() string {
return diffLines(s.pendingTexts()) 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 { func (s System) pendingRows() []DiffRow {
return diffRows(s.pendingTexts()) return diffView(s.pendingTexts())
} }
// pendingTexts are the confirmed settings and the saved ones, normalized; two // pendingTexts are the confirmed settings and the saved ones, normalized; two
+135 -27
View File
@@ -1,35 +1,143 @@
package main package main
import "testing" import (
"net/url"
"os"
"strings"
"testing"
)
func TestDiffRows(t *testing.T) { func TestDiffLines(t *testing.T) {
if diffRows("a\nb", "a\nb") != nil { if diffLines("a\nb", "a\nb") != "" {
t.Fatal("equal texts have rows") 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" { if d := diffLines("a\nb", "a\nc"); d != " a\n- b\n+ c\n" {
t.Fatalf("%q", d) 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)
}
}
}
+41
View File
@@ -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";
}
});
})();
+7 -2
View File
@@ -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 .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 { background: color-mix(in srgb, var(--bad) 14%, var(--surface)); }
.diff .del .ln { background: color-mix(in srgb, var(--bad) 28%, 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 .hid { display: none; }
.diff .gaptext { padding-left: 7.5rem; user-select: 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-question { margin: 0; font-size: 1.05rem; }
.dialog-actions { display: flex; gap: .5rem; justify-content: flex-end; margin-top: 1.25rem; } .dialog-actions { display: flex; gap: .5rem; justify-content: flex-end; margin-top: 1.25rem; }
.upload-card.wide { width: min(48rem, 100%); } .upload-card.wide { width: min(48rem, 100%); }
+1 -1
View File
@@ -5,7 +5,7 @@
Nothing is applied until you press Apply.</p> Nothing is applied until you press Apply.</p>
{{with .TokenEdit}}<p class="error">{{.}}</p>{{end}} {{with .TokenEdit}}<p class="error">{{.}}</p>{{end}}
<div class="diff" role="table" aria-label="Changes"> <div class="diff" role="table" aria-label="Changes">
{{range .Rows}}{{if eq .Class "gap"}}<div class="drow gap" role="row"><span class="gaptext">…</span></div>{{else}}<div class="drow {{.Class}}" role="row"><span class="ln" role="cell">{{if .Old}}{{.Old}}{{end}}</span><span class="ln" role="cell">{{if .New}}{{.New}}{{end}}</span><span class="mk" role="cell">{{.Mark}}</span><code role="cell">{{.Text}}</code></div>{{end}}{{end}} {{range .Rows}}{{if eq .Class "gap"}}<div class="drow gap" role="row" data-n="{{.N}}"><span class="more">{{if .Down}}<button type="button" class="link" data-more="down" title="Show 10 more lines below the change above">↓</button>{{end}}{{if .Up}}<button type="button" class="link" data-more="up" title="Show 10 more lines above the next change">↑</button>{{end}}{{if .N}}<button type="button" class="link" data-more="all" title="Show every line that is hidden here">Show {{.N}} lines</button>{{end}}</span>{{if .Path}}<span class="path">{{.Path}}{{with .Label}} <span class="muted">{{.}}</span>{{end}}</span>{{end}}</div>{{else}}<div class="drow {{.Class}}{{if .Hidden}} hid{{end}}" role="row"><span class="ln" role="cell">{{if .Old}}{{.Old}}{{end}}</span><span class="ln" role="cell">{{if .New}}{{.New}}{{end}}</span><span class="mk" role="cell">{{.Mark}}</span><code role="cell">{{.Text}}</code></div>{{end}}{{end}}
</div> </div>
<div class="actions"> <div class="actions">
<form method="post" action="/apply"><input type="hidden" name="csrf" value="{{$.CSRF}}"><button>Apply</button></form> <form method="post" action="/apply"><input type="hidden" name="csrf" value="{{$.CSRF}}"><button>Apply</button></form>
+1
View File
@@ -47,5 +47,6 @@
<script src="/static/live.js"></script> <script src="/static/live.js"></script>
<script src="/static/upload.js"></script> <script src="/static/upload.js"></script>
<script src="/static/dialog.js"></script> <script src="/static/dialog.js"></script>
<script src="/static/diff.js"></script>
</body> </body>
</html> </html>