diff --git a/pkg/ui/panes/diffviewer/delta_args_test.go b/pkg/ui/panes/diffviewer/delta_args_test.go index dfe3c84..a72da48 100644 --- a/pkg/ui/panes/diffviewer/delta_args_test.go +++ b/pkg/ui/panes/diffviewer/delta_args_test.go @@ -35,11 +35,15 @@ func TestMakeDeltaArgs(t *testing.T) { func TestMakeDeltaEnv(t *testing.T) { t.Setenv("GIT_CONFIG_PARAMETERS", "'delta.navigate'='true'") - if got := makeDeltaEnv(deltaOpts{SideBySide: true}); !slices.Equal(got, os.Environ()) { - t.Fatalf("themed: expected the plain environment, got %q", got) + wantEnv := append(os.Environ(), "OSC1717=V1") + if got := makeDeltaEnv(deltaOpts{SideBySide: true}); !slices.Equal(got, wantEnv) { + t.Fatalf("themed: expected %q, got %q", wantEnv, got) } env := makeDeltaEnv(deltaOpts{UseUserDeltaTheme: true}) + if !slices.Contains(env, "OSC1717=V1") { + t.Errorf("user delta theme: expected OSC1717=V1 in %q", env) + } got := env[len(env)-1] want := "GIT_CONFIG_PARAMETERS='delta.navigate'='true' 'delta.side-by-side'='false'" if got != want { diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 9eaf45b..c52978e 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -42,7 +42,8 @@ func cacheKey(path string, sideBySide bool) string { } type diffLine struct { - item item.Item + item item.Item + records []oscRecord } func (o diffLine) GetItem() item.Item { @@ -95,8 +96,31 @@ type Model struct { useUserDeltaTheme bool preamble string sb common.Scrollbar + // shown are the lines on screen: the last render while a new one is pending. + shown []diffLine + // anchor is where to scroll back to once the re-rendered diff is shown. + anchor *scrollAnchor } +// scrollAnchor is where to scroll back to after a re-render +type scrollAnchor struct { + // whether the user explicitly navigated to the top or bottom + edge anchorEdge + + // otherwise - the position the view was in: the line's osc record and the view's offset from its first row. + oscRec oscRecord + offset int +} + +// anchorEdge is the edge of the diff an anchor sticks to, if any. +type anchorEdge int + +const ( + edgeNone anchorEdge = iota + edgeTop + edgeBottom +) + // SetPreamble stores the preamble text (e.g. commit metadata from git show). func (m *Model) SetPreamble(preamble string) { m.preamble = preamble @@ -228,13 +252,23 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { } node.diff = msg.lines if node == m.file || node == m.dir { - m.fvp.SetObjects(msg.lines) + m.setLines(msg.lines) } } + edge := edgeNone + if k, ok := msg.(tea.KeyPressMsg); ok && !m.fvp.FilterFocused() { + if key.Matches(k, ViewportKeyMap.Top) { + edge = edgeTop + } else if key.Matches(k, ViewportKeyMap.Bottom) { + edge = edgeBottom + } + } + row := m.currentRow() fvp, fvpCmd := m.fvp.Update(msg) cmds = append(cmds, fvpCmd) m.fvp = fvp + m.reanchor(row, edge) return m, tea.Batch(cmds...) } @@ -257,6 +291,8 @@ func (m Model) View() string { } func (m *Model) SetSize(width, height int) tea.Cmd { + // Before resizing: the viewport clamps its top row to the new size. + m.saveAnchor() m.Width = width m.Height = height m.fvp.SetWidth(m.contentWidth()) @@ -266,10 +302,110 @@ func (m *Model) SetSize(width, height int) tea.Cmd { } func (m *Model) UpdateTheme() tea.Cmd { + m.saveAnchor() m.ClearCache() return m.diff() } +// saveAnchor remembers the diff osc record at the top of the view (or the selected one) and +// the view's offset from its first row, so the next render scrolls back to it (anchorRow). +func (m *Model) saveAnchor() { + // there's already a valid anchor + if m.anchor != nil { + return + } + if rec, ok := m.currentOSCRecord(); ok { + m.anchor = &scrollAnchor{oscRec: rec, offset: m.currentRow() - findOSCRecord(m.shown, rec)} + } +} + +// currentOSCRecord returns the first record at or below the current row of the lines on +// screen, so it is correct even while a new render is pending. +func (m *Model) currentOSCRecord() (oscRecord, bool) { + row := m.currentRow() + if row < 0 || m.fvp.GetMatchingItemsOnly() { + return oscRecord{}, false + } + return firstOSCRecord(m.shown, row) +} + +// currentRow is the selected row, or the top visible one without a selection. +func (m *Model) currentRow() int { + if m.SelectionEnabled() { + return m.fvp.GetSelectedItemIdx() + } + return m.fvp.GetItemMetrics().FirstVisibleItemIdx +} + +// reanchor keeps a pending render from undoing a move the user made from row: a jump to +// the top or bottom (edge) stays there, other moves keep the line they land on. +func (m *Model) reanchor(row int, edge anchorEdge) { + if m.anchor == nil { + return + } + if edge != edgeNone { + m.anchor = &scrollAnchor{edge: edge} + return + } + if m.currentRow() == row { + return + } + m.anchor = nil + m.saveAnchor() +} + +// setLines shows lines and scrolls to the pending anchor, if any. +func (m *Model) setLines(lines []diffLine) { + m.shown = lines + m.fvp.SetObjects(lines) + if m.anchor == nil { + return + } + a := *m.anchor + m.anchor = nil + switch a.edge { + case edgeTop: + m.fvp.GoToTop() + return + case edgeBottom: + m.fvp.GoToBottom() + return + } + if m.fvp.GetMatchingItemsOnly() { + return + } + row, ok := anchorRow(lines, a.oscRec, a.offset) + if !ok { + return + } + if m.SelectionEnabled() { + m.fvp.SetSelectedItemIdx(row) + return + } + m.fvp.GoToTop() + m.fvp.ScrollDown(row) +} + +// anchorRow returns the row offset rows from rec's first row, or false when rec is gone. +// Rows above it (offset < 0) have no record, like blank or decoration rows. Rows below it +// are its wrapped rows, so it stops at the line's last row. +func anchorRow(lines []diffLine, rec oscRecord, offset int) (int, bool) { + row := findOSCRecord(lines, rec) + if row < 0 { + return 0, false + } + if offset < 0 { + return max(row+offset, 0), true + } + for range offset { + if row+1 == len(lines) || !lines[row+1].showsOSCRecord(rec) { + break + } + row++ + } + return row, true +} + func (m Model) contentWidth() int { return m.Width - scrollbarWidth } @@ -281,7 +417,7 @@ func (m *Model) diff() tea.Cmd { key := cacheKey(m.file.path, sideBySide) if cached, ok := m.cache[key]; ok && len(cached.diff) != 0 { m.file = cached - m.fvp.SetObjects(cached.diff) + m.setLines(cached.diff) return nil } node := &cachedNode{ @@ -297,7 +433,7 @@ func (m *Model) diff() tea.Cmd { key := cacheKey(m.dir.path, m.sideBySide) if cached, ok := m.cache[key]; ok && len(cached.diff) != 0 { m.dir = cached - m.fvp.SetObjects(cached.diff) + m.setLines(cached.diff) return nil } node := &cachedNode{ @@ -363,6 +499,8 @@ func (m Model) dirHeaderView() string { func (m Model) SetFilePatch(file *gitdiff.File) (Model, tea.Cmd) { m.dir = nil + // The rows on screen are another node's until this one is shown. + m.anchor, m.shown = nil, nil fname := filenode.GetFileName(file) sideBySide := m.sideBySide && !file.IsNew && !file.IsDelete @@ -370,7 +508,7 @@ func (m Model) SetFilePatch(file *gitdiff.File) (Model, tea.Cmd) { if cached, ok := m.cache[key]; ok { m.file = cached m.updateHeader() - m.fvp.SetObjects(cached.diff) + m.setLines(cached.diff) return m, nil } @@ -391,12 +529,13 @@ func (m Model) SetFilePatch(file *gitdiff.File) (Model, tea.Cmd) { func (m Model) SetDirPatch(dirPath string, files []*gitdiff.File) (Model, tea.Cmd) { m.file = nil + m.anchor, m.shown = nil, nil key := cacheKey(dirPath, m.sideBySide) if cached, ok := m.cache[key]; ok { m.dir = cached m.updateHeader() - m.fvp.SetObjects(cached.diff) + m.setLines(cached.diff) return m, nil } @@ -428,17 +567,22 @@ func (m *Model) updateHeader() { // SetSideBySide updates the diff view mode and re-renders. func (m *Model) SetSideBySide(sideBySide bool) tea.Cmd { m.sideBySide = sideBySide + m.saveAnchor() return m.diff() } // ScrollUp scrolls the viewport up by the given number of lines. func (m *Model) ScrollUp(lines int) { + row := m.currentRow() m.fvp.ScrollUp(lines) + m.reanchor(row, edgeNone) } // ScrollDown scrolls the viewport down by the given number of lines. func (m *Model) ScrollDown(lines int) { + row := m.currentRow() m.fvp.ScrollDown(lines) + m.reanchor(row, edgeNone) } // ScrollBottom scrolls the viewport to the bottom. @@ -488,7 +632,7 @@ func (m *Model) diffFile(node *cachedNode, width int) tea.Cmd { return common.ErrMsg{Err: err} } - return diffContentMsg{cacheKey: key, node: node, lines: stringToDiffLines(string(out))} + return diffContentMsg{cacheKey: key, node: node, lines: parseDeltaOutput(string(out))} } } @@ -522,11 +666,11 @@ func (m *Model) diffDir(dir *cachedNode, width int, sideBySide bool, preamble st return common.ErrMsg{Err: err} } - text := string(out) + lines := parseDeltaOutput(string(out)) if preamble != "" { - text = m.renderPreamble(preamble) + "\n" + text + lines = append(stringToDiffLines(m.renderPreamble(preamble)), lines...) } - return diffContentMsg{cacheKey: key, node: dir, lines: stringToDiffLines(text)} + return diffContentMsg{cacheKey: key, node: dir, lines: lines} } } @@ -623,10 +767,11 @@ type deltaOpts struct { UseUserDeltaTheme bool } -// makeDeltaEnv sets side-by-side like `git -c delta.side-by-side=...` would. -// The --side-by-side flag would override the user's line-number format and can't turn it off. +// makeDeltaEnv asks for OSC 1717 line metadata and, with the user's theme, sets side-by-side +// like `git -c delta.side-by-side=...` would. The --side-by-side flag would override the +// user's line-number format and can't turn it off. func makeDeltaEnv(opts deltaOpts) []string { - env := os.Environ() + env := append(os.Environ(), "OSC1717=V1") if !opts.UseUserDeltaTheme { return env } diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go new file mode 100644 index 0000000..7c77212 --- /dev/null +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -0,0 +1,154 @@ +package diffviewer + +import ( + "slices" + "strconv" + "strings" + + "github.com/robinovitch61/viewport/viewport/item" +) + +// OSC 1717 diff line metadata (https://github.com/stefanhaller/diff-line-metadata-spec). +// Delta >= 0.20 emits it when OSC1717=V1 is set; older versions ignore the variable. + +const ( + osc1717Prefix = "\x1b]1717;" + osc1717Term = "\x1b\\" + osc1717Handshake = osc1717Prefix + "1" + osc1717Term + osc1717Version = "1" + osc1717VersionField = 0 + osc1717TypeField = 1 + osc1717NewLineField = 2 + osc1717OldLineField = 3 + osc1717FileField = 4 + osc1717NumFields = 5 + osc1717KindDeleted = 'd' + osc1717KindContext = 'c' + osc1717KindAdded = 'a' + osc1717KindFileHeader = 'f' + osc1717KindHunkHeader = 'h' +) + +// oscRecord says which diff line a row shows. +// Kind is c (context), a (added), d (deleted), f (file header) or h (hunk header). +type oscRecord struct { + Kind byte + NewLine int + OldLine int + File string +} + +// parseDeltaOutput splits delta's output into rows. When it starts with the +// OSC 1717 handshake (a prefix of the first row, not a row of its own), each +// row's records are parsed and stripped from its text. +func parseDeltaOutput(out string) []diffLine { + rest, ok := strings.CutPrefix(out, osc1717Handshake) + if !ok { + return stringToDiffLines(out) + } + rows := strings.Split(rest, "\n") + lines := make([]diffLine, len(rows)) + for i, row := range rows { + text, records := parseOSCRecords(row) + lines[i] = diffLine{item: item.NewItem(text), records: records} + } + return lines +} + +// parseOSCRecords removes the OSC 1717 sequences from a row and returns them. +func parseOSCRecords(row string) (string, []oscRecord) { + if !strings.Contains(row, osc1717Prefix) { + return row, nil + } + var records []oscRecord + var b strings.Builder + for { + before, after, ok := strings.Cut(row, osc1717Prefix) + if !ok { + break + } + oscRecord, diffLine, ok := strings.Cut(after, osc1717Term) + if !ok { + break // unterminated: kept as text + } + b.WriteString(before) + if r, ok := parseOSCRecord(oscRecord); ok { + records = append(records, r) + } + row = diffLine + } + b.WriteString(row) + return b.String(), records +} + +// parseOSCRecord parses ";;;;". +func parseOSCRecord(body string) (oscRecord, bool) { + fields := strings.SplitN(body, ";", osc1717NumFields) + if len(fields) != osc1717NumFields || fields[osc1717VersionField] != osc1717Version || + len(fields[osc1717TypeField]) != 1 || + !strings.Contains("cadfh", fields[osc1717TypeField]) { + return oscRecord{}, false + } + newLine, _ := strconv.Atoi(fields[osc1717NewLineField]) + oldLine, _ := strconv.Atoi(fields[osc1717OldLineField]) + r := oscRecord{ + Kind: fields[osc1717TypeField][0], + NewLine: newLine, + OldLine: oldLine, + File: unquote(fields[osc1717FileField]), + } + return r, true +} + +// unquote undoes git's quoting of unusual file names (\303\244 for ä), which delta copies, +// with the quotes for a renamed file and without them otherwise. Invalid escapes stay as is. +func unquote(file string) string { + if !strings.Contains(file, `\`) { + return file + } + quoted := file + if !strings.HasPrefix(file, `"`) { + quoted = `"` + file + `"` + } + if name, err := strconv.Unquote(quoted); err == nil { + return name + } + return file +} + +// firstOSCRecord returns the first record at or below row. +func firstOSCRecord(lines []diffLine, row int) (oscRecord, bool) { + for i := max(row, 0); i < len(lines); i++ { + if len(lines[i].records) > 0 { + return lines[i].records[0], true + } + } + return oscRecord{}, false +} + +// findOSCRecord returns the first row showing the same diff line as want, or -1. +func findOSCRecord(lines []diffLine, want oscRecord) int { + return slices.IndexFunc(lines, func(l diffLine) bool { return l.showsOSCRecord(want) }) +} + +// showsOSCRecord reports whether the row shows the same diff line as want. +func (o diffLine) showsOSCRecord(want oscRecord) bool { + return slices.ContainsFunc(o.records, func(r oscRecord) bool { return sameLine(r, want) }) +} + +// sameLine reports whether r is the same diff line as want: in the same file, d by old line, +// c and a by new line, f and h by kind and new line. +func sameLine(r, want oscRecord) bool { + if r.File != want.File { + return false + } + switch want.Kind { + case osc1717KindDeleted: + return r.Kind == osc1717KindDeleted && r.OldLine == want.OldLine + case osc1717KindContext, osc1717KindAdded: + return (r.Kind == osc1717KindContext || r.Kind == osc1717KindAdded) && + r.NewLine == want.NewLine + default: + return r.Kind == want.Kind && r.NewLine == want.NewLine + } +} diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go new file mode 100644 index 0000000..ab92f7d --- /dev/null +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -0,0 +1,341 @@ +package diffviewer + +import ( + "os/exec" + "reflect" + "slices" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + "github.com/bluekeyes/go-gitdiff/gitdiff" + "github.com/robinovitch61/viewport/viewport/item" +) + +func osc(body string) string { return osc1717Prefix + body + osc1717Term } + +// osc1717 structure: ";;;;". +func TestParseDeltaOutput(t *testing.T) { + out := osc1717Handshake + osc("1;f;;;a.go") + "a.go\n" + + osc("1;h;10;;a.go") + "@@\n" + + "\x1b[0m────\n" + + osc("1;d;10;9;a.go") + "\x1b[31m-x" + osc("1;a;10;;a.go") + "+y\n" + + osc("1;c;11;;dir;b.go") + " z\n" + + osc("1;C;;;abc123") + osc("2;c;1;;a.go") + "commit" + + lines := parseDeltaOutput(out) + if len(lines) != 6 { + t.Fatalf("expected 6 rows, got %d", len(lines)) + } + want := [][]oscRecord{ + {{Kind: osc1717KindFileHeader, File: "a.go"}}, + {{Kind: osc1717KindHunkHeader, NewLine: 10, File: "a.go"}}, + nil, + { + {Kind: osc1717KindDeleted, NewLine: 10, OldLine: 9, File: "a.go"}, + {Kind: osc1717KindAdded, NewLine: 10, File: "a.go"}, + }, + {{Kind: osc1717KindContext, NewLine: 11, File: "dir;b.go"}}, + nil, // unknown type and version + } + for i, l := range lines { + if !reflect.DeepEqual(l.records, want[i]) { + t.Errorf("row %d: expected %+v, got %+v", i, want[i], l.records) + } + } + if got := lines[3].item.Content(); got != "\x1b[31m-x+y" { + t.Errorf("expected the records stripped from the text, got %q", got) + } +} + +func TestParseRecords_UnquotesFileName(t *testing.T) { + for raw, want := range map[string]string{ + `\303\244.txt`: "ä.txt", + `"\303\244.txt"`: "ä.txt", // a rename keeps git's quotes + `a\q.txt`: `a\q.txt`, // not a valid escape: kept as is + } { + _, records := parseOSCRecords(osc("1;c;1;;"+raw) + "x") + if len(records) != 1 || records[0].File != want { + t.Errorf("%s: expected file %q, got %+v", raw, want, records) + } + } +} + +func TestParseDeltaOutput_NoHandshake(t *testing.T) { + lines := parseDeltaOutput("plain\n" + osc("1;c;1;;a.go") + " x") + if len(lines) != 2 || lines[1].records != nil { + t.Fatalf("expected no records without the handshake, got %+v", lines) + } +} + +func TestParseDeltaOutput_RealDelta(t *testing.T) { + if _, err := exec.LookPath("delta"); err != nil { + t.Skip("delta not installed") + } + patch := "diff --git a/a;b.go b/a;b.go\n--- a/a;b.go\n+++ b/a;b.go\n" + + "@@ -1,2 +1,2 @@\n ctx\n-old\n+new\n" + t.Setenv("GIT_CONFIG_PARAMETERS", "") + cmd := exec.Command("delta", "--no-gitconfig", "--paging=never", "--side-by-side", "-w=80") + cmd.Env = makeDeltaEnv(deltaOpts{}) + cmd.Stdin = strings.NewReader(patch) + out, err := cmd.Output() + if err != nil { + t.Fatalf("delta: %v", err) + } + if !strings.HasPrefix(string(out), osc1717Handshake) { + t.Skip("delta has no OSC 1717 support") + } + + var got []oscRecord + for _, l := range parseDeltaOutput(string(out)) { + for _, r := range l.records { + if r.Kind == osc1717KindContext || r.Kind == osc1717KindAdded || + r.Kind == osc1717KindDeleted { + got = append(got, r) + } + } + } + want := []oscRecord{ + {Kind: osc1717KindContext, NewLine: 1, File: "a;b.go"}, + {Kind: osc1717KindContext, NewLine: 1, File: "a;b.go"}, + {Kind: osc1717KindDeleted, NewLine: 2, OldLine: 2, File: "a;b.go"}, + {Kind: osc1717KindAdded, NewLine: 2, File: "a;b.go"}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("expected %+v, got %+v", want, got) + } +} + +func row(records ...oscRecord) diffLine { + return diffLine{item: item.NewItem("x"), records: records} +} + +// ctxLine is a context line n of a.go. +func ctxLine( + n int, +) oscRecord { + return oscRecord{Kind: osc1717KindContext, NewLine: n, File: "a.go"} +} + +// unifiedAndSbs returns lines 1 to 20 of a.go in unified, and side by side with a +// decoration row before every line. +func unifiedAndSbs() (unified, sbs []diffLine) { + for n := 1; n <= 20; n++ { + unified = append(unified, row(ctxLine(n))) + sbs = append(sbs, row(), row(ctxLine(n), ctxLine(n))) + } + return unified, sbs +} + +// showing returns a model of the given height that shows lines as a.go in unified. +func showing(t *testing.T, height int, lines []diffLine) Model { + t.Helper() + m := newTestModel(t) + m.SetSize(80, height) + m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{}}, diff: lines} + m.cache[cacheKey("a.go", false)] = m.file + m.setLines(lines) + return m +} + +// rendered delivers the pending side-by-side render of a.go. +func rendered(m Model, lines []diffLine) Model { + m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: lines}) + return m +} + +func TestFindRecord(t *testing.T) { + a := func(n int) oscRecord { return oscRecord{Kind: osc1717KindAdded, NewLine: n, File: "a.go"} } + d := func(n, o int) oscRecord { + return oscRecord{Kind: osc1717KindDeleted, NewLine: n, OldLine: o, File: "a.go"} + } + // Side-by-side: a modification is one row with d and a. + lines := []diffLine{ + row(oscRecord{Kind: osc1717KindFileHeader, File: "a.go"}), + row(oscRecord{Kind: osc1717KindHunkHeader, NewLine: 1, File: "a.go"}), + row(ctxLine(1), ctxLine(1)), + row(d(2, 2), a(2)), + row(a(3)), + row(), + row(ctxLine(4), ctxLine(4)), + } + tests := []struct { + name string + want oscRecord + row int + }{ + {"deleted by old line", d(99, 2), 3}, + {"deleted, other old line", d(2, 99), -1}, + {"added on the right of a row", a(2), 3}, + {"added", a(3), 4}, + {"hunk", oscRecord{Kind: osc1717KindHunkHeader, NewLine: 1, File: "a.go"}, 1}, + {"file", oscRecord{Kind: osc1717KindFileHeader, File: "a.go"}, 0}, + {"past the end", ctxLine(9), -1}, + {"other file", oscRecord{Kind: osc1717KindContext, NewLine: 1, File: "b.go"}, -1}, + } + for _, tt := range tests { + if got := findOSCRecord(lines, tt.want); got != tt.row { + t.Errorf("%s: expected row %d, got %d", tt.name, tt.row, got) + } + } +} + +func TestSetSideBySide_KeepsPosition(t *testing.T) { + unified, sbs := unifiedAndSbs() + unified = slices.Insert(unified, 7, row(ctxLine(7))) // line 7 wraps in unified only + m := showing(t, 4, unified) + m.cache[cacheKey("a.go", true)] = &cachedNode{path: "a.go", files: m.file.files, diff: sbs} + m.ScrollDown(7) // line 7's wrapped row at the top + + m.SetSideBySide(true) + if got := m.fvp.GetItemMetrics().FirstVisibleItemIdx; got != 13 { + t.Fatalf("expected row 13 (line 7) at the top, got %d", got) + } +} + +func TestSetSideBySide_KeepsRecordlessTopRow(t *testing.T) { + unified, _ := unifiedAndSbs() + lines := append([]diffLine{row(), row()}, unified...) // a two-row preamble + m := showing(t, 4, lines) + // A new file renders the same in both modes, so `s` re-shows the same lines. + m.file.files[0].IsNew = true + m.ScrollDown(1) // the preamble's second row at the top + + m.SetSideBySide(true) + if got := m.fvp.GetItemMetrics().FirstVisibleItemIdx; got != 1 { + t.Fatalf("expected row 1 to stay at the top, got %d", got) + } +} + +func TestSetSideBySide_UserMoveDuringRender(t *testing.T) { + unified, sbs := unifiedAndSbs() + for _, key := range []string{"g", "G", "j"} { + m := showing(t, 6, unified) + m.ScrollDown(10) + + m.SetSideBySide(true) // renders async: the anchor is pending + m, _ = m.Update(tea.KeyPressMsg{Code: rune(key[0]), Text: key}) + m = rendered(m, sbs) + metrics := m.fvp.GetItemMetrics() + got, _ := firstOSCRecord(sbs, metrics.FirstVisibleItemIdx) + switch { + case key == "g" && metrics.FirstVisibleItemIdx != 0: + t.Errorf("g: expected the top, got row %d", metrics.FirstVisibleItemIdx) + case key == "G" && metrics.LastVisibleItemIdx != len(sbs)-1: + t.Errorf("G: expected the bottom, got row %d", metrics.LastVisibleItemIdx) + case key == "j" && got != ctxLine(12): + t.Errorf("j: expected line 12 at the top, got line %d", got.NewLine) + } + } +} + +func TestSetSideBySide_WheelAtTheBottomKeepsG(t *testing.T) { + unified, sbs := unifiedAndSbs() + m := showing(t, 4, unified) + m.ScrollDown(5) + + m.SetSideBySide(true) // renders async: the anchor is pending + m, _ = m.Update(tea.KeyPressMsg{Code: 'G', Text: "G"}) + m.ScrollDown(3) // already at the bottom: doesn't move + m = rendered(m, sbs) + if got := m.fvp.GetItemMetrics().LastVisibleItemIdx; got != len(sbs)-1 { + t.Fatalf("expected the bottom, got last row %d", got) + } +} + +func TestSetSideBySide_WheelDuringRender(t *testing.T) { + unified, sbs := unifiedAndSbs() + m := showing(t, 6, unified) + m.ScrollDown(5) + + m.SetSideBySide(true) // renders async: the anchor is pending + m.ScrollDown(3) // the wheel moves the old render + m = rendered(m, sbs) + + if got, _ := firstOSCRecord( + sbs, + m.fvp.GetItemMetrics().FirstVisibleItemIdx, + ); got != ctxLine( + 9, + ) { + t.Fatalf("expected line 9 at the top, got line %d", got.NewLine) + } +} + +func TestSwitchToUncachedNode_HasNoRecord(t *testing.T) { + a := []diffLine{row(oscRecord{Kind: osc1717KindContext, NewLine: 40, File: "a.go"})} + b := &gitdiff.File{OldName: "b.go", NewName: "b.go"} + switches := map[string]func(Model) Model{ + "file": func(m Model) Model { m, _ = m.SetFilePatch(b); return m }, + "dir": func(m Model) Model { m, _ = m.SetDirPatch("pkg", []*gitdiff.File{b}); return m }, + } + for name, switchTo := range switches { + m := newTestModel(t) + m.SetSize(80, 6) + m.setLines(a) + m = switchTo(m) + if rec, ok := m.currentOSCRecord(); ok { + t.Errorf("%s: expected no record before the render lands, got %+v", name, rec) + } + } +} + +func TestSetSideBySide_EdgeKeyAtTheEdge(t *testing.T) { + unified, sbs := unifiedAndSbs() + for _, key := range []string{"g", "G"} { + m := showing(t, 4, unified) + if key == "G" { + m.fvp.GoToBottom() + } + + m.SetSideBySide(true) + m, _ = m.Update(tea.KeyPressMsg{Code: rune(key[0]), Text: key}) // already there + m = rendered(m, sbs) + metrics := m.fvp.GetItemMetrics() + if key == "g" && metrics.FirstVisibleItemIdx != 0 { + t.Errorf("g: expected the top, got row %d", metrics.FirstVisibleItemIdx) + } + if key == "G" && metrics.LastVisibleItemIdx != len(sbs)-1 { + t.Errorf("G: expected the bottom, got row %d", metrics.LastVisibleItemIdx) + } + } +} + +func TestSetSideBySide_ResizeDuringRenderKeepsAnchor(t *testing.T) { + unified, sbs := unifiedAndSbs() + m := showing(t, 6, unified) + m.ScrollDown(10) + + m.SetSideBySide(true) + m, _ = m.Update(tea.KeyPressMsg{Code: 'G', Text: "G"}) + m.SetSize(81, 6) // a resize before the render lands + m = rendered(m, sbs) + if got := m.fvp.GetItemMetrics().LastVisibleItemIdx; got != len(sbs)-1 { + t.Fatalf("expected the bottom, got row %d", got) + } +} + +func TestAnchorRow(t *testing.T) { + // A row without a record, line 1 wrapped over two rows, then line 2. + lines := []diffLine{row(), row(ctxLine(1)), row(ctxLine(1)), row(ctxLine(2))} + tests := []struct { + name string + rec oscRecord + offset int + row int + ok bool + }{ + {"on the line", ctxLine(1), 0, 1, true}, + {"a row above it", ctxLine(1), -1, 0, true}, + {"above the first row", ctxLine(1), -5, 0, true}, + {"its wrapped row", ctxLine(1), 1, 2, true}, + {"not onto the next line", ctxLine(1), 5, 2, true}, + {"not past the last row", ctxLine(2), 3, 3, true}, + {"gone", ctxLine(9), 0, 0, false}, + } + for _, tt := range tests { + if row, ok := anchorRow(lines, tt.rec, tt.offset); row != tt.row || ok != tt.ok { + t.Errorf("%s: expected row %d (%v), got %d (%v)", tt.name, tt.row, tt.ok, row, ok) + } + } +}