From 72b07684b8a13d2eb713414f12f1433ef9db0f1c Mon Sep 17 00:00:00 2001 From: omartelo Date: Fri, 4 Dec 2026 12:07:30 -0300 Subject: [PATCH] feat(native): show one thing at a time in the Git panel --- CHANGELOG.md | 3 +- native/DESIGN.md | 58 +-- native/cmd/lich-native/git_branch.go | 35 +- native/cmd/lich-native/git_commit.go | 266 ++++++----- native/cmd/lich-native/git_commit_test.go | 77 +++- native/cmd/lich-native/git_detail.go | 221 ++++------ native/cmd/lich-native/git_graph.go | 65 +-- native/cmd/lich-native/git_graph_test.go | 113 ++--- native/cmd/lich-native/git_log.go | 255 ++++++----- native/cmd/lich-native/git_merge.go | 10 +- native/cmd/lich-native/git_merge_test.go | 22 +- native/cmd/lich-native/git_panel.go | 298 ++++++------- native/cmd/lich-native/git_refs.go | 512 ++++++++++++---------- native/cmd/lich-native/git_refs_test.go | 74 +++- native/cmd/lich-native/git_store.go | 5 + native/cmd/lich-native/git_sync.go | 8 +- native/cmd/lich-native/git_sync_test.go | 42 +- native/i18n/locales/en/git.json | 29 +- native/i18n/locales/es/git.json | 29 +- native/i18n/locales/ja/git.json | 29 +- native/i18n/locales/ko/git.json | 28 +- native/i18n/locales/pt-br/git.json | 29 +- native/i18n/locales/ru/git.json | 31 +- native/i18n/locales/zh-cn/git.json | 29 +- 24 files changed, 1170 insertions(+), 1098 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ba0af19b..2395e5a69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - **A name with several definitions, or its references, opens a list under it in the editor.** F12, Ctrl+click or Shift+F12 list every place with its line of code; arrows and Enter open one. With Vim on, `gd`, `gr` and anything else that fills Neovim's quickfix list open the same list. -- **Commit from the Git panel.** The Uncommitted changes row at the top of the Git panel's log lists every changed file: check the ones to commit and write the message, or have the session's agent write it with the sparkle. The sparkle is not on Antigravity, Crush, Cursor CLI or Kiro CLI. +- **Commit from the Git panel.** The Git panel's Changes tab lists every changed file beside its diff: check the ones to commit and write the message, or have the session's agent write it with the sparkle. The sparkle is not on Antigravity, Crush, Cursor CLI or Kiro CLI. - **Open projects on another machine over ssh.** Add a server from the `+` after the tabs or from Settings › Servers, which also connects, stops or removes one, and pick it as the scope in Settings to set up its agents and sign them in there; lich installs itself there, the folder you pick opens as a tab marked with the server's name, its sessions are marked the same way in the bell, the sidebar's usage line shows the server's own plan, and those tabs come back when lich starts again. The server must run Linux, Windows cannot connect yet, and files you drop, attach or paste into its sessions are copied there. - **Keep several files open in the editor.** Each file you open gets its own row under the session in the sidebar and keeps its unsaved text, cursor and scroll while you look at another; click a row to go back to it. Close one with Ctrl+W in the editor, a middle click on its row, or the row's menu, which also has Close others and Copy path. - **See the subagents an agent runs inside the chat.** A chip over the composer counts the ones still running, including the ones that keep going after the turn ends, and opens a list of each one's type, task and running time. Codex and Antigravity do not report them. @@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - **The Pulls screen is redrawn, and its list is sorted by what each pull request needs.** Open ones are grouped into Ready to merge, Needs work, In review and Drafts, in place of the All, Ready, Drafts and Failing filters and the Approved state. Inside a pull request, its facts stand beside the description, and Copy link and Copy Markdown are in the `⋯` menu. +- **The Git panel shows one thing at a time.** Changes and History are now two tabs, and a commit opens beside the log when you click it. The branches open from the branch's name in the panel's header: click one to check it out, type a new name to create it, and find the rest in its `⋯`. - **Review threads in Pulls show who answers whom.** Each thread is a card with its file and code, and its replies hang from a line under the comment they answer, in Conversation and between the lines in Files. - **Long conversations no longer slow the window down.** Scrolling, typing and watching an answer come in cost about the same in a chat of thousands of messages as in a new one, and several agents working at once take about a third of the diff --git a/native/DESIGN.md b/native/DESIGN.md index 1f62ccb2a..b54fe61fd 100644 --- a/native/DESIGN.md +++ b/native/DESIGN.md @@ -1008,46 +1008,48 @@ to the chrome takes the same gap rather than a number of its own. ### The Git panel -The panel that rises from the stage's foot (`git_panel.go`) is three columns, the branch tree, the log and the -detail, a `gutter` apart with no rule between them; their resize handles take the gaps, as the sidebar's and the -dock's do. +The panel that rises from the stage's foot (`git_panel.go`) does one job at a time: **Changes**, what to commit, or +**History**, what was. It opens on Changes when there is something to commit and on History when there is not. Two +columns at most stand in it, a `gutter` apart with no rule between them, and the left one's resize handle takes the gap. -- **One header line.** "Git" stands over the tree, the log's filters (text or hash, Author, Date, Path) over the - log, and full screen and close at the right. The tree's own field is its first row, not a band of its own. -- **Push and pull** (`git_sync.go`) stand in the header left of full screen, and only the action the branch's +- **One header line.** The tabs (ghost, as Pulls') at the left; the branch, the push or pull it calls for, full screen + and close at the right. Nothing in it belongs to one tab alone. +- **Push and pull** (`git_sync.go`) stand after the branch, and only the action the branch's standing against its upstream calls for: Push with the commits to send ("Push 2", Lucide `arrow-up`), Pull with the commits to bring ("Pull 1", `arrow-down`), or Publish (`cloud-upload`) for a branch with no upstream; even - with its upstream, or on a detached HEAD, the header has none. The one that resolves the state is filled and - stands last. Diverged, Pull is filled and Push is a ghost, disabled, saying why in its tooltip ("Pull first: - origin/x has 1 commit this branch doesn't"). While one runs it is `Busy` and the other is disabled. A pull + with its upstream, or on a detached HEAD, the header has none. The one that resolves the state stands last, filled, + or outline while there are uncommitted changes, since Commit is then the view's filled button. Diverged, Pull + resolves and Push is a ghost, disabled, saying why in its tooltip ("Pull first: origin/x has 1 commit this branch + doesn't"). While one runs it is `Busy` and the other is disabled. A pull under a session asks first, naming it, in the dialog a checkout under a session uses; a push changes no file and asks nothing. A failure is a toast with git's own words. There is no Fetch button: the counts come from the status read, and lich already fetches origin for the base status. -- **The tree.** Its first row is the branch HEAD is on, by name, in `Foreground` and medium, with no "HEAD" before - it. Local branches that share a prefix before their first slash (`feat/`, `fix/`) sit in a folder row: a chevron, - the prefix and the count in mono, all muted; a click opens or shuts it, the folder holding HEAD's branch opens by - itself and a typed filter opens them all. Its branches stand `gitFolderIndent` in; branches with no prefix stay - loose after the folders. +- **Changes** (`git_commit.go`) is the files over the message, and the diff of one file at the right, the first until + another is clicked. A file's box is the index itself (checked while it holds the file), a conflicted file's box is + disabled with why in its tooltip; its name is ink, its folder muted, and git's letter is the one word in a tone, a + deleted file `D` in `Destructive`. The message is `writeBox`'s shape: a box filled with `Background`, no field in it, + growing with the text, a ghost `IconAction` sparkle (Lucide `sparkles`) in its top right corner, the text wrapping + short of it (`PadRight`); while the agent writes, the field is read only and the sparkle is the kit's spinner, + which cancels. Commit stands last inside it, filled, counting its files, with its keys after the text; disabled, it + says why in its tooltip. The box of every file but the conflicted ones is at the foot's left. A failure is git's + first line in `Destructive` `TextXS` left of Commit, the rest in its tooltip, and the message stays. +- **History** (`git_log.go`) is the log on the panel's whole width, under a search with no box. Author, Date and Path are a line of + their own under it, shown by the filter icon and while one of them is set; the icon is then lit, and a click clears + them. A click on a commit opens it beside the log (`git_detail.go`), which gives up the author's column; a click on + the same commit shuts it. The commit is one list: its subject, who, when, hash and refs on one muted line, the + message, the files. A file's diff takes that list's place, a back arrow before its name. - **A log row** is the graph, the subject, then the commit's one ref right after it (Lucide `git-branch` or `tag` - and the name in mono, in its lane's tone), and who and when in fixed columns at the right. The ref is laid out + and the name, muted: the graph has the color), and who and when in fixed columns at the right. The ref is laid out first, so a long subject is cut short of it. - **The graph.** Lanes 12dp apart, 2dp lines, a lane changing lanes on an S curve. A commit is a disc of radius 4 on a 2dp halo of its row's own ground (rest, hover or selection), so a line stops short of it; a merge is a hollow ring; HEAD wears a second ring 3dp out. The lanes' colors are the one exception to "color encodes state" (see Semantic color). -- **Uncommitted changes** is the log's first row while the checkout has any and no filter narrows the log: a - hollow ring in HEAD's lane and tone, tied to HEAD's node by a dashed line when HEAD heads the page, and the - lines it changes as `+a -d`. The panel opens on it when there are changes and on HEAD when there are none, so - the detail never opens empty. -- **The commit form** is that row's detail, in the shape a commit's has: the files over the message, the seam - between them dragged. A file's box is the index itself (checked while it holds the file), a conflicted file's - box is disabled with why in its tooltip, and the rest of the row opens its diff in the log's place; the file's - name and git's letter take the Code tab's tree's tones, a deleted file `D` in `Destructive`. The message is a - `Textarea` with a ghost `IconAction` sparkle (Lucide `sparkles`) in its top right corner, the text wrapping - short of it (`PadRight`); while the agent writes, the field is read only and the sparkle is the kit's spinner, - which cancels. Commit stands last, filled, with its keys after the text; disabled, it says why in its tooltip. - A failure is git's first line in `Destructive` `TextXS` left of Commit, the rest in its tooltip, and the - message stays. +- **The branches** (`git_refs.go`) open from the branch in the header: a field that finds one or names a new one, the + branch HEAD is on first with its check, the other local ones by their whole name, then Remote branches and Tags, shut + until clicked or until something typed is in them. A click goes there: a checkout, or the session on the branch, whose + name stands at the row's end; a tag shows its history. Everything else a ref offers (Merge, New branch from here, + Rename, Show its history, Delete) is in the row's `⋯` and right click. ### Pulls diff --git a/native/cmd/lich-native/git_branch.go b/native/cmd/lich-native/git_branch.go index 6b5f19159..aa19d0409 100644 --- a/native/cmd/lich-native/git_branch.go +++ b/native/cmd/lich-native/git_branch.go @@ -1,6 +1,6 @@ package main -// The branch tree's actions: the menu of each ref row, the in-row fields that +// The branches' actions: the menu of each ref row, the in-row fields that // rename a branch or start one, and the two confirmations, a checkout under a // session's agent and a delete that leaves commits without a branch. @@ -27,6 +27,7 @@ const ( gitActRename gitActDelete gitActMerge + gitActHistory ) // gitBlocked is why a menu entry is there but cannot be chosen. @@ -50,12 +51,12 @@ type gitMenuItem struct { // worktree cannot be checked out here, so its first entry opens the session on // it when there is one; a remote branch is checked out as the local one that // tracks it. -func gitBranchMenu(row gitTreeRow, hasSession bool) []gitMenuItem { +func gitBranchMenu(row gitRefRow, hasSession bool) []gitMenuItem { switch { case row.remote: - return []gitMenuItem{{act: gitActCheckoutRemote}, {act: gitActNewBranch}} + return []gitMenuItem{{act: gitActCheckoutRemote}, {act: gitActNewBranch}, {act: gitActHistory}} case row.tag: - return []gitMenuItem{{act: gitActNewBranch}} + return []gitMenuItem{{act: gitActHistory}, {act: gitActNewBranch}} } held := row.worktree != "" && !row.head var items []gitMenuItem @@ -65,7 +66,7 @@ func gitBranchMenu(row gitTreeRow, hasSession bool) []gitMenuItem { case !held && !row.head: items = append(items, gitMenuItem{act: gitActCheckout}) } - items = append(items, gitMenuItem{act: gitActNewBranch}, gitMenuItem{act: gitActRename}) + items = append(items, gitMenuItem{act: gitActNewBranch}, gitMenuItem{act: gitActRename}, gitMenuItem{act: gitActHistory}) del := gitMenuItem{act: gitActDelete} switch { case row.head: @@ -78,7 +79,7 @@ func gitBranchMenu(row gitTreeRow, hasSession bool) []gitMenuItem { // gitEdit is the in-row field renaming from, or starting a branch at it. type gitEdit struct { - from gitTreeRow + from gitRefRow create bool field ui.InlineEdit } @@ -88,7 +89,7 @@ type gitEdit struct { type gitConfirm struct { remove bool pull bool - row gitTreeRow + row gitRefRow session string only int } @@ -134,6 +135,8 @@ func gitActLabel(act gitBranchAct, session string) string { return i18n.T("git.branch.newBranch") case gitActRename: return i18n.T("git.branch.rename") + case gitActHistory: + return i18n.T("git.branch.history") } return i18n.T("git.branch.delete") } @@ -152,7 +155,7 @@ func gitBlockedText(b gitBlocked) string { return i18n.T("git.branch.inWorktree") } -func (g *gitPanel) branchEntries(row gitTreeRow, in gitPanelInput) []ui.MenuEntry { +func (g *gitPanel) branchEntries(row gitRefRow, in gitPanelInput) []ui.MenuEntry { sv, hasSession := in.sessions[row.branch] hasSession = hasSession && row.branch != "" var out []ui.MenuEntry @@ -183,7 +186,12 @@ func (g *gitPanel) branchEntries(row gitTreeRow, in gitPanelInput) []ui.MenuEntr return out } -func (g *gitPanel) doBranch(act gitBranchAct, row gitTreeRow, sv sessionView, in gitPanelInput) { +// doBranch runs a ref's action. The ones that type in the row keep the +// branches open; the rest are done with them. +func (g *gitPanel) doBranch(act gitBranchAct, row gitRefRow, sv sessionView, in gitPanelInput) { + if act != gitActNewBranch && act != gitActRename { + g.picker.panel.Close() + } switch act { case gitActCheckout, gitActCheckoutRemote: if in.here != nil { @@ -191,6 +199,9 @@ func (g *gitPanel) doBranch(act gitBranchAct, row gitTreeRow, sv sessionView, in return } g.checkout(row) + case gitActHistory: + g.filter.ref, g.filterRef, g.selected = row.ref, row.name, "" + g.show(gitTabHistory) case gitActOpenSession: g.openSession(sv.projectID, sv.ID) case gitActNewBranch, gitActRename: @@ -222,7 +233,7 @@ func (g *gitPanel) runBranchOp(fail string, op func(context.Context, *backend.Cl }() } -func (g *gitPanel) checkout(row gitTreeRow) { +func (g *gitPanel) checkout(row gitRefRow) { g.runBranchOp(i18n.T("git.branch.checkoutFailed", i18n.Args{"name": row.name}), func(ctx context.Context, c *backend.Client, path string) error { return c.For(path).GitCheckout(ctx, path, row.name, row.remote) }, nil) @@ -230,7 +241,7 @@ func (g *gitPanel) checkout(row gitTreeRow) { // askDelete counts what only the branch holds: nothing, and it goes at once // with an Undo; something, and the dialog asks first. -func (g *gitPanel) askDelete(row gitTreeRow) { +func (g *gitPanel) askDelete(row gitRefRow) { path, fail := g.path, i18n.T("git.branch.deleteFailed", i18n.Args{"name": row.name}) go func() { only, err := g.store.client.For(path).GitBranchOnly(g.store.ctx, path, row.name) @@ -292,7 +303,7 @@ func (g *gitPanel) newBranchRow(gtx C, th *ui.Theme) D { e := g.editing size := image.Pt(gtx.Constraints.Max.X, gtx.Dp(gitRowHeight)) gtx.Constraints = layout.Exact(size) - return layout.Inset{Left: ui.Space(5.5), Right: ui.Space(1.5)}.Layout(gtx, func(gtx C) D { + return layout.Inset{Left: ui.Space(2), Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { return layout.Flex{Alignment: layout.Middle}.Layout(gtx, layout.Rigid(func(gtx C) D { return icBranch.Layout(gtx, ui.Space(3), th.MutedForeground) }), ui.Gap(1.5), diff --git a/native/cmd/lich-native/git_commit.go b/native/cmd/lich-native/git_commit.go index 364ee7feb..5a12c6216 100644 --- a/native/cmd/lich-native/git_commit.go +++ b/native/cmd/lich-native/git_commit.go @@ -4,12 +4,11 @@ import ( "context" "image" "image/color" - "path" + "slices" "strconv" "strings" "sync" - "gioui.org/font" "gioui.org/layout" "gioui.org/op" "gioui.org/unit" @@ -22,22 +21,21 @@ import ( "github.com/lichdotdev/lich/native/ui/icons" ) -// gitWorkTree is what g.selected holds while the Uncommitted changes row is -// chosen; no commit hash can spell it. -const gitWorkTree = "\x00worktree" - var ( icGitWrite = icons.Lucide("sparkles") - gitCommitActions = ui.Space(10) // the row under the message: a SizeSM button and its gap - gitStateWidth = ui.Space(2) // the state letter's column, as the Code tab's tree - gitWriteSide = ui.Space(6) // IconAction's box + gitStateWidth = ui.Space(2) // the state letter's column, as the Code tab's tree + gitWriteSide = ui.Space(6) // IconAction's box + gitMessageLines = ui.Space(16) // the message at rest: two lines and their padding ) -// gitCommitForm is the Uncommitted changes row's detail: the files, each -// checked while the index holds it, over the message and Commit. +// gitCommitForm is the Changes tab: the files, each checked while the index +// holds it, over the message and Commit, beside the diff of one of them. type gitCommitForm struct { - list widget.List + list widget.List + // open is the file whose diff is shown, the first one until another is + // picked or it is no longer changed. + open string all ui.Bool boxes map[string]*ui.Bool files map[string]*ui.Clickable @@ -49,6 +47,7 @@ type gitCommitForm struct { commit ui.Clickable tip ui.Tooltip errTip ui.Tooltip + allTip ui.Tooltip mu sync.Mutex staging bool @@ -111,17 +110,29 @@ func gitStagedFiles(files []backend.GitChange) int { return n } -// gitChangesTotal sums the lines of every uncommitted file. -func gitChangesTotal(files []backend.GitChange) (added, deleted int) { +// gitStageable is every file whose box can be checked: staging a conflicted +// one would mark it resolved. +func gitStageable(files []backend.GitChange) []string { + var paths []string for _, c := range files { - added += c.Added - deleted += c.Deleted + if c.State != api.FileConflict { + paths = append(paths, c.Path) + } + } + return paths +} + +// openFile is the file of files the diff is of. +func (f *gitCommitForm) openFile(files []backend.GitChange) backend.GitChange { + if i := slices.IndexFunc(files, func(c backend.GitChange) bool { return c.Path == f.open }); i >= 0 { + return files[i] } - return added, deleted + return files[0] } -// commitForm is the detail column while Uncommitted changes is selected. -func (g *gitPanel) commitForm(gtx C, th *ui.Theme, in gitPanelInput) D { +// changesTab is what can be committed: the files and the message at the left, +// the diff of one file at the right. +func (g *gitPanel) changesTab(gtx C, th *ui.Theme, in gitPanelInput) D { f := &g.form f.settle(gtx) read := g.store.changesOf(in.path, in.cur) @@ -130,82 +141,34 @@ func (g *gitPanel) commitForm(gtx C, th *ui.Theme, in gitPanelInput) D { return layout.UniformInset(ui.Space(3)).Layout(gtx, th.SkeletonText(ui.TextSM, unit.Dp(180)).Layout) case read.err != "": return gitNotice(gtx, th, i18n.T("git.commit.readFailed", i18n.Args{"error": read.err})) + case len(read.val.Files) == 0: + return gitNotice(gtx, th, i18n.T("git.commit.none")) } files, st := read.val.Files, f.state() - size := gtx.Constraints.Max - spare := gtx.Metric.PxToDp(size.Y) - unit.Dp(gitFilesFloorRem*remDp) - formHeight, released := g.messageCol.width(gtx, spare) - if released { - g.saveColumn(g.messageCol) - } - seam := gtx.Dp(1) - filesHeight := max(size.Y-formHeight-seam, 0) - pane := func(height int, w layout.Widget) layout.FlexChild { - return layout.Rigid(func(gtx C) D { - gtx.Constraints = layout.Exact(image.Pt(size.X, height)) - return w(gtx) + return g.columns(gtx, &g.changesCol, + func(gtx C) D { + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Flexed(1, func(gtx C) D { + gtx.Constraints.Min = gtx.Constraints.Max + list := gitScroll(th, &f.list) + return list.Layout(gtx, len(files), func(gtx C, i int) D { return g.changeFile(gtx, th, in.path, files, i, st) }) + }), + layout.Rigid(func(gtx C) D { + gtx.Constraints.Max.Y = max(gtx.Constraints.Max.Y-gtx.Dp(unit.Dp(gitFilesFloorRem*remDp)), 0) + return layout.Inset{Left: ui.Space(2), Top: ui.Space(2), Bottom: ui.Space(2)}.Layout(gtx, func(gtx C) D { + return g.messageBox(gtx, th, in, files, st) + }) + }), + ) + }, + func(gtx C) D { + c := f.openFile(files) + return g.diffPane(gtx, th, in, gitDiffKey{file: c.Path, oldFile: c.OldPath}) }) - } - layout.Flex{Axis: layout.Vertical}.Layout(gtx, - pane(filesHeight, func(gtx C) D { return g.changeFiles(gtx, th, in.path, files, st) }), - layout.Rigid(func(gtx C) D { return D{Size: image.Pt(0, seam)} }), - pane(formHeight, func(gtx C) D { return g.messageForm(gtx, th, in, files, st) }), - ) - defer op.Offset(image.Pt(0, filesHeight+seam)).Push(gtx.Ops).Pop() - handle := gtx - handle.Constraints = layout.Exact(image.Pt(size.X, formHeight)) - g.messageCol.resize.Layout(handle, th) - return D{Size: size} -} - -func (g *gitPanel) changeFiles(gtx C, th *ui.Theme, repo string, files []backend.GitChange, st gitFormState) D { - f := &g.form - staged := gitStagedFiles(files) - f.all.Value = len(files) > 0 && staged == len(files) - if f.all.Update(gtx) && !st.staging { - paths := make([]string, len(files)) - for i, c := range files { - paths[i] = c.Path - } - g.stage(repo, paths, f.all.Value) - } - added, deleted := gitChangesTotal(files) - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, gtx.Dp(ui.Space(7)))) - return layout.Inset{Left: ui.Space(2.5), Right: ui.Space(2.5)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { - box := th.Checkbox(&f.all) - box.Disabled = st.staging || st.committing - return box.Layout(gtx) - }), - ui.Gap(2), - layout.Rigid(func(gtx C) D { - gtx.Constraints.Min = image.Point{} - return layout.Flex{Alignment: layout.Baseline}.Layout(gtx, - layout.Rigid(th.Text(ui.Text2XS, strings.ToUpper(i18n.T("git.commit.changes"))).Muted().Weight(font.SemiBold).Layout), - ui.Gap(1.5), - layout.Rigid(th.Text(ui.TextXS, i18n.T("git.commit.checked", i18n.Args{"checked": staged, "count": len(files)})).Mono().Muted().Layout), - ) - }), - layout.Flexed(1, func(gtx C) D { return D{Size: image.Pt(gtx.Constraints.Min.X, 0)} }), - layout.Rigid(func(gtx C) D { - gtx.Constraints.Min = image.Point{} - return th.DiffStat(added, deleted).Layout(gtx) - }), - ) - }) - }), - layout.Flexed(1, func(gtx C) D { - list := gitScroll(th, &f.list) - return list.Layout(gtx, len(files), func(gtx C, i int) D { return g.changeFile(gtx, th, repo, files[i], st) }) - }), - ) } // gitChangeLook is a file's state as the Code tab's tree draws it: its letter -// and the tone its name and letter take. A deleted file, which the tree never +// and the tone it takes. A deleted file, which the tree never // lists, reads git's D in the removed lines' tone. func gitChangeLook(th *ui.Theme, state string) (letter string, tone color.NRGBA) { switch state { @@ -224,9 +187,9 @@ func gitChangeLook(th *ui.Theme, state string) (letter string, tone color.NRGBA) } // changeFile is one uncommitted file: its box puts it in the index or takes -// it out, the rest of the row opens its diff in the log's place. -func (g *gitPanel) changeFile(gtx C, th *ui.Theme, repo string, c backend.GitChange, st gitFormState) D { - f := &g.form +// it out, the rest of the row shows its diff. +func (g *gitPanel) changeFile(gtx C, th *ui.Theme, repo string, files []backend.GitChange, i int, st gitFormState) D { + f, c := &g.form, files[i] box := mapItem(f.boxes, c.Path) box.Value = c.Staged != "" if box.Update(gtx) && !st.staging { @@ -234,15 +197,14 @@ func (g *gitPanel) changeFile(gtx C, th *ui.Theme, repo string, c backend.GitCha } click := mapItem(f.files, c.Path) for click.Clicked(gtx) { - g.detail.open = &gitDiffKey{file: c.Path, oldFile: c.OldPath} + f.open = c.Path + gtx.Execute(op.InvalidateCmd{}) } conflict := c.State == api.FileConflict - return layout.Inset{Left: ui.Space(1), Right: ui.Space(1)}.Layout(gtx, func(gtx C) D { - size := image.Pt(gtx.Constraints.Max.X, gtx.Dp(gitRowHeight)) - gtx.Constraints = layout.Exact(size) - open := g.detail.open != nil && g.detail.open.hash == "" && g.detail.open.file == c.Path - rowFill(gtx, th, open, click.Hovered()) - return layout.Inset{Left: ui.Space(1.5), Right: ui.Space(1.5)}.Layout(gtx, func(gtx C) D { + return layout.Inset{Left: ui.Space(2)}.Layout(gtx, func(gtx C) D { + gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, gtx.Dp(gitRowHeight))) + rowFill(gtx, th, f.openFile(files).Path == c.Path, click.Hovered()) + return layout.Inset{Left: ui.Space(2), Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { return layout.Flex{Alignment: layout.Middle}.Layout(gtx, layout.Rigid(func(gtx C) D { cb := th.Checkbox(box) @@ -264,36 +226,24 @@ func (g *gitPanel) changeFile(gtx C, th *ui.Theme, repo string, c backend.GitCha }) } -// gitChangeLine is a file's name in its state's tone, its folder, its lines -// and git's letter for its state. +// gitChangeLine is a file's name, its folder and git's letter for its state, +// the one word of the row in a tone. func gitChangeLine(gtx C, th *ui.Theme, c backend.GitChange) D { letter, tone := gitChangeLook(th, c.State) - dir, name := path.Split(c.Path) return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(th.Text(ui.TextXS, gitCleanLine(name)).Mono().In(tone).Layout), - ui.Gap(1.5), - layout.Flexed(1, func(gtx C) D { - return th.Text(ui.TextXS, gitCleanLine(strings.TrimSuffix(dir, "/"))).Muted().Truncated().Layout(gtx) - }), - ui.Gap(1.5), - layout.Rigid(func(gtx C) D { - if c.Binary { - return D{} - } - gtx.Constraints.Min = image.Point{} - return th.DiffStat(c.Added, c.Deleted).Layout(gtx) - }), + layout.Flexed(1, func(gtx C) D { return gitFileName(gtx, th, c.Path) }), ui.Gap(2), layout.Rigid(func(gtx C) D { gtx.Constraints.Min.X = gtx.Dp(gitStateWidth) - return layout.E.Layout(gtx, th.Text(ui.TextXS, letter).Mono().Weight(font.SemiBold).In(tone).Layout) + return layout.E.Layout(gtx, th.Text(ui.TextXS, letter).Mono().In(tone).Layout) }), ) } -// messageForm is the message, the sparkle that has an agent write it, and -// Commit, which stands last and filled. -func (g *gitPanel) messageForm(gtx C, th *ui.Theme, in gitPanelInput, files []backend.GitChange, st gitFormState) D { +// messageBox is the message on a filled box with no field in it, as a comment +// is written on Pulls: it grows with the text, the sparkle that has an agent +// write it in its corner, and Commit stands last, inside. +func (g *gitPanel) messageBox(gtx C, th *ui.Theme, in gitPanelInput, files []backend.GitChange, st gitFormState) D { f := &g.form text := strings.TrimSpace(f.message.Text()) staged := gitStagedFiles(files) @@ -313,15 +263,29 @@ func (g *gitPanel) messageForm(gtx C, th *ui.Theme, in gitPanelInput, files []ba g.writeMessage(in, st.writing) } } - return layout.Inset{Left: ui.Space(2.5), Right: ui.Space(2.5), Top: ui.Space(2), Bottom: ui.Space(2)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { return g.messageField(gtx, th, st, staged > 0) }), - layout.Rigid(func(gtx C) D { - gtx.Constraints.Min.Y = gtx.Dp(gitCommitActions) - return layout.S.Layout(gtx, func(gtx C) D { return g.commitRow(gtx, th, st, why, ready) }) - }), - ) - }) + free := gitStageable(files) + f.all.Value = len(free) > 0 && gitStagedFiles(files) >= len(free) + if f.all.Update(gtx) && !st.staging { + g.stage(in.path, free, f.all.Value) + } + on := th.On(th.Background) + return layout.Background{}.Layout(gtx, + func(gtx C) D { return ui.Fill(gtx, on.Surface, ui.RadiusMD) }, + func(gtx C) D { + foot := op.Record(gtx.Ops) + fgtx := gtx + fgtx.Constraints.Min.Y = 0 + fd := layout.Inset{Left: writeBoxPadX, Right: ui.Space(2), Bottom: ui.Space(2)}.Layout(fgtx, func(gtx C) D { + return g.commitRow(gtx, on, st, gitCommitAsk{why: why, ready: ready, staged: staged, free: len(free)}) + }) + footCall := foot.Stop() + gtx.Constraints.Max.Y = max(gtx.Constraints.Max.Y-fd.Size.Y, gtx.Dp(gitMessageLines)) + md := g.messageField(gtx, on, st, staged > 0) + defer op.Offset(image.Pt(0, md.Size.Y)).Push(gtx.Ops).Pop() + footCall.Add(gtx.Ops) + return D{Size: image.Pt(gtx.Constraints.Max.X, md.Size.Y+fd.Size.Y)} + }, + ) } // messageField is the textarea with the sparkle in its top right corner, the @@ -329,16 +293,16 @@ func (g *gitPanel) messageForm(gtx C, th *ui.Theme, in gitPanelInput, files []ba // and the sparkle is the spinner that cancels it. func (g *gitPanel) messageField(gtx C, th *ui.Theme, st gitFormState, staged bool) D { f := &g.form - gtx.Constraints.Min = gtx.Constraints.Max + gtx.Constraints.Min.Y = 0 placeholder := i18n.T("git.commit.placeholder") if st.writing { placeholder = i18n.T("git.commit.writing") } ta := th.Textarea(&f.message, placeholder) ta.History, ta.Disabled = &f.history, st.writing || st.committing - ta.MinHeight = gtx.Metric.PxToDp(gtx.Constraints.Max.Y) - ta.PadX = ui.Space(2.5) - inset := ui.Space(1) + ta.Bare, ta.MinHeight = true, gitMessageLines + ta.PadX, ta.PadY = writeBoxPadX, writeBoxPadY + inset := ui.Space(2) ta.PadRight = gitWriteSide + 2*inset d := ta.Layout(gtx) full := image.Pt(gtx.Constraints.Max.X, d.Size.Y) @@ -372,13 +336,35 @@ func (g *gitPanel) messageField(gtx C, th *ui.Theme, st gitFormState, staged boo return D{Size: full} } -// commitRow is the last failure's first line or what the agent was not shown, -// then Commit. -func (g *gitPanel) commitRow(gtx C, th *ui.Theme, st gitFormState, why string, ready bool) D { +// gitCommitAsk is what Commit stands on: how many files it would take, and why +// it cannot run, "" when it can. +type gitCommitAsk struct { + why string + ready bool + staged, free int // free is the files whose boxes can be checked +} + +// commitRow is the box of every file, the last failure's first line or what +// the agent was not shown, then Commit, which counts its files. +func (g *gitPanel) commitRow(gtx C, th *ui.Theme, st gitFormState, ask gitCommitAsk) D { f := &g.form - commit := th.Button(&f.commit, i18n.T("git.commit.commit")) - commit.Keys, commit.Disabled, commit.Busy = ctrlEnterCap(), !ready && !st.committing, st.committing + label := i18n.T("git.commit.commit") + if ask.staged > 0 { + label = i18n.T("git.commit.commitFiles", i18n.Args{"count": ask.staged}) + } + commit := th.Button(&f.commit, label) + commit.Size, commit.Keys, commit.Disabled, commit.Busy = ui.SizeXS, ctrlEnterCap(), !ask.ready && !st.committing, st.committing return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(func(gtx C) D { + if ask.free < 2 { + return D{} + } + box := th.Checkbox(&f.all) + box.Disabled = st.staging || st.committing + return layout.Inset{Right: ui.Space(1.5)}.Layout(gtx, func(gtx C) D { + return th.Tooltip(g.root, &f.allTip, i18n.T("git.commit.allFiles")).Layout(gtx, box.Layout) + }) + }), layout.Flexed(1, func(gtx C) D { switch { case st.err != "": @@ -387,15 +373,17 @@ func (g *gitPanel) commitRow(gtx C, th *ui.Theme, st gitFormState, why string, r return th.Tooltip(g.root, &f.errTip, st.err).Layout(gtx, l.Layout) case st.read.Read < st.read.Total: return th.Text(ui.TextXS, i18n.T("git.commit.readPart", i18n.Args{"read": strconv.Itoa(st.read.Read), "total": strconv.Itoa(st.read.Total)})).Muted().Truncated().Layout(gtx) + case ask.free > 1: + return th.Text(ui.TextXS, i18n.T("git.commit.all")).Muted().Layout(gtx) } return D{Size: image.Pt(gtx.Constraints.Min.X, 0)} }), ui.Gap(2), layout.Rigid(func(gtx C) D { - if why == "" || st.committing { + if ask.why == "" || st.committing { return commit.Layout(gtx) } - return th.Tooltip(g.root, &f.tip, why).Layout(gtx, commit.Layout) + return th.Tooltip(g.root, &f.tip, ask.why).Layout(gtx, commit.Layout) }), ) } diff --git a/native/cmd/lich-native/git_commit_test.go b/native/cmd/lich-native/git_commit_test.go index 319148fc9..d799f8c0e 100644 --- a/native/cmd/lich-native/git_commit_test.go +++ b/native/cmd/lich-native/git_commit_test.go @@ -28,7 +28,7 @@ type gitWorkBackend struct { } // gitHeadMessage is the message of the HEAD commit the fake answers with, -// which the panel's detail shows once it has read it. +// which the panel shows once the commit is opened. const gitHeadMessage = "the head commit" func (b *gitWorkBackend) client(t *testing.T) *backend.Client { @@ -43,7 +43,8 @@ func (b *gitWorkBackend) client(t *testing.T) *backend.Client { var out any switch method { case "project.GitRefs": - out = backend.GitRefs{Head: "aaaaaaaaaaaa", Stamp: "1", Refs: []backend.GitRef{{Name: "main", Kind: backend.GitRefLocal, Head: true}}} + out = backend.GitRefs{Head: "aaaaaaaaaaaa", Stamp: "1", Refs: []backend.GitRef{ + {Name: "main", Kind: backend.GitRefLocal, Head: true}, {Name: "feature", Kind: backend.GitRefLocal}}} case "project.GitLog": out = backend.GitLogPage{Commits: []backend.GitCommit{{Hash: "aaaaaaaaaaaa", Author: "me", Subject: "first", Head: true}}} case "project.GitChanges": @@ -54,9 +55,11 @@ func (b *gitWorkBackend) client(t *testing.T) *backend.Client { case "project.GitWriteMessage": out = backend.GitWrittenMessage{Message: "feat: write the message", Read: 10, Total: 10} case "project.GitCommit": - out = backend.GitCommitDetail{Hash: "aaaaaaaaaaaa", Author: "me", Message: gitHeadMessage} + out = backend.GitCommitDetail{Hash: "aaaaaaaaaaaa", Author: "me", Message: gitHeadMessage, Files: []backend.GitCommitFile{{Path: "pkg/c.go", Added: 1}}} case "project.GitCreateCommit": out = "bbbbbbbbbbbb" + case "project.DiffText": + out = "diff --git a/a.go b/a.go\n--- a/a.go\n+++ b/a.go\n@@ -1 +1 @@\n-x\n+y\n" } _ = json.NewEncoder(w).Encode(out) })) @@ -119,18 +122,31 @@ func gitWorkRig(t *testing.T, b *gitWorkBackend, here *sessionView) (*frameRig, func TestGitPanelOpensOnUncommittedChanges(t *testing.T) { r, g := gitWorkRig(t, &gitWorkBackend{}, nil) - if g.selected != gitWorkTree { - t.Fatalf("selected %q, want the uncommitted changes", g.selected) + if g.tab() != gitTabChanges { + t.Fatalf("opened on tab %v, want Changes", g.tab()) } - if !r.shows("Uncommitted changes") || !r.shows("b.go") { - t.Fatalf("the form is not on screen:\n%s", r.drawn()) + if !r.shows("b.go") || r.shows("first") { + t.Fatalf("want the files and no history:\n%s", r.drawn()) } } +// gitLeftGlyph is the first glyph of name in the left column: the diff at the +// right names its file too. +func gitLeftGlyph(t *testing.T, r *frameRig, name string) f32.Point { + t.Helper() + for _, n := range r.nodes() { + if at := n.Desc.Bounds.Min; n.Desc.Label == name && at.X < r.size.X/4 { + return f32.Pt(float32(at.X)+2, float32(at.Y)+2) + } + } + t.Fatalf("no %q in the left column:\n%s", name, r.drawn()) + return f32.Point{} +} + // The box left of a file's name. func gitBoxOf(t *testing.T, r *frameRig, name string) f32.Point { t.Helper() - p := r.glyphAt(t, name) + p := gitLeftGlyph(t, r, name) b, ok := r.smallestClickAt(image.Pt(int(p.X)-int(ui.Space(4)), int(p.Y)+4)) if !ok { t.Fatalf("no box beside %q:\n%s", name, r.drawn()) @@ -162,14 +178,14 @@ func TestUncheckingAFileTakesItOutOfTheIndex(t *testing.T) { } } -// gitSparkle is the icon button in the message field's corner, the one -// square clickable under the file list in the detail column. +// gitSparkle is the icon button in the message box's corner, the one square +// clickable under the file list in the left column. func gitSparkle(t *testing.T, r *frameRig) f32.Point { t.Helper() side := int(gitWriteSide) for _, n := range r.nodes() { b := n.Desc.Bounds - if b.Dx() == side && b.Dy() == side && b.Min.X > r.size.X/2 && b.Min.Y > int(dockHeaderHeight)+int(gitRowHeight)*3 { + if b.Dx() == side && b.Dy() == side && b.Min.X < r.size.X/2 && b.Min.Y > int(dockHeaderHeight)+int(gitRowHeight)*3 { return centre(b) } } @@ -180,7 +196,7 @@ func gitSparkle(t *testing.T, r *frameRig) f32.Point { func TestCommitWaitsForAMessageThenCommitsIt(t *testing.T) { b := &gitWorkBackend{} r, g := gitWorkRig(t, b, nil) - r.queueClick(r.glyphAt(t, "Commit")) + r.queueClick(r.glyphAt(t, "Commit 1 file")) r.settle(t) b.mu.Lock() early := len(b.calls["project.GitCreateCommit"]) @@ -190,7 +206,7 @@ func TestCommitWaitsForAMessageThenCommitsIt(t *testing.T) { } g.form.message.SetText("fix: the thing") r.settle(t) - r.queueClick(r.at(t, "Commit")) + r.queueClick(r.at(t, "Commit 1 file")) r.frame() var got api.GitCreateCommitOptions b.asked(t, "project.GitCreateCommit", &got) @@ -224,3 +240,38 @@ func TestTheSparkleAsksTheSessionsAgentForTheMessage(t *testing.T) { r.frame() } } + +func TestCheckingEveryFileLeavesConflictsOut(t *testing.T) { + got := gitStageable([]backend.GitChange{{Path: "a", State: api.FileModified}, {Path: "b", State: api.FileConflict}}) + if len(got) != 1 || got[0] != "a" { + t.Fatalf("got %v, want only the file with no conflict", got) + } +} + +func TestTheBoxUnderTheMessageChecksEveryFile(t *testing.T) { + b := &gitWorkBackend{} + r, _ := gitWorkRig(t, b, nil) + r.queueClick(gitBoxOf(t, r, "All")) + r.frame() + var got api.GitFilesOptions + b.asked(t, "project.GitStage", &got) + if len(got.Files) != 2 { + t.Fatalf("staged %v, want both files", got.Files) + } +} + +// Another file of the same work tree is already in the answer on hand. +func TestPickingAnotherChangedFileReadsNoDiffAgain(t *testing.T) { + b := &gitWorkBackend{} + r, g := gitWorkRig(t, b, nil) + r.settle(t) + before := b.called("project.DiffText") + r.click(t, gitLeftGlyph(t, r, "b.go")) + r.settle(t) + if g.form.open != "pkg/b.go" { + t.Fatalf("open %q, want the file clicked", g.form.open) + } + if n := b.called("project.DiffText"); before == 0 || n != before { + t.Fatalf("read the work tree's diff %d times, want the %d of before the click", n, before) + } +} diff --git a/native/cmd/lich-native/git_detail.go b/native/cmd/lich-native/git_detail.go index 5fc866f69..9ac3f1489 100644 --- a/native/cmd/lich-native/git_detail.go +++ b/native/cmd/lich-native/git_detail.go @@ -3,8 +3,8 @@ package main import ( "image" "log" + "path" "slices" - "strconv" "strings" "time" @@ -24,20 +24,19 @@ import ( var icGitBack = icons.Lucide("arrow-left") -// gitDetailPane is the selected commit's detail, and the one file of it whose -// diff is standing in for the log. +// gitDetailPane is the commit open beside the log, the one file of it whose +// diff stands in its place, and the diff view both tabs draw with. type gitDetailPane struct { - list widget.List - message widget.List - files map[string]*ui.Clickable + list widget.List + files map[string]*ui.Clickable open *gitDiffKey - back ui.Clickable + back ui.IconActionState split bool splitBtn ui.IconActionState view *godemirror.DiffView viewFail bool - // patchFor is the answer patch was parsed from. + // patchFor is the answer patch was parsed from, and the file of it. patchFor string patch godemirror.FilePatch binary bool @@ -45,19 +44,20 @@ type gitDetailPane struct { } func (d *gitDetailPane) init() { - d.list.Axis, d.message.Axis = layout.Vertical, layout.Vertical + d.list.Axis = layout.Vertical d.files = map[string]*ui.Clickable{} } -func (d *gitDetailPane) diffOpen() bool { return d.open != nil } -func (d *gitDetailPane) closeFile() { d.open = nil } +func (d *gitDetailPane) closeFile() { d.open = nil } -func (g *gitPanel) detailColumn(gtx C, th *ui.Theme, in gitPanelInput) D { - if g.selected == gitWorkTree { - return g.commitForm(gtx, th, in) +// commitPane is the commit open beside the log, or the one file of it that was +// clicked. +func (g *gitPanel) commitPane(gtx C, th *ui.Theme, in gitPanelInput) D { + for g.detail.back.Click.Clicked(gtx) { + g.detail.closeFile() } - if g.selected == "" { - return gitNotice(gtx, th, i18n.T("git.panel.selectCommit")) + if key := g.detail.open; key != nil { + return g.diffPane(gtx, th, in, *key) } read := g.store.commit(in.path, g.selected) switch { @@ -66,134 +66,58 @@ func (g *gitPanel) detailColumn(gtx C, th *ui.Theme, in gitPanelInput) D { case read.err != "": return gitNotice(gtx, th, i18n.T("git.panel.commitFailed", i18n.Args{"error": read.err})) } - return g.detailSplit(gtx, th, read.val) -} - -// detailSplit is the commit's files over its message, as IntelliJ stacks them, -// each scrolling alone, the seam between them dragged. -func (g *gitPanel) detailSplit(gtx C, th *ui.Theme, c backend.GitCommitDetail) D { - size := gtx.Constraints.Max - spare := gtx.Metric.PxToDp(size.Y) - unit.Dp(gitFilesFloorRem*remDp) - messageHeight, released := g.messageCol.width(gtx, spare) - if released { - g.saveColumn(g.messageCol) - } - seam := gtx.Dp(1) - filesHeight := max(size.Y-messageHeight-seam, 0) - pane := func(height int, w layout.Widget) layout.FlexChild { - return layout.Rigid(func(gtx C) D { - gtx.Constraints = layout.Exact(image.Pt(size.X, height)) - return w(gtx) - }) - } - layout.Flex{Axis: layout.Vertical}.Layout(gtx, - pane(filesHeight, func(gtx C) D { return g.detailFiles(gtx, th, c) }), - layout.Rigid(func(gtx C) D { return D{Size: image.Pt(0, gtx.Dp(1))} }), // the resize handle's room, drawn as nothing - pane(messageHeight, func(gtx C) D { - list := gitScroll(th, &g.detail.message) - return list.Layout(gtx, 1, func(gtx C, _ int) D { return gitCommitHead(gtx, th, c) }) - }), - ) - defer op.Offset(image.Pt(0, filesHeight+seam)).Push(gtx.Ops).Pop() - handle := gtx - handle.Constraints = layout.Exact(image.Pt(size.X, messageHeight)) - g.messageCol.resize.Layout(handle, th) - return D{Size: size} -} - -// gitFilesTotal sums what a commit changed, the figure over its file list. -func gitFilesTotal(files []backend.GitCommitFile) (added, deleted int) { - for _, f := range files { - added += f.Added - deleted += f.Deleted - } - return added, deleted -} - -func (g *gitPanel) detailFiles(gtx C, th *ui.Theme, c backend.GitCommitDetail) D { - added, deleted := gitFilesTotal(c.Files) - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, gtx.Dp(ui.Space(7)))) - return layout.Inset{Left: ui.Space(3.5), Right: ui.Space(2.5)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { - // Two sizes on one line: under the row's Exact height they would not share a baseline. - gtx.Constraints.Min = image.Point{} - return layout.Flex{Alignment: layout.Baseline}.Layout(gtx, - layout.Rigid(th.Text(ui.Text2XS, strings.ToUpper(i18n.T("git.panel.files"))).Muted().Weight(font.SemiBold).Layout), - ui.Gap(1.5), - layout.Rigid(th.Text(ui.TextXS, strconv.Itoa(len(c.Files))).Mono().Muted().Layout), - ) - }), - layout.Flexed(1, func(gtx C) D { return D{Size: image.Pt(gtx.Constraints.Min.X, 0)} }), - layout.Rigid(func(gtx C) D { - gtx.Constraints.Min = image.Point{} - return th.DiffStat(added, deleted).Layout(gtx) - }), - ) - }) - }), - layout.Flexed(1, func(gtx C) D { - list := gitScroll(th, &g.detail.list) - return list.Layout(gtx, len(c.Files), func(gtx C, i int) D { return g.detailFile(gtx, th, c.Hash, c.Files[i]) }) - }), - ) + c := read.val + list := gitScroll(th, &g.detail.list) + return list.Layout(gtx, len(c.Files)+1, func(gtx C, i int) D { + if i == 0 { + return gitCommitHead(gtx, th, c) + } + return g.detailFile(gtx, th, c.Hash, c.Files[i-1]) + }) } -// gitCommitHead is the commit's subject, who and when, every ref it carries -// and the rest of its message. +// gitCommitHead is the commit's subject, then who, when, its hash and every ref +// it carries on one line, then the rest of its message. func gitCommitHead(gtx C, th *ui.Theme, c backend.GitCommitDetail) D { subject, body, _ := strings.Cut(c.Message, "\n") multi := func(l ui.LabelStyle) layout.Widget { l.MaxLines = 0 return l.Layout } - short := c.Hash[:min(len(c.Hash), shortHashLen)] when := time.Unix(c.When, 0).In(gtx.Now.Location()).Format("Jan 2, 2006 15:04") + facts := []string{gitCleanLine(c.Author), when, c.Hash[:min(len(c.Hash), shortHashLen)]} + for _, r := range c.Refs { + facts = append(facts, r.Name) + } kids := []layout.FlexChild{ layout.Rigid(multi(th.Text(ui.TextSM, gitCleanLine(subject)).Weight(font.Medium))), - ui.VGap(1.5), - layout.Rigid(multi(th.Text(ui.TextXS, short+" "+gitCleanLine(c.Author)).Mono().Muted())), - layout.Rigid(multi(th.Text(ui.TextXS, when).Mono().Muted())), - } - if len(c.Refs) > 0 { - names := make([]string, len(c.Refs)) - for i, r := range c.Refs { - names[i] = r.Name - } - kids = append(kids, ui.VGap(1.5), layout.Rigid(multi(th.Text(ui.TextXS, strings.Join(names, " ")).Mono().Muted()))) + ui.VGap(1), + layout.Rigid(multi(th.Text(ui.TextXS, strings.Join(facts, " · ")).Muted())), } if body = strings.TrimSpace(body); body != "" { - kids = append(kids, ui.VGap(2), layout.Rigid(multi(th.Text(ui.TextXS, strings.ReplaceAll(body, "\t", " ")).Muted()))) + kids = append(kids, ui.VGap(2.5), layout.Rigid(multi(th.Text(ui.TextXS, strings.ReplaceAll(body, "\t", " ")).Muted()))) } - return layout.Inset{Left: ui.Space(3.5), Right: ui.Space(2), Top: ui.Space(2.5), Bottom: ui.Space(2)}.Layout(gtx, func(gtx C) D { + return layout.Inset{Left: ui.Space(3), Right: ui.Space(3), Top: ui.Space(1.5), Bottom: ui.Space(3)}.Layout(gtx, func(gtx C) D { return layout.Flex{Axis: layout.Vertical}.Layout(gtx, kids...) }) } -// detailFile is one changed file; choosing it opens its diff in the log's -// place. +// detailFile is one file the commit changed; a click opens its diff. func (g *gitPanel) detailFile(gtx C, th *ui.Theme, hash string, f backend.GitCommitFile) D { - click, ok := g.detail.files[f.Path] - if !ok { - click = new(ui.Clickable) - g.detail.files[f.Path] = click - } + click := mapItem(g.detail.files, f.Path) for click.Clicked(gtx) { g.detail.open = &gitDiffKey{hash: hash, file: f.Path, oldFile: f.OldPath} + // The pane chose what to draw before this row: draw it again. + gtx.Execute(op.InvalidateCmd{}) } - return layout.Inset{Left: ui.Space(1), Right: ui.Space(1)}.Layout(gtx, func(gtx C) D { + return layout.Inset{Left: ui.Space(1), Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { return click.Layout(gtx, func(gtx C) D { - size := image.Pt(gtx.Constraints.Max.X, gtx.Dp(gitRowHeight)) - gtx.Constraints = layout.Exact(size) - open := g.detail.open != nil && g.detail.open.hash == hash && g.detail.open.file == f.Path - rowFill(gtx, th, open, click.Hovered()) - return layout.Inset{Left: ui.Space(2.5), Right: ui.Space(1.5)}.Layout(gtx, func(gtx C) D { + gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, gtx.Dp(gitRowHeight))) + rowFill(gtx, th, false, click.Hovered()) + return layout.Inset{Left: ui.Space(2), Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - // From its end: the file's name is what tells two rows apart. - layout.Flexed(1, ui.Spanning(func(gtx C) D { return th.Text(ui.TextXS, gitCleanLine(f.Path)).Mono().LayoutTail(gtx) })), - ui.Gap(1.5), + layout.Flexed(1, func(gtx C) D { return gitFileName(gtx, th, f.Path) }), + ui.Gap(2), layout.Rigid(func(gtx C) D { if f.Binary { return D{} @@ -208,13 +132,21 @@ func (g *gitPanel) detailFile(gtx C, th *ui.Theme, hash string, f backend.GitCom }) } -// layoutDiff stands in for the log: a strip with the way back over one file's -// patch. -func (d *gitDetailPane) layoutDiff(gtx C, th *ui.Theme, g *gitPanel, in gitPanelInput) D { - for d.back.Clicked(gtx) { - d.closeFile() - return D{Size: gtx.Constraints.Max} - } +// gitFileName is a file's name and, muted after it, its folder, which is what +// gives way in a narrow row. +func gitFileName(gtx C, th *ui.Theme, file string) D { + dir, name := path.Split(file) + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(th.Text(ui.TextXS, gitCleanLine(name)).Truncated().Layout), + ui.Gap(2), + layout.Flexed(1, th.Text(ui.TextXS, gitCleanLine(strings.TrimSuffix(dir, "/"))).Muted().Truncated().Layout), + ) +} + +// diffPane is one file's patch under its name, led by the way back to the +// commit it is of. +func (g *gitPanel) diffPane(gtx C, th *ui.Theme, in gitPanelInput, key gitDiffKey) D { + d := &g.detail for d.splitBtn.Click.Clicked(gtx) { d.split = !d.split } @@ -222,27 +154,27 @@ func (d *gitDetailPane) layoutDiff(gtx C, th *ui.Theme, g *gitPanel, in gitPanel if d.split { splitLabel = i18n.T("diff.dockReviewBody.unified") } - key := *d.open + left := ui.Space(2.5) + var kids []layout.FlexChild + if key.hash != "" { + left = ui.Space(1) + kids = append(kids, layout.Rigid(th.IconAction(g.root, &d.back, icGitBack, i18n.T("git.panel.back"), false).Layout), ui.Gap(1)) + } + kids = append(kids, + layout.Flexed(1, func(gtx C) D { return gitFileName(gtx, th, key.file) }), + ui.Gap(2), + layout.Rigid(th.IconAction(g.root, &d.splitBtn, icSplit, splitLabel, d.split).Layout), + ) return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { - gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, gtx.Dp(gitFilterHeight))) - return layout.Inset{Left: ui.Space(2), Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { - b := th.Button(&d.back, i18n.T("git.panel.back")) - b.Variant, b.Size, b.Icon = ui.VariantGhost, ui.SizeSM, icGitBack - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(b.Layout), - ui.Gap(2), - layout.Flexed(1, func(gtx C) D { - return th.Text(ui.TextXS, gitCleanLine(key.file)).Mono().Muted().Truncated().Layout(gtx) - }), - ui.Gap(2), - layout.Rigid(func(gtx C) D { return th.IconAction(g.root, &d.splitBtn, icSplit, splitLabel, d.split).Layout(gtx) }), - ) + gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, gtx.Dp(gitRowHeight))) + return layout.Inset{Left: left, Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, kids...) }) }), layout.Flexed(1, func(gtx C) D { gtx.Constraints.Min = gtx.Constraints.Max - return d.diffBody(gtx, th, g, in, key) + return layout.Inset{Right: ui.Space(2), Bottom: ui.Space(2)}.Layout(gtx, func(gtx C) D { return d.diffBody(gtx, th, g, in, key) }) }), ) } @@ -293,10 +225,11 @@ func (d *gitDetailPane) diffBody(gtx C, th *ui.Theme, g *gitPanel, in gitPanelIn // takeDiff parses an answer once. A commit's answer is the one file asked // for; the work tree's holds every file, and file picks one. func (d *gitDetailPane) takeDiff(read gitLoaded[string], file string) { - if d.patchFor == read.key { + key := read.key + "\x00" + file + if d.patchFor == key { return } - d.patchFor, d.binary, d.empty = read.key, false, false + d.patchFor, d.binary, d.empty = key, false, false files, err := parsePatchFiles(read.val) if err != nil { log.Printf("git diff: %v", err) diff --git a/native/cmd/lich-native/git_graph.go b/native/cmd/lich-native/git_graph.go index 204de5210..e8505ee3d 100644 --- a/native/cmd/lich-native/git_graph.go +++ b/native/cmd/lich-native/git_graph.go @@ -18,7 +18,7 @@ import ( ) var ( - gitRowHeight = ui.Space(6.5) + gitRowHeight = ui.Space(7) gitLaneWidth = unit.Dp(12) gitGraphInset = ui.Space(3) gitNodeRadius = unit.Dp(4) @@ -32,16 +32,13 @@ var ( gitRingStroke = unit.Dp(1.5) // gitHeadGap is how far HEAD's outer ring stands off its node. gitHeadGap = unit.Dp(3) - // gitDash is a dash of the tie to HEAD, and the gap after it. - gitDash = unit.Dp(3) ) // gitNode is how a row's node reads: on what ground, and whether it is a // merge (hollow) or HEAD (ringed). -// workAbove ties the node up to the uncommitted changes' row over it. type gitNode struct { - ground color.NRGBA - merge, head, workAbove bool + ground color.NRGBA + merge, head bool } // gitMaxLanes is how many lanes the graph column grows to: past it the @@ -142,9 +139,6 @@ func drawGitRow(gtx C, th *ui.Theme, r gitGraphRow, size image.Point, n gitNode) for _, l := range r.down { strokeGitLink(gtx, tone(l.color), node, f32.Pt(x(l.lane), h), width) } - if n.workAbove { - strokeGitDash(gtx, tone(r.color), node.X, 0, node.Y, width) - } drawGitNode(gtx, node, tone(r.color), n) } @@ -178,13 +172,10 @@ func strokeGitLink(gtx C, c color.NRGBA, from, to f32.Point, width float32) { paint.FillShape(gtx.Ops, c, clip.Stroke{Path: p.End(), Width: width}.Op()) } -// gitRefLabel is the one ref a row names, how many more the commit carries, -// and the local branch a session could be on. +// gitRefLabel is the one ref a row names and how many more the commit carries. type gitRefLabel struct { - text, branch string - kind string - head bool - extra int + text, kind string + extra int } // gitRefLabelOf picks what a row says of a commit's refs: the branch HEAD is @@ -211,11 +202,10 @@ func gitRefLabelOf(refs []backend.GitRef) (gitRefLabel, bool) { best = r } } - label := gitRefLabel{text: best.Name, kind: best.Kind, head: best.Head, extra: len(refs) - 1} + label := gitRefLabel{text: best.Name, kind: best.Kind, extra: len(refs) - 1} if best.Kind != backend.GitRefLocal { return label, true } - label.branch = best.Name for _, r := range refs { if remote, ok := strings.CutSuffix(r.Name, "/"+best.Name); ok && r.Kind == backend.GitRefRemote { label.text, label.extra = best.Name+" & "+remote, label.extra-1 @@ -236,44 +226,3 @@ func gitWhen(unix int64, now time.Time) string { } return t.Format("15:04") } - -// gitHeadNode is the row of the commit HEAD is at, and whether that commit -// heads the page, where the uncommitted changes can be tied to it; ok is -// false when it is not on the page or no graph is drawn. -func gitHeadNode(view gitLogView) (row gitGraphRow, first, ok bool) { - for i, c := range view.commits { - if c.Head && i < len(view.rows) { - return view.rows[i], i == 0, true - } - } - return gitGraphRow{}, false, false -} - -// drawGitWorkNode is the uncommitted changes' hollow ring in HEAD's lane and -// tone, tied to HEAD below by a dashed line when HEAD heads the page: work on -// top of HEAD that no commit holds yet. -func drawGitWorkNode(gtx C, th *ui.Theme, view gitLogView, height int, ground color.NRGBA) { - head, first, ok := gitHeadNode(view) - tone := th.MutedForeground - if ok { - tone = th.GraphLanes[head.color%len(th.GraphLanes)] - } - x := float32(gtx.Dp(gitGraphInset)) + float32(head.lane)*float32(gtx.Dp(gitLaneWidth)) - at := f32.Pt(x, float32(height)/2) - width := float32(gtx.Dp(gitGraphStroke)) - if first { - strokeGitDash(gtx, tone, x, at.Y, float32(height), width) - } - radius, halo := float32(gtx.Dp(gitNodeRadius)), float32(gtx.Dp(gitNodeHalo)) - ui.StrokeArc(gtx, at, (radius+halo)/2, radius+halo, 0, 2*math.Pi, ground) - ui.StrokeArc(gtx, at, radius-width/2, width, 0, 2*math.Pi, tone) -} - -// strokeGitDash is a dashed vertical line at x from y0 to y1, the tie -// between the uncommitted changes and HEAD. -func strokeGitDash(gtx C, c color.NRGBA, x, y0, y1, width float32) { - dash := float32(gtx.Dp(gitDash)) - for y := y0; y < y1; y += 2 * dash { - strokeGitLink(gtx, c, f32.Pt(x, y), f32.Pt(x, min(y+dash, y1)), width) - } -} diff --git a/native/cmd/lich-native/git_graph_test.go b/native/cmd/lich-native/git_graph_test.go index f515c2143..064b2271a 100644 --- a/native/cmd/lich-native/git_graph_test.go +++ b/native/cmd/lich-native/git_graph_test.go @@ -1,7 +1,9 @@ package main import ( + "cmp" "reflect" + "slices" "testing" "time" @@ -96,11 +98,11 @@ func TestGitRefLabelOf(t *testing.T) { refs []backend.GitRef want gitRefLabel }{ - {"head wins", []backend.GitRef{local("a", false), local("b", true)}, gitRefLabel{text: "b", branch: "b", kind: backend.GitRefLocal, head: true, extra: 1}}, - {"local and its remote read as one", []backend.GitRef{remote("origin/main"), local("main", false)}, gitRefLabel{text: "main & origin", branch: "main", kind: backend.GitRefLocal}}, + {"head wins", []backend.GitRef{local("a", false), local("b", true)}, gitRefLabel{text: "b", kind: backend.GitRefLocal, extra: 1}}, + {"local and its remote read as one", []backend.GitRef{remote("origin/main"), local("main", false)}, gitRefLabel{text: "main & origin", kind: backend.GitRefLocal}}, {"remote before tag", []backend.GitRef{tag, remote("origin/x")}, gitRefLabel{text: "origin/x", kind: backend.GitRefRemote, extra: 1}}, {"tag alone", []backend.GitRef{tag}, gitRefLabel{text: "v1", kind: backend.GitRefTag}}, - {"a remote of another name is not merged", []backend.GitRef{local("a", false), remote("origin/b")}, gitRefLabel{text: "a", branch: "a", kind: backend.GitRefLocal, extra: 1}}, + {"a remote of another name is not merged", []backend.GitRef{local("a", false), remote("origin/b")}, gitRefLabel{text: "a", kind: backend.GitRefLocal, extra: 1}}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -128,61 +130,33 @@ func TestGitWhen(t *testing.T) { } } -func TestGitTreeRowsGroupsAndFilters(t *testing.T) { +func TestGitRefRowsPutHeadFirstAndFoldWhatIsNotLocal(t *testing.T) { refs := []backend.GitRef{ + {Name: "amber", Kind: backend.GitRefLocal}, {Name: "feat/x", Kind: backend.GitRefLocal, Head: true}, {Name: "origin/feat/x", Kind: backend.GitRefRemote}, {Name: "upstream/main", Kind: backend.GitRefRemote}, {Name: "v1", Kind: backend.GitRefTag}, } - rows := gitTreeRows(refs, "") - labels := make([]string, len(rows)) - for i, r := range rows { - labels[i] = r.label - } - want := []string{"Local", "feat/", "x", "origin", "feat/x", "upstream", "main", "Tags", "v1"} - if !reflect.DeepEqual(labels, want) { - t.Fatalf("labels = %v", labels) - } - if rows[1].folder != "feat" || rows[1].count != 1 || rows[2].parent != "feat" { - t.Errorf("a local branch's prefix is its folder: %+v", rows[1:3]) - } - if rows[4].ref != "refs/remotes/origin/feat/x" || rows[2].branch != "feat/x" || rows[4].branch != "" { - t.Errorf("rows = %+v", rows) - } - if got := gitTreeRows(refs, "V1"); len(got) != 2 || !got[0].group || !got[1].tag { - t.Errorf("filtered = %+v, a group nothing matched is left out", got) - } -} - -func TestGitFoldersGoFirstAndShutFoldersHideTheirBranches(t *testing.T) { - refs := []backend.GitRef{ - {Name: "amber-comet", Kind: backend.GitRefLocal}, - {Name: "fix/b", Kind: backend.GitRefLocal}, - {Name: "feat/a", Kind: backend.GitRefLocal, Head: true}, - {Name: "feat/c", Kind: backend.GitRefLocal}, - } - rows := gitTreeRows(refs, "") - shown := gitShownRows(rows, func(folder string) bool { return folder == "feat" }) - labels := make([]string, len(shown)) - for i, r := range shown { - labels[i] = r.label - } - want := []string{"Local", "feat/", "a", "c", "fix/", "amber-comet"} - if !reflect.DeepEqual(labels, want) { - t.Fatalf("labels = %v, want %v", labels, want) - } - g := &gitPanel{folders: map[string]bool{}} - open := g.folderOpen(rows, "") - if !open("feat") || open("fix") { - t.Error("only the folder holding HEAD's branch opens by itself") - } - g.folders["feat"] = false - if open("feat") { - t.Error("a folder the person shut stays shut") + names := func(filter string, open ...string) []string { + var out []string + for _, r := range gitRefRows(refs, filter, func(g string) bool { return slices.Contains(open, g) }) { + out = append(out, cmp.Or(r.group, r.ref)) + } + return out } - if !g.folderOpen(rows, "b")("fix") { - t.Error("a typed filter opens every folder") + for _, c := range []struct { + name, filter string + open []string + want []string + }{ + {"shut", "", nil, []string{"refs/heads/feat/x", "refs/heads/amber", "remote", "tags"}}, + {"remotes unfolded", "", []string{"remote"}, []string{"refs/heads/feat/x", "refs/heads/amber", "remote", "refs/remotes/origin/feat/x", "refs/remotes/upstream/main", "tags"}}, + {"a group nothing matched is left out", "V1", []string{"remote", "tags"}, []string{"tags", "refs/tags/v1"}}, + } { + if got := names(c.filter, c.open...); !slices.Equal(got, c.want) { + t.Errorf("%s: %v, want %v", c.name, got, c.want) + } } } @@ -245,13 +219,6 @@ func TestParseGitRemKeepsTheFallbackForGarbage(t *testing.T) { } } -func TestGitFilesTotal(t *testing.T) { - a, d := gitFilesTotal([]backend.GitCommitFile{{Added: 3, Deleted: 1}, {Binary: true}, {Added: 2}}) - if a != 5 || d != 1 { - t.Errorf("got +%d -%d", a, d) - } -} - func TestGitBranchMenu(t *testing.T) { acts := func(items []gitMenuItem) []gitBranchAct { out := make([]gitBranchAct, len(items)) @@ -262,17 +229,17 @@ func TestGitBranchMenu(t *testing.T) { } cases := []struct { name string - row gitTreeRow + row gitRefRow session bool want []gitBranchAct blocked gitBlocked }{ - {"a local branch", gitTreeRow{}, false, []gitBranchAct{gitActCheckout, gitActNewBranch, gitActRename, gitActDelete}, gitFree}, - {"the branch you are on", gitTreeRow{head: true, worktree: "/here"}, false, []gitBranchAct{gitActNewBranch, gitActRename, gitActDelete}, gitOnBranch}, - {"held by a worktree with a session", gitTreeRow{worktree: "/wt"}, true, []gitBranchAct{gitActOpenSession, gitActNewBranch, gitActRename, gitActDelete}, gitInWorktree}, - {"held by a worktree without one", gitTreeRow{worktree: "/wt"}, false, []gitBranchAct{gitActNewBranch, gitActRename, gitActDelete}, gitInWorktree}, - {"a remote branch", gitTreeRow{remote: true}, false, []gitBranchAct{gitActCheckoutRemote, gitActNewBranch}, gitFree}, - {"a tag", gitTreeRow{tag: true}, false, []gitBranchAct{gitActNewBranch}, gitFree}, + {"a local branch", gitRefRow{}, false, []gitBranchAct{gitActCheckout, gitActNewBranch, gitActRename, gitActHistory, gitActDelete}, gitFree}, + {"the branch you are on", gitRefRow{head: true, worktree: "/here"}, false, []gitBranchAct{gitActNewBranch, gitActRename, gitActHistory, gitActDelete}, gitOnBranch}, + {"held by a worktree with a session", gitRefRow{worktree: "/wt"}, true, []gitBranchAct{gitActOpenSession, gitActNewBranch, gitActRename, gitActHistory, gitActDelete}, gitInWorktree}, + {"held by a worktree without one", gitRefRow{worktree: "/wt"}, false, []gitBranchAct{gitActNewBranch, gitActRename, gitActHistory, gitActDelete}, gitInWorktree}, + {"a remote branch", gitRefRow{remote: true}, false, []gitBranchAct{gitActCheckoutRemote, gitActNewBranch, gitActHistory}, gitFree}, + {"a tag", gitRefRow{tag: true}, false, []gitBranchAct{gitActHistory, gitActNewBranch}, gitFree}, } for _, c := range cases { items := gitBranchMenu(c.row, c.session) @@ -284,19 +251,3 @@ func TestGitBranchMenu(t *testing.T) { } } } - -func TestGitHeadNodeTiesTheChangesOnlyWhenHeadHeadsThePage(t *testing.T) { - commits := []backend.GitCommit{{Hash: "a", Parents: []string{"b"}}, {Hash: "b", Head: true}} - rows, lanes := layoutGitGraph(commits) - view := gitLogView{commits: commits, rows: rows, lanes: lanes} - if _, first, ok := gitHeadNode(view); !ok || first { - t.Errorf("HEAD under a newer commit: ok=%v first=%v, want found and not first", ok, first) - } - view.commits[0].Head, view.commits[1].Head = true, false - if _, first, ok := gitHeadNode(view); !ok || !first { - t.Errorf("HEAD heading the page: ok=%v first=%v", ok, first) - } - if _, _, ok := gitHeadNode(gitLogView{commits: commits}); ok { - t.Error("a page with no graph has no node to tie to") - } -} diff --git a/native/cmd/lich-native/git_log.go b/native/cmd/lich-native/git_log.go index 17c71629c..016435caf 100644 --- a/native/cmd/lich-native/git_log.go +++ b/native/cmd/lich-native/git_log.go @@ -2,22 +2,20 @@ package main import ( "image" - "image/color" "slices" "strconv" "strings" "time" - "gioui.org/font" "gioui.org/layout" "gioui.org/op" "gioui.org/text" "gioui.org/unit" - "gioui.org/widget" "github.com/lichdotdev/lich/native/backend" "github.com/lichdotdev/lich/native/i18n" "github.com/lichdotdev/lich/native/ui" + "github.com/lichdotdev/lich/native/ui/icons" ) const ( @@ -30,13 +28,13 @@ const ( ) var ( - gitFilterHeight = ui.Space(12) - gitFieldHeight = ui.Space(8) - gitSearchWidth = unit.Dp(200) - gitPathWidth = unit.Dp(150) - gitRefMaxWidth = unit.Dp(170) - gitAuthorWidth = unit.Dp(96) - gitWhenWidth = unit.Dp(60) + gitStripHeight = ui.Space(8) // the search's line, and the filters' + gitPathWidth = unit.Dp(150) + gitRefMaxWidth = unit.Dp(170) + gitAuthorWidth = unit.Dp(96) + gitWhenWidth = unit.Dp(84) + + icGitFilter = icons.Lucide("list-filter") ) // applyTyped takes what was typed in the filter fields once typing stops. @@ -55,24 +53,87 @@ func (g *gitPanel) applyTyped(gtx C) { g.filter.query, g.filter.file = q, f } -func (g *gitPanel) filterBar(gtx C, th *ui.Theme, view gitLogView) D { - field := func(editor *widget.Editor, placeholder string, width unit.Dp) layout.FlexChild { +// filtersSet is whether anything but the search narrows the log. +func (g *gitPanel) filtersSet() bool { + return g.filter.ref != "" || g.filter.author != "" || g.sinceDays != 0 || g.file.Len() > 0 +} + +func (g *gitPanel) clearFilters() { + g.filter.ref, g.filterRef, g.filter.author = "", "", "" + g.sinceDays, g.filter.since = 0, 0 + g.file.SetText("") +} + +// history is the search over the log, with the filters' line between them +// once asked for. +func (g *gitPanel) history(gtx C, th *ui.Theme, view gitLogView, wide bool) D { + for g.filters.Click.Clicked(gtx) { + if g.filtersSet() { + g.clearFilters() + g.filtering = false + } else { + g.filtering = !g.filtering + } + } + for g.dropRef.Clicked(gtx) { + g.filter.ref, g.filterRef = "", "" + } + strip := func(w layout.Widget) layout.FlexChild { return layout.Rigid(func(gtx C) D { - in := th.Input(editor, placeholder) - in.Height, in.Width, in.TextSize = gitFieldHeight, width, ui.TextXS - return in.Layout(gtx) + gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, gtx.Dp(gitStripHeight))) + return layout.Inset{Left: ui.Space(2), Right: ui.Space(2)}.Layout(gtx, w) }) } - return layout.Inset{Left: ui.Space(2), Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - field(&g.query, i18n.T("git.panel.searchPlaceholder"), gitSearchWidth), - ui.Gap(1), - layout.Rigid(func(gtx C) D { return g.authorFilter(gtx, th, view) }), - layout.Rigid(func(gtx C) D { return g.dateFilter(gtx, th) }), - ui.Gap(1), - field(&g.file, i18n.T("git.panel.pathPlaceholder"), gitPathWidth), - ) - }) + kids := []layout.FlexChild{strip(func(gtx C) D { return g.searchLine(gtx, th) })} + if g.filtering || g.filtersSet() { + kids = append(kids, strip(func(gtx C) D { return g.filterLine(gtx, th, view) })) + } + kids = append(kids, layout.Flexed(1, func(gtx C) D { return g.logBody(gtx, th, view, wide) })) + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, kids...) +} + +// searchLine is the search with no box, the head of the list under it. +func (g *gitPanel) searchLine(gtx C, th *ui.Theme) D { + label := i18n.T("git.panel.filter") + if g.filtersSet() { + label = i18n.T("git.panel.clearFilters") + } + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Flexed(1, func(gtx C) D { + field := th.Input(&g.query, i18n.T("git.panel.searchPlaceholder")) + field.Bare, field.Height, field.TextSize = true, gitStripHeight, ui.TextXS + field.Leading, field.LeadingSize = icPullSearch, ui.Space(3.5) + return field.Layout(gtx) + }), + ui.Gap(1), + layout.Rigid(func(gtx C) D { + return th.IconAction(g.root, &g.filters, icGitFilter, label, g.filtering || g.filtersSet()).Layout(gtx) + }), + ) +} + +// filterLine is the ref the log is narrowed to, when it is, then who, when +// and which path. +func (g *gitPanel) filterLine(gtx C, th *ui.Theme, view gitLogView) D { + var kids []layout.FlexChild + if g.filter.ref != "" { + kids = append(kids, layout.Rigid(func(gtx C) D { + gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(gitRefMaxWidth)) + b := th.Button(&g.dropRef, gitCleanLine(g.filterRef)) + b.Variant, b.Size, b.Icon = ui.VariantSecondary, ui.SizeXS, icPullX + return b.Layout(gtx) + }), ui.Gap(1)) + } + kids = append(kids, + layout.Rigid(func(gtx C) D { return g.authorFilter(gtx, th, view) }), + layout.Rigid(func(gtx C) D { return g.dateFilter(gtx, th) }), + layout.Rigid(func(gtx C) D { + field := th.Input(&g.file, i18n.T("git.panel.pathPlaceholder")) + field.Bare, field.Height, field.Width, field.TextSize = true, gitStripHeight, gitPathWidth, ui.TextXS + return field.Layout(gtx) + }), + ) + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, kids...) } // gitAuthors are the authors of the commits loaded, newest first. @@ -106,7 +167,7 @@ func (g *gitPanel) authorFilter(gtx C, th *ui.Theme, view gitLogView) D { label = g.filter.author } b := th.Button(&g.author, gitCleanLine(label)) - b.Variant, b.Size, b.Icon = ui.VariantGhost, ui.SizeSM, icPullDown + b.Variant, b.Size, b.Icon = ui.VariantGhost, ui.SizeXS, icPullDown return th.DropdownMenu(g.root, &g.authorMenu, entries).Layout(gtx, b.Layout) } @@ -139,63 +200,24 @@ func (g *gitPanel) dateFilter(gtx C, th *ui.Theme) D { label = gitDateLabel(g.sinceDays) } b := th.Button(&g.date, label) - b.Variant, b.Size, b.Icon = ui.VariantGhost, ui.SizeSM, icPullDown + b.Variant, b.Size, b.Icon = ui.VariantGhost, ui.SizeXS, icPullDown return th.DropdownMenu(g.root, &g.dateMenu, entries).Layout(gtx, b.Layout) } -func (g *gitPanel) logBody(gtx C, th *ui.Theme, view gitLogView, in gitPanelInput) D { +// logBody is the commits; wide has the room to say who wrote each. +func (g *gitPanel) logBody(gtx C, th *ui.Theme, view gitLogView, wide bool) D { gtx.Constraints.Min = gtx.Constraints.Max switch { case !view.loaded: return gitLogSkeleton(gtx, th) case view.err != "": return gitNotice(gtx, th, i18n.T("git.panel.loadFailed", i18n.Args{"error": view.err})) - } - wip := in.cur.Files > 0 && g.filter.ref == "" && !g.filter.narrowed() - g.workShown = wip - if len(view.commits) == 0 && !wip { + case len(view.commits) == 0: return gitNotice(gtx, th, i18n.T("git.panel.noCommits")) } - first := 0 - if wip { - first = 1 - } list := gitScroll(th, &g.log) - return list.Layout(gtx, len(view.commits)+first, func(gtx C, i int) D { - if i < first { - return g.workRow(gtx, th, view, in) - } - return g.logRow(gtx, th, view, i-first, in) - }) -} - -// workRow is Uncommitted changes, over the history: a hollow ring tied to -// HEAD, and the lines it changes. -func (g *gitPanel) workRow(gtx C, th *ui.Theme, view gitLogView, in gitPanelInput) D { - r := &g.work - for r.click.Clicked(gtx) { - g.selected = gitWorkTree - g.detail.closeFile() - } - return r.click.Layout(gtx, func(gtx C) D { - size := image.Pt(gtx.Constraints.Max.X, gtx.Dp(gitRowHeight)) - gtx.Constraints = layout.Exact(size) - selected, hovered := g.selected == gitWorkTree, r.click.Hovered() - rowFill(gtx, th, selected, hovered) - graph := gitGraphWidth(gtx, view.lanes) - drawGitWorkNode(gtx, th, view, size.Y, rowGround(th, selected, hovered)) - left := max(graph+gtx.Dp(ui.Space(1.5)), gtx.Dp(ui.Space(3.5))) - return layout.Inset{Left: gtx.Metric.PxToDp(left), Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, th.Text(ui.TextSM, i18n.T("git.commit.uncommitted")).Truncated().Layout), - ui.Gap(2), - layout.Rigid(func(gtx C) D { - gtx.Constraints.Min = image.Point{} - return th.DiffStat(in.cur.Added, in.cur.Deleted).Layout(gtx) - }), - layout.Rigid(func(gtx C) D { return D{Size: image.Pt(gtx.Dp(gitAuthorWidth+gitWhenWidth), 0)} }), - ) - }) + return layout.Inset{Left: ui.Space(2), Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { + return list.Layout(gtx, len(view.commits), func(gtx C, i int) D { return g.logRow(gtx, th, view, i, wide) }) }) } @@ -214,12 +236,15 @@ func gitLogSkeleton(gtx C, th *ui.Theme) D { return D{Size: gtx.Constraints.Max} } -func (g *gitPanel) logRow(gtx C, th *ui.Theme, view gitLogView, i int, in gitPanelInput) D { +// logRow is one commit. A click opens it beside the log, and shuts it when it +// was the one open. +func (g *gitPanel) logRow(gtx C, th *ui.Theme, view gitLogView, i int, wide bool) D { c := view.commits[i] r := gitRow(g.rows, c.Hash) for r.click.Clicked(gtx) { - g.selected = c.Hash - g.detail.closeFile() + g.openCommit(c.Hash) + // The body took its columns before this row: draw it again. + gtx.Execute(op.InvalidateCmd{}) } if i >= len(view.commits)-gitLoadAhead { g.store.more() @@ -231,63 +256,72 @@ func (g *gitPanel) logRow(gtx C, th *ui.Theme, view gitLogView, i int, in gitPan rowFill(gtx, th, selected, hovered) graph := gitGraphWidth(gtx, view.lanes) if view.rows != nil { - n := gitNode{ground: rowGround(th, selected, hovered), merge: len(c.Parents) > 1, head: c.Head, workAbove: c.Head && i == 0 && g.workShown} + n := gitNode{ground: rowGround(th, selected, hovered), merge: len(c.Parents) > 1, head: c.Head} drawGitRow(gtx, th, view.rows[i], image.Pt(graph, size.Y), n) } - left := max(graph+gtx.Dp(ui.Space(1.5)), gtx.Dp(ui.Space(3.5))) - return layout.Inset{Left: gtx.Metric.PxToDp(left), Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { - tone := th.Foreground - if view.rows != nil { - tone = th.GraphLanes[view.rows[i].color%len(th.GraphLanes)] - } - return g.logRowText(gtx, th, c, r, in, tone) + left := max(graph+gtx.Dp(ui.Space(1.5)), gtx.Dp(ui.Space(2.5))) + return layout.Inset{Left: gtx.Metric.PxToDp(left), Right: ui.Space(2.5)}.Layout(gtx, func(gtx C) D { + return logRowText(gtx, th, c, wide) }) }) } -// logRowText is the subject with the commit's ref right after it, in its -// lane's tone, then who and when in their columns at the right. -func (g *gitPanel) logRowText(gtx C, th *ui.Theme, c backend.GitCommit, r *gitRowState, in gitPanelInput, tone color.NRGBA) D { +func (g *gitPanel) openCommit(hash string) { + if g.selected == hash { + hash = "" + } + g.selected = hash + g.detail.closeFile() +} + +// logRowText is the subject with the commit's ref right after it, then who +// and when in their columns at the right. +func logRowText(gtx C, th *ui.Theme, c backend.GitCommit, wide bool) D { fixed := func(width unit.Dp, w layout.Widget) layout.FlexChild { return layout.Rigid(func(gtx C) D { gtx.Constraints = layout.Exact(image.Pt(gtx.Dp(width), gtx.Constraints.Max.Y)) return layout.W.Layout(gtx, w) }) } - when := th.Text(ui.TextXS, gitWhen(c.When, gtx.Now)).Mono().Muted() + when := th.Text(ui.TextXS, gitWhen(c.When, gtx.Now)).Muted() when.Align = text.End - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { return g.subjectAndRef(gtx, th, c, r, in, tone) }), - ui.Gap(2), - fixed(gitAuthorWidth, func(gtx C) D { return th.Text(ui.TextXS, gitCleanLine(c.Author)).Muted().Truncated().Layout(gtx) }), - fixed(gitWhenWidth, func(gtx C) D { - gtx.Constraints.Min.X = gtx.Constraints.Max.X - return when.Layout(gtx) - }), - ) + kids := []layout.FlexChild{layout.Flexed(1, func(gtx C) D { return subjectAndRef(gtx, th, c) }), ui.Gap(2)} + if wide { + kids = append(kids, fixed(gitAuthorWidth, func(gtx C) D { return th.Text(ui.TextXS, gitCleanLine(c.Author)).Muted().Truncated().Layout(gtx) })) + } + kids = append(kids, fixed(gitWhenWidth, func(gtx C) D { + gtx.Constraints.Min.X = gtx.Constraints.Max.X + return when.Layout(gtx) + })) + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, kids...) } // subjectAndRef lays the ref out first, so a long subject is cut short of it // rather than pushing it off the row. -func (g *gitPanel) subjectAndRef(gtx C, th *ui.Theme, c backend.GitCommit, r *gitRowState, in gitPanelInput, tone color.NRGBA) D { +func subjectAndRef(gtx C, th *ui.Theme, c backend.GitCommit) D { ref := op.Record(gtx.Ops) cgtx := gtx cgtx.Constraints.Min = image.Point{} - rd := g.refCell(cgtx, th, c, r, in, tone) + rd := refCell(cgtx, th, c) refCall := ref.Stop() subject := gtx - subject.Constraints.Min.X = 0 + subject.Constraints.Min = image.Point{} subject.Constraints.Max.X = max(gtx.Constraints.Max.X-rd.Size.X, 0) + line := op.Record(gtx.Ops) sd := th.Text(ui.TextSM, gitCleanLine(c.Subject)).Truncated().Layout(subject) - off := op.Offset(image.Pt(sd.Size.X, (gtx.Constraints.Max.Y-rd.Size.Y)/2)).Push(gtx.Ops) + lineCall := line.Stop() + off := op.Offset(image.Pt(0, (gtx.Constraints.Max.Y-sd.Size.Y)/2)).Push(gtx.Ops) + lineCall.Add(gtx.Ops) + off.Pop() + off = op.Offset(image.Pt(sd.Size.X, (gtx.Constraints.Max.Y-rd.Size.Y)/2)).Push(gtx.Ops) refCall.Add(gtx.Ops) off.Pop() return D{Size: image.Pt(gtx.Constraints.Max.X, gtx.Constraints.Max.Y)} } -// refCell is the row's one ref, its glyph and name in its lane's tone, led by -// the ring of a session on that branch. -func (g *gitPanel) refCell(gtx C, th *ui.Theme, c backend.GitCommit, r *gitRowState, in gitPanelInput, tone color.NRGBA) D { +// refCell is the row's one ref, its glyph and name muted: the graph already +// has the lane's color. +func refCell(gtx C, th *ui.Theme, c backend.GitCommit) D { label, ok := gitRefLabelOf(c.Refs) if !ok { return D{} @@ -296,28 +330,17 @@ func (g *gitPanel) refCell(gtx C, th *ui.Theme, c backend.GitCommit, r *gitRowSt if label.extra > 0 { text += " +" + strconv.Itoa(label.extra) } - l := th.Text(ui.TextXS, text).Mono().In(tone) - if label.head { - l = l.Weight(font.Medium) - } ic := icBranch if label.kind == backend.GitRefTag { ic = icGitTag } - sv, onBranch := in.sessions[label.branch] - return layout.Inset{Left: ui.Space(2)}.Layout(gtx, func(gtx C) D { + return layout.Inset{Left: ui.Space(2.5)}.Layout(gtx, func(gtx C) D { return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { - if !onBranch { - return D{} - } - return layout.Inset{Right: ui.Space(1)}.Layout(gtx, func(gtx C) D { return g.sessionMark(gtx, th, r, sv) }) - }), - layout.Rigid(func(gtx C) D { return ic.Layout(gtx, ui.Space(3), tone) }), + layout.Rigid(func(gtx C) D { return ic.Layout(gtx, ui.Space(3), th.MutedForeground) }), ui.Gap(1), layout.Rigid(func(gtx C) D { gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(gitRefMaxWidth)) - return l.Truncated().Layout(gtx) + return th.Text(ui.TextXS, text).Muted().Truncated().Layout(gtx) }), ) }) diff --git a/native/cmd/lich-native/git_merge.go b/native/cmd/lich-native/git_merge.go index 1d43f8d58..9129a0a6f 100644 --- a/native/cmd/lich-native/git_merge.go +++ b/native/cmd/lich-native/git_merge.go @@ -21,7 +21,7 @@ type mergePreview struct { // gitMergeItem is the Merge entry a row offers into the checkout cur, false // for a row that has none: a tag, and the branch HEAD is on. -func gitMergeItem(row gitTreeRow, cur backend.DiffStats, p mergePreview) (gitMenuItem, bool) { +func gitMergeItem(row gitRefRow, cur backend.DiffStats, p mergePreview) (gitMenuItem, bool) { if row.tag || row.head { return gitMenuItem{}, false } @@ -39,14 +39,14 @@ func gitMergeItem(row gitTreeRow, cur backend.DiffStats, p mergePreview) (gitMen // mergeEntry dresses the item: the branch it merges into, why it cannot run, // or what the preview found. -func (g *gitPanel) mergeEntry(row gitTreeRow, in gitPanelInput) (ui.MenuEntry, bool) { +func (g *gitPanel) mergeEntry(row gitRefRow, in gitPanelInput) (ui.MenuEntry, bool) { p := g.preview(row, in.cur) it, ok := gitMergeItem(row, in.cur, p) if !ok { return ui.MenuEntry{}, false } e := ui.MenuEntry{Label: i18n.T("git.merge.into", i18n.Args{"branch": branchOrHead(in.cur.Branch)}), - OnClick: func() { g.merge(row, in) }} + OnClick: func() { g.picker.panel.Close(); g.merge(row, in) }} switch { case it.blocked != gitFree: e.Disabled, e.Shortcut = true, gitBlockedText(it.blocked) @@ -68,7 +68,7 @@ func branchOrHead(branch string) string { // preview answers what merging row would bring, asking the backend the first // time a menu shows it for this HEAD. -func (g *gitPanel) preview(row gitTreeRow, cur backend.DiffStats) mergePreview { +func (g *gitPanel) preview(row gitRefRow, cur backend.DiffStats) mergePreview { g.mu.Lock() defer g.mu.Unlock() if g.previewHead != cur.Head || g.previews == nil { @@ -94,7 +94,7 @@ func (g *gitPanel) preview(row gitTreeRow, cur backend.DiffStats) mergePreview { // merge runs it off the UI goroutine. A clean merge toasts the command with an // Undo; one that stops says so and points at the Review, where it ends. -func (g *gitPanel) merge(row gitTreeRow, in gitPanelInput) { +func (g *gitPanel) merge(row gitRefRow, in gitPanelInput) { path, into := g.path, branchOrHead(in.cur.Branch) behind := 0 if st, ok := in.status(row.worktree); ok && row.worktree != "" { diff --git a/native/cmd/lich-native/git_merge_test.go b/native/cmd/lich-native/git_merge_test.go index 78c48f4d3..fcdd15493 100644 --- a/native/cmd/lich-native/git_merge_test.go +++ b/native/cmd/lich-native/git_merge_test.go @@ -13,22 +13,22 @@ func TestGitMergeItem(t *testing.T) { none := mergePreview{done: true} cases := []struct { name string - row gitTreeRow + row gitRefRow cur backend.DiffStats preview mergePreview offered bool blocked gitBlocked }{ - {"a local branch", gitTreeRow{}, clean, ready, true, gitFree}, - {"a remote branch", gitTreeRow{remote: true}, clean, ready, true, gitFree}, - {"a branch held by another worktree", gitTreeRow{worktree: "/wt"}, clean, ready, true, gitFree}, - {"still reading the preview", gitTreeRow{}, clean, mergePreview{}, true, gitFree}, - {"a preview that failed", gitTreeRow{}, clean, mergePreview{done: true, failed: true}, true, gitFree}, - {"nothing to bring", gitTreeRow{}, clean, none, true, gitMerged}, - {"uncommitted changes here", gitTreeRow{}, backend.DiffStats{Files: 1}, ready, true, gitDirtyHere}, - {"a merge already running", gitTreeRow{}, backend.DiffStats{Files: 1, Merging: "x"}, ready, true, gitMergeRunning}, - {"the branch HEAD is on", gitTreeRow{head: true}, clean, ready, false, gitFree}, - {"a tag", gitTreeRow{tag: true}, clean, ready, false, gitFree}, + {"a local branch", gitRefRow{}, clean, ready, true, gitFree}, + {"a remote branch", gitRefRow{remote: true}, clean, ready, true, gitFree}, + {"a branch held by another worktree", gitRefRow{worktree: "/wt"}, clean, ready, true, gitFree}, + {"still reading the preview", gitRefRow{}, clean, mergePreview{}, true, gitFree}, + {"a preview that failed", gitRefRow{}, clean, mergePreview{done: true, failed: true}, true, gitFree}, + {"nothing to bring", gitRefRow{}, clean, none, true, gitMerged}, + {"uncommitted changes here", gitRefRow{}, backend.DiffStats{Files: 1}, ready, true, gitDirtyHere}, + {"a merge already running", gitRefRow{}, backend.DiffStats{Files: 1, Merging: "x"}, ready, true, gitMergeRunning}, + {"the branch HEAD is on", gitRefRow{head: true}, clean, ready, false, gitFree}, + {"a tag", gitRefRow{tag: true}, clean, ready, false, gitFree}, } for _, c := range cases { it, ok := gitMergeItem(c.row, c.cur, c.preview) diff --git a/native/cmd/lich-native/git_panel.go b/native/cmd/lich-native/git_panel.go index 469c84af9..409757c54 100644 --- a/native/cmd/lich-native/git_panel.go +++ b/native/cmd/lich-native/git_panel.go @@ -1,8 +1,9 @@ package main // The Git panel: the region at the stage's foot, opened from the branch's -// balloon, that reads the repository of the active session. Log, the only tab -// for now, is the branch tree, the history and the selected commit's detail. +// balloon, on the repository of the active session. It shows one job at a +// time: Changes, what to commit, or History, what was. The branch in its +// header opens the branches. import ( "context" @@ -14,7 +15,6 @@ import ( "strings" "time" - "gioui.org/f32" "gioui.org/layout" "gioui.org/op" "gioui.org/op/clip" @@ -34,22 +34,32 @@ const ( gitHeightKey = "lich.git.height" gitMinRem = 12 gitMaxRem = 60 - gitDefaultRem = 19 + gitDefaultRem = 20.5 gitStageFloorRem = 10 - gitTreeWidthKey = "lich.git.tree.width" - gitDetailWidthKey = "lich.git.detail.width" - gitMessageKey = "lich.git.detail.message" - // gitFilesFloorRem is what dragging the message up leaves the file list. + gitChangesWidthKey = "lich.git.changes.width" + gitLogWidthKey = "lich.git.log.width" + // gitFilesFloorRem is what a message growing leaves the files over it. gitFilesFloorRem = 5 - // gitLogFloorRem is what dragging either side column leaves the log. - gitLogFloorRem = 18 + // gitDiffFloorRem is what dragging the left column leaves the diff. + gitDiffFloorRem = 18 ) -// gitColumnGap is the space between the tree, the log and the detail, the -// window's gutter between islands. +// gitColumnGap is the space between the panel's two columns, the window's +// gutter between islands. const gitColumnGap = gutter +// gitBranchMax is how much of the branch's name the header shows. +var gitBranchMax = unit.Dp(280) + +// gitTab is the panel's tab, the index the strip keeps. +type gitTab int + +const ( + gitTabChanges gitTab = iota + gitTabHistory +) + // gitColumn is a side column whose width is dragged and kept. type gitColumn struct { key string @@ -85,10 +95,10 @@ type gitPanelInput struct { newKind string } -// gitRowState is a list row's clickable and its tooltip. +// gitRowState is a list row's clickable and its menus. type gitRowState struct { click ui.Clickable - tip, moreTip ui.Tooltip + moreTip ui.Tooltip more ui.Clickable menu, context ui.MenuState } @@ -112,39 +122,36 @@ type gitPanel struct { covers bool pendingPx int path string - treeCol gitColumn - detailCol gitColumn - // messageCol is the commit message's height under the file list. - messageCol gitColumn + // changesCol is the files of Changes; logCol the log once a commit is open + // beside it. + changesCol, logCol gitColumn + tabs ui.TabsState filter gitLogFilter + filterRef string // the name of filter.ref query, file widget.Editor typedQuery, typedFile string typedAt time.Time sinceDays int - authorMenu, dateMenu ui.MenuState - author, date ui.Clickable - - treeField widget.Editor - tree widget.List - treeRows map[string]*gitRowState - // folders is whether each folder of branches the person opened or shut - // shows them; one they never touched follows folderOpen. - folders map[string]bool - - log widget.List - rows map[string]*gitRowState + // filtering is whether the filters' line was asked for; it also shows while + // one of them is set. + filtering bool + filters ui.IconActionState + dropRef ui.Clickable + authorMenu, dateMenu ui.MenuState + author, date ui.Clickable + + log widget.List + rows map[string]*gitRowState + // selected is the commit open beside the log, "" for none. selected string detail gitDetailPane form gitCommitForm - // shown is whether the panel was on screen last frame: opening it with - // uncommitted changes selects them. + picker gitPicker + // shown is whether the panel was on screen last frame: opening it picks + // the tab. shown bool - work gitRowState - // workShown is whether this frame's log heads its rows with the - // uncommitted changes. - workShown bool branchOps } @@ -152,15 +159,15 @@ func newGitPanel(ctx context.Context, client *backend.Client, root *ui.Root, inv g := &gitPanel{root: root, family: family, size: size, heightRem: gitDefaultRem, notify: notify, invalidate: invalidate, resize: ui.ResizeHandle{Edge: ui.PanelEdgeTop}, - treeCol: gitColumn{key: gitTreeWidthKey, rem: 12.5, minRem: 9, maxRem: 32, resize: ui.ResizeHandle{Edge: ui.PanelEdgeRight}}, - detailCol: gitColumn{key: gitDetailWidthKey, rem: 16.25, minRem: 12, maxRem: 40, resize: ui.ResizeHandle{Edge: ui.PanelEdgeLeft}}, - messageCol: gitColumn{key: gitMessageKey, rem: 7.5, minRem: 4, maxRem: 40, resize: ui.ResizeHandle{Edge: ui.PanelEdgeTop}}, + changesCol: gitColumn{key: gitChangesWidthKey, rem: 21.25, minRem: 14, maxRem: 40, resize: ui.ResizeHandle{Edge: ui.PanelEdgeRight}}, + logCol: gitColumn{key: gitLogWidthKey, rem: 31.25, minRem: 16, maxRem: 60, resize: ui.ResizeHandle{Edge: ui.PanelEdgeRight}}, store: &gitStore{ctx: ctx, client: client, invalidate: invalidate}, - treeRows: map[string]*gitRowState{}, rows: map[string]*gitRowState{}, folders: map[string]bool{}, + rows: map[string]*gitRowState{}, } - g.tree.Axis, g.log.Axis = layout.Vertical, layout.Vertical + g.log.Axis = layout.Vertical g.detail.init() g.form.init() + g.picker.init() return g } @@ -188,8 +195,8 @@ func (g *gitPanel) holdsKeys(gtx C) bool { if !g.open { return false } - return gtx.Focused(&g.query) || gtx.Focused(&g.file) || gtx.Focused(&g.treeField) || gtx.Focused(&g.form.message) || - g.authorMenu.Opened() || g.dateMenu.Opened() || + return gtx.Focused(&g.query) || gtx.Focused(&g.file) || gtx.Focused(&g.form.message) || + g.picker.panel.Opened() || g.authorMenu.Opened() || g.dateMenu.Opened() || g.editing != nil || g.menuOpen } @@ -219,13 +226,13 @@ func (g *gitPanel) act(gtx C) { func (g *gitPanel) layout(gtx C, th *ui.Theme, in gitPanelInput) { if in.path != g.path { g.path, g.selected = in.path, "" - g.filter.ref = "" + g.filter.ref, g.filterRef = "", "" g.detail.closeFile() } g.applyTyped(gtx) g.store.follow(in.path, g.filter) view := g.store.snapshot() - g.followWork(in, view) + g.openOnWork(in) size := gtx.Constraints.Max gtx.Constraints = layout.Exact(size) @@ -233,130 +240,101 @@ func (g *gitPanel) layout(gtx C, th *ui.Theme, in gitPanelInput) { ui.Fill(gtx, th.Sidebar, 0) on := th.On(th.Sidebar) defer ui.InsetBorder(gtx, size, gtx.Dp(ui.RadiusLG), on.Over(on.Border)) - cols := g.columns(gtx) layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { return g.header(gtx, on, view, in, cols) }), - layout.Flexed(1, func(gtx C) D { return g.body(gtx, on, view, in, cols) }), + layout.Rigid(func(gtx C) D { return g.header(gtx, on, view, in) }), + layout.Flexed(1, func(gtx C) D { return g.body(gtx, on, view, in) }), ) if !g.expanded { g.resize.Layout(gtx, on) } } -// followWork selects the uncommitted changes when the panel opens on some, -// and HEAD when it opens on none or once they are all committed, so the -// detail never opens empty. -func (g *gitPanel) followWork(in gitPanelInput, view gitLogView) { - if !g.shown { - g.shown = true - if in.cur.Files > 0 { - g.selected = gitWorkTree - g.detail.closeFile() - } +// openOnWork picks the tab as the panel opens: Changes when there is something +// to commit, else History. +func (g *gitPanel) openOnWork(in gitPanelInput) { + if g.shown { + return } - if (g.selected == "" || g.selected == gitWorkTree && in.cur.Files == 0) && view.loaded { - g.selected = view.refs.Head - g.detail.closeFile() + g.shown = true + g.show(gitTabHistory) + if in.cur.Files > 0 { + g.show(gitTabChanges) } } -// header is the panel's one line: its name over the tree, the log's filters -// over the log, the push or pull the branch calls for, and the panel's -// actions at the right. -func (g *gitPanel) header(gtx C, th *ui.Theme, view gitLogView, in gitPanelInput, cols gitColumns) D { - gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, gtx.Dp(dockHeaderHeight))) - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { - gtx.Constraints = layout.Exact(image.Pt(cols.tree, gtx.Constraints.Max.Y)) - return layout.Inset{Left: ui.Space(2.5)}.Layout(gtx, func(gtx C) D { - return layout.W.Layout(gtx, th.Text(ui.TextSM, i18n.T("git.panel.title")).Layout) - }) - }), - layout.Rigid(func(gtx C) D { return D{Size: image.Pt(gtx.Dp(gitColumnGap), 0)} }), - layout.Flexed(1, func(gtx C) D { - gtx.Constraints.Min.X = 0 - return g.filterBar(gtx, th, view) - }), - layout.Rigid(func(gtx C) D { return g.syncActions(gtx, th, in) }), - layout.Rigid(func(gtx C) D { - return layout.Inset{Left: ui.Space(2), Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { - ic, label := icDockMaximize, i18n.T("dock.rightDock.fullScreen") - if g.expanded { - ic, label = icDockMinimize, i18n.T("dock.rightDock.exitFullScreen") - } - return th.IconAction(g.root, &g.full, ic, label, false).Layout(gtx) - }), - ui.Gap(1), - layout.Rigid(func(gtx C) D { - return th.IconAction(g.root, &g.close, icDockClose, i18n.T("git.panel.close"), false).Layout(gtx) - }), - ) - }) - }), - ) -} +func (g *gitPanel) tab() gitTab { return gitTab(g.tabs.Selected) } -// gitColumns is one frame's widths of the tree and the detail, in px. -type gitColumns struct{ tree, detail int } - -// columns reads the frame's drags of the two side columns, once, for the -// header and the body to lay out on. -func (g *gitPanel) columns(gtx C) gitColumns { - spare := gtx.Metric.PxToDp(gtx.Constraints.Max.X) - unit.Dp(gitLogFloorRem*remDp) - tree, treeDone := g.treeCol.width(gtx, spare-unit.Dp(g.detailCol.rem*remDp)) - detail, detailDone := g.detailCol.width(gtx, spare-unit.Dp(g.treeCol.rem*remDp)) - if treeDone { - g.saveColumn(g.treeCol) - } - if detailDone { - g.saveColumn(g.detailCol) +func (g *gitPanel) show(t gitTab) { g.tabs.Selected = int(t) } + +// header is the panel's one line: its tabs, then the branch, the push or pull +// it calls for and the panel's own actions at the right. +func (g *gitPanel) header(gtx C, th *ui.Theme, view gitLogView, in gitPanelInput) D { + gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, gtx.Dp(dockHeaderHeight))) + return layout.Inset{Left: ui.Space(2), Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(func(gtx C) D { return g.tabStrip(gtx, th, in) }), + layout.Flexed(1, func(gtx C) D { + return layout.E.Layout(gtx, func(gtx C) D { return g.branchButton(gtx, th, view, in) }) + }), + layout.Rigid(func(gtx C) D { return g.syncActions(gtx, th, in) }), + ui.Gap(2), + layout.Rigid(func(gtx C) D { + ic, label := icDockMaximize, i18n.T("dock.rightDock.fullScreen") + if g.expanded { + ic, label = icDockMinimize, i18n.T("dock.rightDock.exitFullScreen") + } + return th.IconAction(g.root, &g.full, ic, label, false).Layout(gtx) + }), + ui.Gap(1), + layout.Rigid(func(gtx C) D { + return th.IconAction(g.root, &g.close, icDockClose, i18n.T("git.panel.close"), false).Layout(gtx) + }), + ) + }) +} + +func (g *gitPanel) tabStrip(gtx C, th *ui.Theme, in gitPanelInput) D { + gtx.Constraints.Min = image.Point{} + changes := ui.TabsTrigger{Text: i18n.T("git.commit.changes")} + if n := in.cur.Files; n > 0 { + changes.Trailing = th.Text(ui.TextXS, strconv.Itoa(n)).Muted().Layout } - return gitColumns{tree: tree, detail: detail} + tabs := th.Tabs(&g.tabs, changes, ui.TabsTrigger{Text: i18n.T("git.panel.history")}) + tabs.Variant = ui.TabsVariantGhost + return tabs.Layout(gtx) } -func (g *gitPanel) body(gtx C, th *ui.Theme, view gitLogView, in gitPanelInput, cols gitColumns) D { +func (g *gitPanel) body(gtx C, th *ui.Theme, view gitLogView, in gitPanelInput) D { gtx.Constraints.Min = gtx.Constraints.Max - treeWidth, detailWidth := cols.tree, cols.detail - column := func(width int, w layout.Widget) layout.FlexChild { - return layout.Rigid(func(gtx C) D { - gtx.Constraints = layout.Exact(image.Pt(width, gtx.Constraints.Max.Y)) - return w(gtx) - }) + switch { + case g.tab() == gitTabChanges: + return g.changesTab(gtx, th, in) + case g.selected == "": + return g.history(gtx, th, view, true) } - // Columns stand apart by space, never a rule; their handles take the gap. - gap := layout.Rigid(func(gtx C) D { return D{Size: image.Pt(gtx.Dp(gitColumnGap), 0)} }) - dims := layout.Flex{}.Layout(gtx, - column(treeWidth, func(gtx C) D { return g.treeColumn(gtx, th, view, in) }), - gap, - layout.Flexed(1, func(gtx C) D { - gtx.Constraints.Min = gtx.Constraints.Max - if g.detail.diffOpen() { - return g.detail.layoutDiff(gtx, th, g, in) - } - return g.logBody(gtx, th, view, in) - }), - gap, - column(detailWidth, func(gtx C) D { return g.detailColumn(gtx, th, in) }), - ) - g.columnHandles(gtx, treeWidth, detailWidth) - return dims + return g.columns(gtx, &g.logCol, + func(gtx C) D { return g.history(gtx, th, view, false) }, + func(gtx C) D { return g.commitPane(gtx, th, in) }) } -// columnHandles lays the two handles out in the gaps between the columns, -// as the sidebar's and the dock's are: they draw nothing over a column, so -// neither covers the tree's scrollbar. -func (g *gitPanel) columnHandles(gtx C, treeWidth, detailWidth int) { +// columns lays left, as wide as it was dragged, and right, a gap apart with +// no rule; the handle takes the gap. +func (g *gitPanel) columns(gtx C, c *gitColumn, left, right layout.Widget) D { size := gtx.Constraints.Max + width, released := c.width(gtx, gtx.Metric.PxToDp(size.X)-unit.Dp(gitDiffFloorRem*remDp)) + if released { + g.saveColumn(*c) + } gap := gtx.Dp(gitColumnGap) - tree := gtx - tree.Constraints = layout.Exact(image.Pt(treeWidth, size.Y)) - g.treeCol.resize.LayoutGap(tree, gap) - defer op.Offset(image.Pt(size.X-detailWidth, 0)).Push(gtx.Ops).Pop() - detail := gtx - detail.Constraints = layout.Exact(image.Pt(detailWidth, size.Y)) - g.detailCol.resize.LayoutGap(detail, gap) + pane := gtx + pane.Constraints = layout.Exact(image.Pt(width, size.Y)) + left(pane) + c.resize.LayoutGap(pane, gap) + defer op.Offset(image.Pt(width+gap, 0)).Push(gtx.Ops).Pop() + pane.Constraints = layout.Exact(image.Pt(max(size.X-width-gap, 0), size.Y)) + defer clip.Rect{Max: pane.Constraints.Max}.Push(gtx.Ops).Pop() + right(pane) + return D{Size: size} } func (g *gitPanel) saveColumn(c gitColumn) { @@ -371,7 +349,7 @@ func (g *gitPanel) saveColumn(c gitColumn) { // loadColumns reads the stored widths; an unset or unreadable one keeps the // default. func (g *gitPanel) loadColumns(ctx context.Context, c *backend.Client) error { - for _, col := range []*gitColumn{&g.treeCol, &g.detailCol, &g.messageCol} { + for _, col := range []*gitColumn{&g.changesCol, &g.logCol} { raw, err := c.GetSetting(ctx, col.key, "") if err != nil { return err @@ -428,28 +406,6 @@ func gitCleanLine(s string) string { return strings.NewReplacer("\t", " ", "\n", " ", "\r", "").Replace(s) } -// gitSessionRing marks a branch a session is on, colored by what it is doing. -func gitSessionRing(gtx C, th *ui.Theme, status string) D { - size := gtx.Dp(ui.Space(3)) - stroke := float32(gtx.Dp(sessionTreeStroke)) - tone := th.MutedForeground - switch status { - case "waiting": - tone = th.ToneWait - case "done": - tone = th.TonePass - } - center := float32(size) / 2 - ui.StrokeArc(gtx, f32.Pt(center, center), center-stroke/2, stroke, 0, 2*math.Pi, tone) - return D{Size: image.Pt(size, size)} -} - -// sessionMark is the session's ring with its name in a tooltip. -func (g *gitPanel) sessionMark(gtx C, th *ui.Theme, r *gitRowState, sv sessionView) D { - tip := th.Tooltip(g.root, &r.tip, sv.Label) - return tip.Layout(gtx, func(gtx C) D { return gitSessionRing(gtx, th, sv.status) }) -} - func parseGitHeight(raw string) float64 { return parseGitRem(raw, gitDefaultRem, gitMinRem, gitMaxRem) } diff --git a/native/cmd/lich-native/git_refs.go b/native/cmd/lich-native/git_refs.go index 435d5d216..948e6afde 100644 --- a/native/cmd/lich-native/git_refs.go +++ b/native/cmd/lich-native/git_refs.go @@ -1,301 +1,353 @@ package main +// The branches, opened from the branch in the Git panel's header: the one HEAD +// is on first, the other local ones, then the remote ones and the tags, each +// behind a row that unfolds them. + import ( - "cmp" + "context" "image" "slices" "strconv" "strings" - "gioui.org/font" + "gioui.org/io/key" "gioui.org/layout" + "gioui.org/op" + "gioui.org/unit" + "gioui.org/widget" + "github.com/lichdotdev/lich/api" "github.com/lichdotdev/lich/native/backend" "github.com/lichdotdev/lich/native/i18n" "github.com/lichdotdev/lich/native/ui" "github.com/lichdotdev/lich/native/ui/icons" ) -var icGitTag = icons.Lucide("tag") +var ( + icGitTag = icons.Lucide("tag") + + gitPickerWidth = unit.Dp(340) + gitPickerHeight = unit.Dp(440) + gitPickerSlot = ui.Space(4) // a row's end: its check, its ⋯ or its chevron +) -// gitFolderIndent sets a folder's branches in under its name, past its -// chevron and the gap after it. -var gitFolderIndent = ui.Space(4.5) +const shortHashLen = 8 -// gitTreeRow is one line of the branch tree: a group's label, or a ref. ref is -// the full name the log is narrowed by, so a tag and a branch of one name are -// two rows; branch is the local branch a session could be on. -// name is git's short name for the ref, origin/x for a remote branch, and -// worktree where a local branch is checked out. -// folder is set on a folder row, the prefix its branches share, with count -// the branches in it; parent is the folder a branch row sits in. -type gitTreeRow struct { - label, ref, branch, name, worktree string - folder, parent string - count int - group, tag, head, remote bool +// The groups a row of the branches unfolds. +const ( + gitGroupRemote = "remote" + gitGroupTags = "tags" +) + +// gitRefRow is one line of the branches: a ref, or the group that unfolds +// more of them. ref is the full name the log is narrowed by, so a tag and a +// branch of one name are two rows; branch is the local branch a session could +// be on. name is git's short name for the ref, origin/x for a remote branch, +// and worktree where a local branch is checked out. On a group, count is the +// refs it holds. +type gitRefRow struct { + ref, branch, name, worktree string + group string + count int + tag, head, remote bool } -// gitTreeRows lays the refs out under Local, each remote and Tags, keeping the -// ones whose name holds filter. A group nothing matched is left out. -func gitTreeRows(refs []backend.GitRef, filter string) []gitTreeRow { +// gitRefRows are the rows holding filter, with the refs of the groups open +// says are unfolded. A group nothing matched is left out. +func gitRefRows(refs []backend.GitRef, filter string, open func(group string) bool) []gitRefRow { filter = strings.ToLower(filter) - keep := slices.DeleteFunc(slices.Clone(refs), func(r backend.GitRef) bool { - return !strings.Contains(strings.ToLower(r.Name), filter) - }) - var local, tags []gitTreeRow - remotes := map[string][]gitTreeRow{} - for _, r := range keep { + var local, remotes, tags []gitRefRow + for _, r := range refs { + if !strings.Contains(strings.ToLower(r.Name), filter) { + continue + } switch r.Kind { case backend.GitRefLocal: - local = append(local, gitTreeRow{label: r.Name, ref: "refs/heads/" + r.Name, branch: r.Name, name: r.Name, head: r.Head, worktree: r.Worktree}) + row := gitRefRow{ref: "refs/heads/" + r.Name, branch: r.Name, name: r.Name, head: r.Head, worktree: r.Worktree} + if r.Head { + local = slices.Insert(local, 0, row) + continue + } + local = append(local, row) case backend.GitRefTag: - tags = append(tags, gitTreeRow{label: r.Name, ref: "refs/tags/" + r.Name, name: r.Name, tag: true}) + tags = append(tags, gitRefRow{ref: "refs/tags/" + r.Name, name: r.Name, tag: true}) default: - remote, name, _ := strings.Cut(r.Name, "/") - remotes[remote] = append(remotes[remote], gitTreeRow{label: name, ref: "refs/remotes/" + r.Name, name: r.Name, remote: true}) + remotes = append(remotes, gitRefRow{ref: "refs/remotes/" + r.Name, name: r.Name, remote: true}) } } - var rows []gitTreeRow - add := func(group string, items []gitTreeRow) { - if len(items) > 0 { - rows = append(append(rows, gitTreeRow{label: group, group: true}), items...) + rows := local + add := func(group string, items []gitRefRow) { + if len(items) == 0 { + return + } + rows = append(rows, gitRefRow{group: group, count: len(items)}) + if open(group) { + rows = append(rows, items...) } } - add(i18n.T("git.panel.local"), gitFolders(local)) - names := make([]string, 0, len(remotes)) - for name := range remotes { - names = append(names, name) - } - slices.SortFunc(names, cmp.Compare[string]) - for _, name := range names { - add(name, remotes[name]) - } - add(i18n.T("git.panel.tags"), tags) + add(gitGroupRemote, remotes) + add(gitGroupTags, tags) return rows } -// gitFolders puts the local branches that share a prefix before their first -// slash (feat/, fix/) in a folder row of their own, folders first, and leaves -// the rest loose after them, as IntelliJ's tree does. -func gitFolders(local []gitTreeRow) []gitTreeRow { - byFolder := map[string][]gitTreeRow{} - var folders []string - var loose []gitTreeRow - for _, r := range local { - folder, name, ok := strings.Cut(r.name, "/") - if !ok { - loose = append(loose, r) - continue - } - if _, seen := byFolder[folder]; !seen { - folders = append(folders, folder) - } - r.label, r.parent = name, folder - byFolder[folder] = append(byFolder[folder], r) - } - slices.Sort(folders) - var rows []gitTreeRow - for _, f := range folders { - kids := byFolder[f] - rows = append(append(rows, gitTreeRow{label: f + "/", folder: f, count: len(kids)}), kids...) - } - return append(rows, loose...) +// gitPicker is the branches' panel and what is typed in it. +type gitPicker struct { + button ui.Clickable + panel ui.DropdownPanelState + field widget.Editor + list widget.List + rows map[string]*gitRowState + groups map[string]bool + create ui.Clickable + // opened is whether the panel was up last frame: it opens with nothing + // typed in it. + opened bool } -// gitShownRows leaves out the branches of the folders open says are shut. -func gitShownRows(rows []gitTreeRow, open func(folder string) bool) []gitTreeRow { - return slices.DeleteFunc(slices.Clone(rows), func(r gitTreeRow) bool { return r.parent != "" && !open(r.parent) }) +func (k *gitPicker) init() { + k.list.Axis = layout.Vertical + k.field.SingleLine, k.field.Submit = true, true + k.rows, k.groups = map[string]*gitRowState{}, map[string]bool{} } -// folderOpen is whether folder shows its branches: as the person left it, -// else open while a filter is typed or while it holds the branch HEAD is on. -func (g *gitPanel) folderOpen(rows []gitTreeRow, filter string) func(string) bool { - return func(folder string) bool { - if open, set := g.folders[folder]; set { - return open - } - return filter != "" || slices.ContainsFunc(rows, func(r gitTreeRow) bool { return r.parent == folder && r.head }) +// gitHeadName is the branch HEAD is on, or its short hash on a detached one. +func gitHeadName(view gitLogView, cur backend.DiffStats) string { + if cur.Branch != "" { + return cur.Branch + } + if i := slices.IndexFunc(view.refs.Refs, func(r backend.GitRef) bool { return r.Head }); i >= 0 { + return view.refs.Refs[i].Name + } + return view.refs.Head[:min(len(view.refs.Head), shortHashLen)] +} + +// branchButton is the branch in the header; a press opens the branches. +func (g *gitPanel) branchButton(gtx C, th *ui.Theme, view gitLogView, in gitPanelInput) D { + k := &g.picker + if k.panel.Opened() != k.opened { + k.opened = k.panel.Opened() + k.field.SetText("") + g.editing = nil + } + if !k.opened { + g.menuOpen = false + } + name := gitHeadName(view, in.cur) + if name == "" { + return D{} } + gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(gitBranchMax)) + b := th.Button(&k.button, gitCleanLine(name)) + b.Variant, b.Icon = ui.VariantGhost, icBranch + pop := th.DropdownPanel(g.root, &k.panel, gitPickerWidth, func(gtx C, th *ui.Theme) D { return g.branchList(gtx, th, view, in) }) + pop.AlignEnd, pop.MaxHeight = true, gitPickerHeight + return pop.Layout(gtx, b.Layout) } -func (g *gitPanel) treeColumn(gtx C, th *ui.Theme, view gitLogView, in gitPanelInput) D { +// branchList is the field that finds or names a branch, over the rows. +func (g *gitPanel) branchList(gtx C, th *ui.Theme, view gitLogView, in gitPanelInput) D { + k := &g.picker + typing := g.editing == nil && !g.menuOpen g.menuOpen = false - filter := strings.TrimSpace(g.treeField.Text()) - all := gitTreeRows(view.refs.Refs, filter) - open := g.folderOpen(all, filter) - rows := gitShownRows(all, open) + submit := k.fieldEvents(gtx) + typed := strings.TrimSpace(k.field.Text()) + rows := gitRefRows(view.refs.Refs, typed, func(group string) bool { return typed != "" || k.groups[group] }) + create := typed != "" && !slices.ContainsFunc(view.refs.Refs, func(r backend.GitRef) bool { + return r.Kind == backend.GitRefLocal && r.Name == typed + }) + // Enter takes the first ref the text finds, else makes the branch it names. + first := slices.IndexFunc(rows, func(r gitRefRow) bool { return r.group == "" }) + if submit && typed != "" { + if first >= 0 { + g.pickRef(rows[first], in) + } else if create { + g.createHere(typed, in) + } + } + for k.create.Clicked(gtx) { + g.createHere(typed, in) + } + if typing && !gtx.Focused(&k.field) { + gtx.Execute(key.FocusCmd{Tag: &k.field}) + } + count := len(rows) + if create { + count++ + } return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { - return layout.Inset{Left: ui.Space(1), Right: ui.Space(1), Bottom: ui.Space(1)}.Layout(gtx, func(gtx C) D { - field := th.Input(&g.treeField, i18n.T("git.panel.branchPlaceholder")) - field.Height, field.TextSize = gitFieldHeight, ui.TextXS - return field.Layout(gtx) - }) + field := th.Input(&k.field, i18n.T("git.panel.branchPlaceholder")) + field.Bare, field.Height, field.Leading, field.LeadingSize = true, ui.Space(8), icPullSearch, ui.Space(3.5) + return field.Layout(gtx) }), + ui.VGap(1), layout.Flexed(1, func(gtx C) D { - list := gitScroll(th, &g.tree) - return layout.Inset{Left: ui.Space(1), Right: ui.Space(1)}.Layout(gtx, func(gtx C) D { - return list.Layout(gtx, len(rows)+1, func(gtx C, i int) D { - if i == 0 { - return g.headRow(gtx, th, view) - } - row := rows[i-1] - return g.treeRow(gtx, th, row, row.folder != "" && open(row.folder), in) - }) + gtx.Constraints.Min.Y = 0 + return gitScroll(th, &k.list).Layout(gtx, count, func(gtx C, i int) D { + if i == len(rows) { + return th.PopoverRow(&k.create, func(gtx C, on *ui.Theme) D { + return on.Text(ui.TextSM, i18n.T("git.branch.create", i18n.Args{"name": typed})).Truncated().Layout(gtx) + }).Layout(gtx) + } + return g.pickerRow(gtx, th, rows[i], typed != "" && i == first, in) }) }), ) } -// headRow narrows the log to what HEAD reaches, and names where HEAD is. -func (g *gitPanel) headRow(gtx C, th *ui.Theme, view gitLogView) D { - name := "" - if i := slices.IndexFunc(view.refs.Refs, func(r backend.GitRef) bool { return r.Head }); i >= 0 { - name = view.refs.Refs[i].Name - } else if head := view.refs.Head; len(head) >= shortHashLen { - name = head[:shortHashLen] - } - return g.refRow(gtx, th, gitRow(g.treeRows, "HEAD"), gitTreeRow{label: name, ref: "HEAD", head: true}, nil, nil) -} - -func (g *gitPanel) treeRow(gtx C, th *ui.Theme, row gitTreeRow, open bool, in gitPanelInput) D { - if row.folder != "" { - return g.folderRow(gtx, th, row, open) - } - if row.group { - return layout.Inset{Left: ui.Space(2.5), Top: ui.Space(2), Bottom: ui.Space(0.5)}.Layout(gtx, - th.Text(ui.Text2XS, strings.ToUpper(row.label)).Muted().Weight(font.SemiBold).Layout) - } - var session *sessionView - if sv, ok := in.sessions[row.branch]; ok && row.branch != "" { - session = &sv +// fieldEvents closes the panel on Escape and reports Enter. +func (k *gitPicker) fieldEvents(gtx C) (submit bool) { + for { + ev, ok := gtx.Event(key.Filter{Focus: &k.field, Name: key.NameEscape}) + if !ok { + break + } + if e, ok := ev.(key.Event); ok && e.State == key.Press { + k.panel.Close() + } } - r := gitRow(g.treeRows, row.ref) - entries := func() []ui.MenuEntry { return g.branchEntries(row, in) } - if e := g.editing; e == nil || !e.create || e.from.ref != row.ref { - return g.refRow(gtx, th, r, row, session, entries) + for { + ev, ok := k.field.Update(gtx) + if !ok { + return submit + } + if _, ok := ev.(widget.SubmitEvent); ok { + submit = true + } } - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { return g.refRow(gtx, th, r, row, session, entries) }), - layout.Rigid(func(gtx C) D { return g.newBranchRow(gtx, th) }), - ) } -// folderRow is a folder of branches, its chevron and how many it holds; a -// click opens or shuts it. -func (g *gitPanel) folderRow(gtx C, th *ui.Theme, row gitTreeRow, open bool) D { - r := gitRow(g.treeRows, "folder:"+row.folder) - for r.click.Clicked(gtx) { - g.folders[row.folder] = !open - } - ic := icChevronRight - if open { - ic = icChevronDown +// pickRef goes to a ref: its checkout here, the session on it, or a tag's +// history. A branch another worktree holds with no session on it has nowhere +// to go. +func (g *gitPanel) pickRef(row gitRefRow, in gitPanelInput) { + sv, hasSession := in.sessions[row.branch] + hasSession = hasSession && row.branch != "" + switch act := gitBranchMenu(row, hasSession)[0].act; { + case act == gitActCheckout, act == gitActCheckoutRemote, act == gitActOpenSession, act == gitActHistory: + g.doBranch(act, row, sv, in) + case row.head: + g.picker.panel.Close() } - return r.click.Layout(gtx, func(gtx C) D { - gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, gtx.Dp(gitRowHeight))) - rowFill(gtx, th, false, r.click.Hovered()) - return layout.Inset{Left: ui.Space(1.5), Right: ui.Space(1.5)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { return ic.Layout(gtx, ui.Space(3), th.MutedForeground) }), - ui.Gap(1.5), - layout.Rigid(th.Text(ui.TextXS, gitCleanLine(row.label)).Muted().Layout), - ui.Gap(1.5), - layout.Rigid(th.Text(ui.TextXS, strconv.Itoa(row.count)).Mono().Muted().Layout), - ) - }) - }) } -const shortHashLen = 8 - -// refRow is a selectable ref: choosing it narrows the log, and choosing it -// again goes back to every branch. -func (g *gitPanel) refRow(gtx C, th *ui.Theme, r *gitRowState, row gitTreeRow, session *sessionView, entries func() []ui.MenuEntry) D { - if entries == nil { - return g.refRowBody(gtx, th, r, row, session, nil) - } - more := func(gtx C) D { - return th.DropdownMenu(g.root, &r.menu, entries()).Layout(gtx, func(gtx C) D { - return th.Tooltip(g.root, &r.moreTip, i18n.T("git.branch.options", i18n.Args{"name": row.name})).Layout(gtx, func(gtx C) D { - return th.CornerButton(&r.more, icGroupMore, r.menu.Opened()).Layout(gtx) - }) - }) - } - if r.menu.Opened() || r.context.Opened() { - g.menuOpen = true - } - return th.ContextMenuLazy(g.root, &r.context, entries).Layout(gtx, func(gtx C) D { - return g.refRowBody(gtx, th, r, row, session, more) +// createHere starts a branch at HEAD and goes to it, asking first when a +// session works in the checkout. +func (g *gitPanel) createHere(name string, in gitPanelInput) { + g.picker.panel.Close() + row := gitRefRow{ref: "refs/heads/" + name, branch: name, name: name} + g.runBranchOp(i18n.T("git.branch.createFailed", i18n.Args{"name": name}), func(ctx context.Context, c *backend.Client, path string) error { + return c.For(path).GitCreateBranch(ctx, path, name, "HEAD", api.GitUpstream{}) + }, func() { + if in.here == nil { + g.checkout(row) + return + } + g.mu.Lock() + g.asked = &gitConfirm{row: row, session: in.here.Label} + g.mu.Unlock() + g.invalidate() }) } -// narrowTo takes the row's clicks: the log narrows to its ref, or back to -// every branch when it already was. -func (g *gitPanel) narrowTo(gtx C, r *gitRowState, row gitTreeRow, renaming bool) { +// pickerRow is a ref, or the group that unfolds more of them; lit is the one +// Enter takes. +func (g *gitPanel) pickerRow(gtx C, th *ui.Theme, row gitRefRow, lit bool, in gitPanelInput) D { + if row.group != "" { + return g.groupRow(gtx, th, row) + } + r := gitRow(g.picker.rows, row.ref) + entries := func() []ui.MenuEntry { return g.branchEntries(row, in) } + menu := r.menu.Opened() || r.context.Opened() + g.menuOpen = g.menuOpen || menu + renaming := g.editing != nil && !g.editing.create && g.editing.from.ref == row.ref for r.click.Clicked(gtx) { // The ⋯ sits inside the row, so its click reaches the row too. - if renaming || r.more.Hovered() { - continue - } - if g.filter.ref == row.ref { - g.filter.ref = "" - } else { - g.filter.ref = row.ref + if !renaming && !r.more.Hovered() { + g.pickRef(row, in) } } + pr := th.PopoverRow(&r.click, func(gtx C, on *ui.Theme) D { + return g.refLine(gtx, on, r, row, renaming, in, func(gtx C) D { + return on.DropdownMenu(g.root, &r.menu, entries()).Layout(gtx, func(gtx C) D { + return on.Tooltip(g.root, &r.moreTip, i18n.T("git.branch.options", i18n.Args{"name": row.name})).Layout(gtx, func(gtx C) D { + return on.CornerButton(&r.more, icGroupMore, r.menu.Opened()).Layout(gtx) + }) + }) + }) + }) + pr.Lit = lit || menu + line := func(gtx C) D { return th.ContextMenuLazy(g.root, &r.context, entries).Layout(gtx, pr.Layout) } + if e := g.editing; e == nil || !e.create || e.from.ref != row.ref { + return line(gtx) + } + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Rigid(line), + layout.Rigid(func(gtx C) D { return g.newBranchRow(gtx, th) }), + ) } -// refRowBody is the row itself: its glyph, its name or the field renaming it, -// the ring of a session on it and, under the pointer, the ⋯ of its menu. -func (g *gitPanel) refRowBody(gtx C, th *ui.Theme, r *gitRowState, row gitTreeRow, session *sessionView, more layout.Widget) D { - renaming := g.editing != nil && !g.editing.create && g.editing.from.ref == row.ref - g.narrowTo(gtx, r, row, renaming) - return r.click.Layout(gtx, func(gtx C) D { - size := image.Pt(gtx.Constraints.Max.X, gtx.Dp(gitRowHeight)) - gtx.Constraints = layout.Exact(size) - hovered := r.click.Hovered() || r.menu.Opened() || r.context.Opened() - rowFill(gtx, th, g.filter.ref == row.ref, hovered) - ic := icBranch - if row.tag { - ic = icGitTag - } - tone := th.MutedForeground - l := th.Text(ui.TextXS, gitCleanLine(row.label)) - if row.head { - tone = th.Foreground - l = l.Weight(font.Medium) - } - left := ui.Space(1.5) - if row.parent != "" { - left += gitFolderIndent - } - return layout.Inset{Left: left, Right: ui.Space(1.5)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { return ic.Layout(gtx, ui.Space(3), tone) }), - ui.Gap(1.5), - layout.Flexed(1, func(gtx C) D { - if renaming { - return g.renameField(gtx, th) - } - return l.Truncated().Layout(gtx) - }), +// refLine is a row's name, or the field renaming it, what holds the branch +// elsewhere, and the check of the one HEAD is on, which gives way to more +// under the pointer. +func (g *gitPanel) refLine(gtx C, th *ui.Theme, r *gitRowState, row gitRefRow, renaming bool, in gitPanelInput, more layout.Widget) D { + note := "" + if sv, ok := in.sessions[row.branch]; ok && row.branch != "" && !row.head { + note = sv.Label + } else if row.worktree != "" && !row.head { + note = i18n.T("git.branch.inWorktree") + } + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Flexed(1, func(gtx C) D { + if renaming { + return g.renameField(gtx, th) + } + return layout.Flex{Alignment: layout.Middle, Spacing: layout.SpaceBetween}.Layout(gtx, + layout.Rigid(th.Text(ui.TextSM, gitCleanLine(row.name)).Truncated().Layout), layout.Rigid(func(gtx C) D { - if session == nil { + if note == "" { return D{} } - return g.sessionMark(gtx, th, r, *session) - }), - layout.Rigid(func(gtx C) D { - size := gtx.Dp(cardSlotSize) - if more == nil || !hovered { - return D{Size: image.Pt(0, size)} - } - gtx.Constraints = layout.Exact(image.Pt(size, size)) - return layout.Inset{Left: ui.Space(1)}.Layout(gtx, more) + return layout.Inset{Left: ui.Space(2)}.Layout(gtx, th.Text(ui.TextXS, gitCleanLine(note)).Muted().Truncated().Layout) }), ) - }) - }) + }), + ui.Gap(2), + layout.Rigid(func(gtx C) D { + side := gtx.Dp(gitPickerSlot) + gtx.Constraints = layout.Exact(image.Pt(side, side)) + switch { + case r.click.Hovered() || r.menu.Opened() || r.context.Opened(): + return more(gtx) + case row.head: + return icCheck.Layout(gtx, gitPickerSlot, th.Foreground) + } + return D{Size: image.Pt(side, side)} + }), + ) +} + +func (g *gitPanel) groupRow(gtx C, th *ui.Theme, row gitRefRow) D { + k := &g.picker + r := gitRow(k.rows, "group:"+row.group) + for r.click.Clicked(gtx) { + k.groups[row.group] = !k.groups[row.group] + gtx.Execute(op.InvalidateCmd{}) + } + label, ic := i18n.T("git.panel.remoteBranches"), icChevronRight + if row.group == gitGroupTags { + label = i18n.T("git.panel.tags") + } + if k.groups[row.group] || k.field.Len() > 0 { + ic = icChevronDown + } + return layout.Inset{Top: ui.Space(2)}.Layout(gtx, th.PopoverRow(&r.click, func(gtx C, on *ui.Theme) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(on.Text(ui.TextSM, label).Muted().Layout), + ui.Gap(1.5), + layout.Flexed(1, on.Text(ui.TextXS, strconv.Itoa(row.count)).Muted().Layout), + layout.Rigid(func(gtx C) D { return ic.Layout(gtx, gitPickerSlot, on.MutedForeground) }), + ) + }).Layout) } diff --git a/native/cmd/lich-native/git_refs_test.go b/native/cmd/lich-native/git_refs_test.go index 81ce8b5e1..5b0f85833 100644 --- a/native/cmd/lich-native/git_refs_test.go +++ b/native/cmd/lich-native/git_refs_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" + "github.com/lichdotdev/lich/api" "github.com/lichdotdev/lich/native/backend" "github.com/lichdotdev/lich/native/ui" ) @@ -37,26 +38,85 @@ func gitRefsBackend(t *testing.T) *backend.Client { return backend.New(backend.Runtime{Port: port, Token: "tok"}) } -func TestBranchMenuButtonOpensTheMenuWithoutSelectingTheBranch(t *testing.T) { - r := newFrameRig(image.Pt(1200, 400), nil) +// gitPickerRig is the panel with its branches open over a checkout on main, a +// session working in it when here is set. +func gitPickerRig(t *testing.T, client *backend.Client, here *sessionView) (*frameRig, *gitPanel) { + t.Helper() + r := newFrameRig(image.Pt(1200, 800), nil) var root ui.Root - g := newGitPanel(t.Context(), gitRefsBackend(t), &root, r.invalidate, func(ui.Toast) {}, "monospace", 12) + g := newGitPanel(t.Context(), client, &root, r.invalidate, func(ui.Toast) {}, "monospace", 12) + in := gitPanelInput{path: "/repo", here: here, cur: backend.DiffStats{Branch: "main", Upstream: "origin/main"}} r.draw = func(gtx C, th *ui.Theme) { root.Layout(gtx, func(gtx C) D { - g.layout(gtx, th, gitPanelInput{path: "/repo"}) + g.layout(gtx, th, in) + g.layoutDialogs(gtx, th) return D{Size: gtx.Constraints.Max} }) } + r.waitFor(t, "first") + r.pressLabel(t, "main") r.waitFor(t, "feature") + return r, g +} + +func TestBranchMenuButtonOpensTheMenuWithoutGoingToTheBranch(t *testing.T) { + b := &gitWorkBackend{} + r, g := gitPickerRig(t, b.client(t), nil) row := r.at(t, "feature") r.hover(row) more := r.smallestClickIn(t, image.Rect(int(row.X), int(row.Y)-rowReach, r.size.X, int(row.Y)+rowReach)) r.queueClick(more) r.frame() - if !g.treeRows["refs/heads/feature"].menu.Opened() { + if !g.picker.rows["refs/heads/feature"].menu.Opened() { t.Fatal("the click missed the branch's menu button") } - if g.filter.ref != "" { - t.Errorf("the menu button narrowed the log to %q", g.filter.ref) + r.waitFor(t, "Show its history") + if n := b.called("project.GitCheckout"); n != 0 { + t.Errorf("the menu button checked the branch out") + } + r.queueClick(r.glyphAt(t, "Show its history")) + r.settle(t) + if g.filter.ref != "refs/heads/feature" || g.picker.panel.Opened() { + t.Errorf("log narrowed to %q, panel open %v; want feature and shut", g.filter.ref, g.picker.panel.Opened()) + } +} + +func TestPickingABranchChecksItOut(t *testing.T) { + b := &gitWorkBackend{} + r, g := gitPickerRig(t, b.client(t), nil) + r.queueClick(r.at(t, "feature")) + r.frame() + var got api.GitCheckoutOptions + b.asked(t, "project.GitCheckout", &got) + if got.Branch != "feature" || g.picker.panel.Opened() { + t.Fatalf("checked out %+v, panel open %v", got, g.picker.panel.Opened()) + } +} + +func TestPickingABranchUnderASessionAsksFirst(t *testing.T) { + b := &gitWorkBackend{} + here := &sessionView{} + here.ID, here.Label = "s1", "Refine the panel" + r, _ := gitPickerRig(t, b.client(t), here) + r.queueClick(r.at(t, "feature")) + r.waitFor(t, "Switch Refine the panel to feature?") + if n := b.called("project.GitCheckout"); n != 0 { + t.Fatal("switched the branch under a session without asking") + } +} + +func TestANameNoBranchHasMakesItAndGoesToIt(t *testing.T) { + b := &gitWorkBackend{} + r, g := gitPickerRig(t, b.client(t), nil) + g.picker.field.SetText("fix/new") + r.waitFor(t, "Create fix/new") + r.queueClick(r.at(t, "Create fix/new")) + r.frame() + var made api.GitCreateBranchOptions + b.asked(t, "project.GitCreateBranch", &made) + var went api.GitCheckoutOptions + b.asked(t, "project.GitCheckout", &went) + if made.Name != "fix/new" || made.From != "HEAD" || went.Branch != "fix/new" { + t.Fatalf("made %+v, went to %+v", made, went) } } diff --git a/native/cmd/lich-native/git_store.go b/native/cmd/lich-native/git_store.go index c4095575a..c523da28e 100644 --- a/native/cmd/lich-native/git_store.go +++ b/native/cmd/lich-native/git_store.go @@ -276,7 +276,12 @@ func (s *gitStore) authorsOf(view gitLogView) []string { return gitTopAuthors(read.val) } +// fileDiff is the diff k is in: a commit's holds the one file, the work tree's +// every file, so choosing another of them reads nothing. func (s *gitStore) fileDiff(path string, k gitDiffKey) gitLoaded[string] { + if k.hash == "" { + k.file, k.oldFile = "", "" + } return gitFetch(s, &s.diff, path+"\x00"+k.hash+"\x00"+k.file+"\x00"+k.oldFile+"\x00"+k.stamp, func(ctx context.Context) (string, error) { if k.hash == "" { return s.client.For(path).DiffText(ctx, path) diff --git a/native/cmd/lich-native/git_sync.go b/native/cmd/lich-native/git_sync.go index b4af69ef8..3862faafd 100644 --- a/native/cmd/lich-native/git_sync.go +++ b/native/cmd/lich-native/git_sync.go @@ -65,8 +65,12 @@ func (g *gitPanel) syncActions(gtx C, th *ui.Theme, in gitPanelInput) D { button := func(click *ui.Clickable, ic *icons.Icon, text string, op gitSyncOp, lead bool) ui.ButtonStyle { b := th.Button(click, text) b.Icon, b.Busy, b.Disabled = ic, running == op, !idle && running != op - if !lead { + switch { + case !lead: b.Variant = ui.VariantGhost + case in.cur.Files > 0: + // Commit is the view's filled button while there is something to commit. + b.Variant = ui.VariantOutline } return b } @@ -123,7 +127,7 @@ func (g *gitPanel) takeSyncClicks(gtx C, in gitPanelInput, idle, diverged bool) // changes files under its agent. func (g *gitPanel) askPull(in gitPanelInput) { if in.here != nil { - g.confirm = &gitConfirm{pull: true, row: gitTreeRow{name: in.cur.Branch}, session: in.here.Label} + g.confirm = &gitConfirm{pull: true, row: gitRefRow{name: in.cur.Branch}, session: in.here.Label} return } g.runSync(gitSyncPull, in.cur.Branch) diff --git a/native/cmd/lich-native/git_sync_test.go b/native/cmd/lich-native/git_sync_test.go index 6c37c2b7a..f11b47863 100644 --- a/native/cmd/lich-native/git_sync_test.go +++ b/native/cmd/lich-native/git_sync_test.go @@ -55,9 +55,7 @@ func gitSyncRig(t *testing.T, b *gitWorkBackend, cur backend.DiffStats, here *se return D{Size: gtx.Constraints.Max} }) } - // The panel opens on HEAD, whose detail it reads only once the log is in: - // the screen is still only once that answer is drawn, not the log. - r.waitFor(t, gitHeadMessage) + r.waitFor(t, "first") // the one commit of the log it opens on return r, g } @@ -122,3 +120,41 @@ func TestPublishOffersItselfWithNoUpstream(t *testing.T) { var got struct{ Path string } b.asked(t, "project.GitPublish", &got) } + +func TestACommitOpensBesideTheLogAndItsFileOverIt(t *testing.T) { + r, g := gitSyncRig(t, &gitWorkBackend{}, backend.DiffStats{Branch: "main"}, nil) + if r.shows(gitHeadMessage) { + t.Fatal("a commit is open that nobody clicked") + } + r.pressLabel(t, "first") + r.waitFor(t, gitHeadMessage) + r.pressLabel(t, "c.go") + r.settle(t) + if r.shows(gitHeadMessage) || !r.shows("first") { + t.Fatalf("want the file's diff in the commit's place, the log still there:\n%s", r.drawn()) + } + g.detail.closeFile() + r.waitFor(t, gitHeadMessage) + r.pressLabel(t, "first") + r.settle(t) + if r.shows(gitHeadMessage) { + t.Fatal("a second click on the commit left it open") + } +} + +func TestClearingTheFiltersDropsAllOfThem(t *testing.T) { + r, g := gitSyncRig(t, &gitWorkBackend{}, backend.DiffStats{Branch: "main"}, nil) + if r.shows("Author") { + t.Fatal("the filters show before they were asked for") + } + g.filter.ref, g.filterRef, g.filter.author = "refs/heads/main", "main", "me" + g.sinceDays, g.filter.since = 7, 1 + g.file.SetText("pkg/") + if !g.filtersSet() { + t.Fatal("filters set and not told") + } + g.clearFilters() + if g.filtersSet() || g.filter.narrowed() || g.filter.ref != "" { + t.Fatalf("left %+v", g.filter) + } +} diff --git a/native/i18n/locales/en/git.json b/native/i18n/locales/en/git.json index b1c34f483..2f102743e 100644 --- a/native/i18n/locales/en/git.json +++ b/native/i18n/locales/en/git.json @@ -28,11 +28,10 @@ "revert": "Revert" }, "panel": { - "title": "Git", "close": "Close the Git panel", - "searchPlaceholder": "Text or hash", + "searchPlaceholder": "Search commits", "pathPlaceholder": "Path", - "branchPlaceholder": "Branch or tag", + "branchPlaceholder": "Find or create a branch", "author": "Author", "authorAny": "All authors", "date": "Date", @@ -40,17 +39,18 @@ "dateDay": "Last 24 hours", "dateWeek": "Last 7 days", "dateMonth": "Last 30 days", - "local": "Local", "tags": "Tags", - "selectCommit": "Select a commit to see its files.", "noCommits": "No commits match.", "loadFailed": "Could not read the history: {error}", "commitFailed": "Could not read this commit: {error}", "diffFailed": "Could not read this diff: {error}", "binary": "This file is binary.", "noDiff": "Nothing changed in this file.", - "back": "Back to the log", - "files": "Files" + "back": "Back to the commit", + "history": "History", + "filter": "Filter", + "clearFilters": "Clear the filters", + "remoteBranches": "Remote branches" }, "branch": { "checkout": "Checkout", @@ -80,7 +80,9 @@ "createFailed": "Could not create {name}", "renameFailed": "Could not rename {name}", "deleteFailed": "Could not delete {name}", - "undoFailed": "Could not bring back {name}" + "undoFailed": "Could not bring back {name}", + "create": "Create {name}", + "history": "Show its history" }, "merge": { "merging": "Merging {source} into {branch}", @@ -144,9 +146,7 @@ } }, "commit": { - "uncommitted": "Uncommitted changes", "changes": "Changes", - "checked": "{checked} of {count}", "resolveFirst": "Resolve the conflict first", "checkFile": "Check a file to commit", "writeMessage": "Write a commit message", @@ -158,7 +158,14 @@ "commit": "Commit", "readPart": "Read the first {read} lines of {total}", "writeFailed": "Couldn't write the message: {error}", - "readFailed": "Couldn't read the changes: {error}" + "readFailed": "Couldn't read the changes: {error}", + "none": "No uncommitted changes.", + "all": "All", + "allFiles": "Check every file", + "commitFiles": { + "one": "Commit {count} file", + "other": "Commit {count} files" + } }, "sync": { "publish": "Publish", diff --git a/native/i18n/locales/es/git.json b/native/i18n/locales/es/git.json index 0c2d9e7b9..fa255d1ce 100644 --- a/native/i18n/locales/es/git.json +++ b/native/i18n/locales/es/git.json @@ -28,11 +28,10 @@ "revert": "Revertir" }, "panel": { - "title": "Git", "close": "Cerrar el panel de Git", - "searchPlaceholder": "Texto o hash", + "searchPlaceholder": "Buscar commits", "pathPlaceholder": "Ruta", - "branchPlaceholder": "Rama o etiqueta", + "branchPlaceholder": "Buscar o crear una rama", "author": "Autor", "authorAny": "Todos los autores", "date": "Fecha", @@ -40,17 +39,18 @@ "dateDay": "Últimas 24 horas", "dateWeek": "Últimos 7 días", "dateMonth": "Últimos 30 días", - "local": "Locales", "tags": "Etiquetas", - "selectCommit": "Selecciona un commit para ver sus archivos.", "noCommits": "Ningún commit coincide.", "loadFailed": "No se pudo leer el historial: {error}", "commitFailed": "No se pudo leer este commit: {error}", "diffFailed": "No se pudo leer este diff: {error}", "binary": "Este archivo es binario.", "noDiff": "Este archivo no tiene cambios.", - "back": "Volver al registro", - "files": "Archivos" + "back": "Volver al commit", + "history": "Historial", + "filter": "Filtrar", + "clearFilters": "Quitar los filtros", + "remoteBranches": "Ramas remotas" }, "branch": { "checkout": "Checkout", @@ -80,7 +80,9 @@ "createFailed": "No se pudo crear {name}", "renameFailed": "No se pudo renombrar {name}", "deleteFailed": "No se pudo eliminar {name}", - "undoFailed": "No se pudo recuperar {name}" + "undoFailed": "No se pudo recuperar {name}", + "create": "Crear {name}", + "history": "Ver su historial" }, "merge": { "merging": "Fusionando {source} en {branch}", @@ -144,9 +146,7 @@ } }, "commit": { - "uncommitted": "Cambios sin commit", "changes": "Cambios", - "checked": "{checked} de {count}", "resolveFirst": "Resuelve el conflicto primero", "checkFile": "Marca un archivo para hacer commit", "writeMessage": "Escribe el mensaje del commit", @@ -158,7 +158,14 @@ "commit": "Commit", "readPart": "Leyó las primeras {read} líneas de {total}", "writeFailed": "No se pudo escribir el mensaje: {error}", - "readFailed": "No se pudieron leer los cambios: {error}" + "readFailed": "No se pudieron leer los cambios: {error}", + "none": "No hay cambios sin commit.", + "all": "Todos", + "allFiles": "Marcar todos los archivos", + "commitFiles": { + "one": "Hacer commit de {count} archivo", + "other": "Hacer commit de {count} archivos" + } }, "sync": { "publish": "Publicar", diff --git a/native/i18n/locales/ja/git.json b/native/i18n/locales/ja/git.json index 404ca8eb1..c229f544c 100644 --- a/native/i18n/locales/ja/git.json +++ b/native/i18n/locales/ja/git.json @@ -28,11 +28,10 @@ "revert": "元に戻す" }, "panel": { - "title": "Git", "close": "Git パネルを閉じる", - "searchPlaceholder": "テキストまたはハッシュ", + "searchPlaceholder": "コミットを検索", "pathPlaceholder": "パス", - "branchPlaceholder": "ブランチまたはタグ", + "branchPlaceholder": "ブランチを検索または作成", "author": "作成者", "authorAny": "すべての作成者", "date": "日付", @@ -40,17 +39,18 @@ "dateDay": "過去 24 時間", "dateWeek": "過去 7 日間", "dateMonth": "過去 30 日間", - "local": "ローカル", "tags": "タグ", - "selectCommit": "コミットを選択するとファイルが表示されます。", "noCommits": "一致するコミットはありません。", "loadFailed": "履歴を読み取れませんでした: {error}", "commitFailed": "このコミットを読み取れませんでした: {error}", "diffFailed": "この差分を読み取れませんでした: {error}", "binary": "このファイルはバイナリです。", "noDiff": "このファイルに変更はありません。", - "back": "ログに戻る", - "files": "ファイル" + "back": "コミットに戻る", + "history": "履歴", + "filter": "絞り込み", + "clearFilters": "絞り込みを解除", + "remoteBranches": "リモートブランチ" }, "branch": { "checkout": "チェックアウト", @@ -80,7 +80,9 @@ "createFailed": "{name} を作成できませんでした", "renameFailed": "{name} の名前を変更できませんでした", "deleteFailed": "{name} を削除できませんでした", - "undoFailed": "{name} を復元できませんでした" + "undoFailed": "{name} を復元できませんでした", + "create": "{name} を作成", + "history": "履歴を表示" }, "merge": { "merging": "{source} を {branch} にマージ中", @@ -144,9 +146,7 @@ } }, "commit": { - "uncommitted": "未コミットの変更", "changes": "変更", - "checked": "{count} 件中 {checked} 件", "resolveFirst": "先にコンフリクトを解消してください", "checkFile": "コミットするファイルにチェックを入れてください", "writeMessage": "コミットメッセージを入力してください", @@ -158,7 +158,14 @@ "commit": "コミット", "readPart": "{total} 行のうち最初の {read} 行を読みました", "writeFailed": "メッセージを作成できませんでした: {error}", - "readFailed": "変更を読み取れませんでした: {error}" + "readFailed": "変更を読み取れませんでした: {error}", + "none": "未コミットの変更はありません。", + "all": "すべて", + "allFiles": "すべてのファイルを選択", + "commitFiles": { + "one": "{count} 個のファイルをコミット", + "other": "{count} 個のファイルをコミット" + } }, "sync": { "publish": "公開", diff --git a/native/i18n/locales/ko/git.json b/native/i18n/locales/ko/git.json index 00127a3d1..5e2fec56a 100644 --- a/native/i18n/locales/ko/git.json +++ b/native/i18n/locales/ko/git.json @@ -24,11 +24,10 @@ "revert": "되돌리기" }, "panel": { - "title": "Git", "close": "Git 패널 닫기", - "searchPlaceholder": "텍스트 또는 해시", + "searchPlaceholder": "커밋 검색", "pathPlaceholder": "경로", - "branchPlaceholder": "브랜치 또는 태그", + "branchPlaceholder": "브랜치 찾기 또는 만들기", "author": "작성자", "authorAny": "모든 작성자", "date": "날짜", @@ -36,17 +35,18 @@ "dateDay": "최근 24시간", "dateWeek": "최근 7일", "dateMonth": "최근 30일", - "local": "로컬", "tags": "태그", - "selectCommit": "커밋을 선택하면 파일이 표시됩니다.", "noCommits": "일치하는 커밋이 없습니다.", "loadFailed": "기록을 읽을 수 없습니다: {error}", "commitFailed": "이 커밋을 읽을 수 없습니다: {error}", "diffFailed": "이 diff를 읽을 수 없습니다: {error}", "binary": "이 파일은 바이너리입니다.", "noDiff": "이 파일에는 변경 사항이 없습니다.", - "back": "로그로 돌아가기", - "files": "파일" + "back": "커밋으로 돌아가기", + "history": "기록", + "filter": "필터", + "clearFilters": "필터 지우기", + "remoteBranches": "원격 브랜치" }, "branch": { "checkout": "체크아웃", @@ -76,7 +76,9 @@ "createFailed": "{name} 브랜치를 만들지 못했습니다", "renameFailed": "{name} 브랜치 이름을 바꾸지 못했습니다", "deleteFailed": "{name} 브랜치를 삭제하지 못했습니다", - "undoFailed": "{name} 브랜치를 되살리지 못했습니다" + "undoFailed": "{name} 브랜치를 되살리지 못했습니다", + "create": "{name} 만들기", + "history": "기록 보기" }, "merge": { "merging": "{source}을(를) {branch}에 병합 중", @@ -140,9 +142,7 @@ } }, "commit": { - "uncommitted": "커밋하지 않은 변경", "changes": "변경", - "checked": "{count}개 중 {checked}개", "resolveFirst": "먼저 충돌을 해결하세요", "checkFile": "커밋할 파일을 선택하세요", "writeMessage": "커밋 메시지를 입력하세요", @@ -154,7 +154,13 @@ "commit": "커밋", "readPart": "{total}줄 중 처음 {read}줄을 읽었습니다", "writeFailed": "메시지를 작성할 수 없습니다: {error}", - "readFailed": "변경을 읽을 수 없습니다: {error}" + "readFailed": "변경을 읽을 수 없습니다: {error}", + "none": "커밋하지 않은 변경 사항이 없습니다.", + "all": "모두", + "allFiles": "모든 파일 선택", + "commitFiles": { + "other": "파일 {count}개 커밋" + } }, "sync": { "publish": "게시", diff --git a/native/i18n/locales/pt-br/git.json b/native/i18n/locales/pt-br/git.json index 5d2240798..4dafd7d1e 100644 --- a/native/i18n/locales/pt-br/git.json +++ b/native/i18n/locales/pt-br/git.json @@ -28,11 +28,10 @@ "revert": "Reverter" }, "panel": { - "title": "Git", "close": "Fechar o painel Git", - "searchPlaceholder": "Texto ou hash", + "searchPlaceholder": "Buscar commits", "pathPlaceholder": "Caminho", - "branchPlaceholder": "Branch ou tag", + "branchPlaceholder": "Buscar ou criar uma branch", "author": "Autor", "authorAny": "Todos os autores", "date": "Data", @@ -40,17 +39,18 @@ "dateDay": "Últimas 24 horas", "dateWeek": "Últimos 7 dias", "dateMonth": "Últimos 30 dias", - "local": "Locais", "tags": "Tags", - "selectCommit": "Selecione um commit para ver os arquivos.", "noCommits": "Nenhum commit encontrado.", "loadFailed": "Não foi possível ler o histórico: {error}", "commitFailed": "Não foi possível ler este commit: {error}", "diffFailed": "Não foi possível ler este diff: {error}", "binary": "Este arquivo é binário.", "noDiff": "Nada mudou neste arquivo.", - "back": "Voltar ao log", - "files": "Arquivos" + "back": "Voltar ao commit", + "history": "Histórico", + "filter": "Filtrar", + "clearFilters": "Limpar os filtros", + "remoteBranches": "Branches remotas" }, "branch": { "checkout": "Checkout", @@ -80,7 +80,9 @@ "createFailed": "Não foi possível criar {name}", "renameFailed": "Não foi possível renomear {name}", "deleteFailed": "Não foi possível excluir {name}", - "undoFailed": "Não foi possível trazer {name} de volta" + "undoFailed": "Não foi possível trazer {name} de volta", + "create": "Criar {name}", + "history": "Ver o histórico dela" }, "merge": { "merging": "Fazendo merge de {source} em {branch}", @@ -144,9 +146,7 @@ } }, "commit": { - "uncommitted": "Mudanças sem commit", "changes": "Mudanças", - "checked": "{checked} de {count}", "resolveFirst": "Resolva o conflito primeiro", "checkFile": "Marque um arquivo para fazer o commit", "writeMessage": "Escreva a mensagem do commit", @@ -158,7 +158,14 @@ "commit": "Commit", "readPart": "Leu as primeiras {read} linhas de {total}", "writeFailed": "Não foi possível escrever a mensagem: {error}", - "readFailed": "Não foi possível ler as mudanças: {error}" + "readFailed": "Não foi possível ler as mudanças: {error}", + "none": "Nenhuma mudança sem commit.", + "all": "Todos", + "allFiles": "Marcar todos os arquivos", + "commitFiles": { + "one": "Commitar {count} arquivo", + "other": "Commitar {count} arquivos" + } }, "sync": { "publish": "Publicar", diff --git a/native/i18n/locales/ru/git.json b/native/i18n/locales/ru/git.json index 59a355037..c5cf53377 100644 --- a/native/i18n/locales/ru/git.json +++ b/native/i18n/locales/ru/git.json @@ -36,11 +36,10 @@ "revert": "Откатить" }, "panel": { - "title": "Git", "close": "Закрыть панель Git", - "searchPlaceholder": "Текст или хеш", + "searchPlaceholder": "Поиск коммитов", "pathPlaceholder": "Путь", - "branchPlaceholder": "Ветка или тег", + "branchPlaceholder": "Найти или создать ветку", "author": "Автор", "authorAny": "Все авторы", "date": "Дата", @@ -48,17 +47,18 @@ "dateDay": "За 24 часа", "dateWeek": "За 7 дней", "dateMonth": "За 30 дней", - "local": "Локальные", "tags": "Теги", - "selectCommit": "Выберите коммит, чтобы увидеть его файлы.", "noCommits": "Подходящих коммитов нет.", "loadFailed": "Не удалось прочитать историю: {error}", "commitFailed": "Не удалось прочитать этот коммит: {error}", "diffFailed": "Не удалось прочитать этот diff: {error}", "binary": "Это двоичный файл.", "noDiff": "В этом файле нет изменений.", - "back": "Назад к журналу", - "files": "Файлы" + "back": "Назад к коммиту", + "history": "История", + "filter": "Фильтр", + "clearFilters": "Сбросить фильтры", + "remoteBranches": "Удалённые ветки" }, "branch": { "checkout": "Переключиться", @@ -92,7 +92,9 @@ "createFailed": "Не удалось создать {name}", "renameFailed": "Не удалось переименовать {name}", "deleteFailed": "Не удалось удалить {name}", - "undoFailed": "Не удалось вернуть {name}" + "undoFailed": "Не удалось вернуть {name}", + "create": "Создать {name}", + "history": "Показать историю" }, "merge": { "merging": "Слияние {source} в {branch}", @@ -168,9 +170,7 @@ } }, "commit": { - "uncommitted": "Незакоммиченные изменения", "changes": "Изменения", - "checked": "{checked} из {count}", "resolveFirst": "Сначала разрешите конфликт", "checkFile": "Отметьте файл для коммита", "writeMessage": "Напишите сообщение коммита", @@ -182,7 +182,16 @@ "commit": "Коммит", "readPart": "Прочитаны первые {read} строк из {total}", "writeFailed": "Не удалось написать сообщение: {error}", - "readFailed": "Не удалось прочитать изменения: {error}" + "readFailed": "Не удалось прочитать изменения: {error}", + "none": "Незакоммиченных изменений нет.", + "all": "Все", + "allFiles": "Отметить все файлы", + "commitFiles": { + "one": "Закоммитить {count} файл", + "few": "Закоммитить {count} файла", + "many": "Закоммитить {count} файлов", + "other": "Закоммитить {count} файла" + } }, "sync": { "publish": "Опубликовать", diff --git a/native/i18n/locales/zh-cn/git.json b/native/i18n/locales/zh-cn/git.json index 61934c75c..9e6d4d848 100644 --- a/native/i18n/locales/zh-cn/git.json +++ b/native/i18n/locales/zh-cn/git.json @@ -28,11 +28,10 @@ "revert": "还原" }, "panel": { - "title": "Git", "close": "关闭 Git 面板", - "searchPlaceholder": "文本或哈希", + "searchPlaceholder": "搜索提交", "pathPlaceholder": "路径", - "branchPlaceholder": "分支或标签", + "branchPlaceholder": "查找或新建分支", "author": "作者", "authorAny": "所有作者", "date": "日期", @@ -40,17 +39,18 @@ "dateDay": "最近 24 小时", "dateWeek": "最近 7 天", "dateMonth": "最近 30 天", - "local": "本地", "tags": "标签", - "selectCommit": "选择一个提交以查看其文件。", "noCommits": "没有匹配的提交。", "loadFailed": "无法读取历史记录:{error}", "commitFailed": "无法读取此提交:{error}", "diffFailed": "无法读取此差异:{error}", "binary": "此文件是二进制文件。", "noDiff": "此文件没有更改。", - "back": "返回日志", - "files": "文件" + "back": "返回提交", + "history": "历史", + "filter": "筛选", + "clearFilters": "清除筛选", + "remoteBranches": "远程分支" }, "branch": { "checkout": "检出", @@ -80,7 +80,9 @@ "createFailed": "无法创建 {name}", "renameFailed": "无法重命名 {name}", "deleteFailed": "无法删除 {name}", - "undoFailed": "无法恢复 {name}" + "undoFailed": "无法恢复 {name}", + "create": "新建 {name}", + "history": "查看其历史" }, "merge": { "merging": "正在将 {source} 合并到 {branch}", @@ -144,9 +146,7 @@ } }, "commit": { - "uncommitted": "未提交的更改", "changes": "更改", - "checked": "{checked}/{count}", "resolveFirst": "请先解决冲突", "checkFile": "勾选要提交的文件", "writeMessage": "请填写提交信息", @@ -158,7 +158,14 @@ "commit": "提交", "readPart": "已读取 {total} 行中的前 {read} 行", "writeFailed": "无法撰写提交信息:{error}", - "readFailed": "无法读取更改:{error}" + "readFailed": "无法读取更改:{error}", + "none": "没有未提交的更改。", + "all": "全部", + "allFiles": "勾选所有文件", + "commitFiles": { + "one": "提交 {count} 个文件", + "other": "提交 {count} 个文件" + } }, "sync": { "publish": "发布",