From c0cfab70154eebcb285d2c2f8d4691990486fcac Mon Sep 17 00:00:00 2001 From: omartelo Date: Fri, 4 Dec 2026 00:18:00 -0300 Subject: [PATCH 1/2] Read a finished job's whole log --- api/checklog.go | 28 ++++++ api/project.go | 3 + api/testdata/contract.golden | 19 ++++ internal/project/forge.go | 2 + internal/project/gitlabchecks.go | 14 ++- internal/project/joblog.go | 167 +++++++++++++++++++++++++++++++ internal/project/joblog_test.go | 148 +++++++++++++++++++++++++++ internal/project/prchecks.go | 6 +- internal/routes/project.go | 1 + native/backend/pulls.go | 8 ++ 10 files changed, 391 insertions(+), 5 deletions(-) create mode 100644 internal/project/joblog.go create mode 100644 internal/project/joblog_test.go diff --git a/api/checklog.go b/api/checklog.go index faebefd5e..bcaa726d8 100644 --- a/api/checklog.go +++ b/api/checklog.go @@ -43,3 +43,31 @@ type StepLog struct { Lines []string `json:"lines"` Cut int `json:"cut,omitempty"` } + +// ProjectJobLog reads the whole log of one finished job of a pull request, the +// check of a CheckItem with HasLog. +var ProjectJobLog = define[JobLogOptions, JobLog]("project.JobLog") + +// JobLogOptions names the job by its check's URL, read with the account of the +// checkout at Path. +type JobLogOptions struct { + Path string `json:"path"` + URL string `json:"url"` +} + +// JobLog is a job's log by step, in the order they ran, a skipped one left +// out. A GitLab job's is one step with no name. +type JobLog struct { + Steps []JobStep `json:"steps"` +} + +// JobStep is one step of a job and what it printed, without timestamps or +// terminal escapes; the runner's own markers ("##[error]", "##[group]") stay. +// State is passed or failed, "" for a step with no name. +type JobStep struct { + Name string `json:"name"` + State string `json:"state"` + StartedAt string `json:"startedAt"` + CompletedAt string `json:"completedAt"` + Lines []string `json:"lines"` +} diff --git a/api/project.go b/api/project.go index d7f65fcaa..16c662325 100644 --- a/api/project.go +++ b/api/project.go @@ -766,6 +766,9 @@ type CheckItem struct { // Required is GitHub's own answer to "does this check gate the merge", the // same verdict its checks list labels Required. Required bool `json:"required"` + // HasLog is a finished job whose log ProjectJobLog reads; any other check + // is read at URL alone. + HasLog bool `json:"hasLog"` } // ReviewComment is one line comment of a review being submitted. Line is the diff --git a/api/testdata/contract.golden b/api/testdata/contract.golden index d119ccdd1..1629e8436 100644 --- a/api/testdata/contract.golden +++ b/api/testdata/contract.golden @@ -198,6 +198,7 @@ project.GitWriteMessage(GitWriteMessageOptions) GitWrittenMessage project.GlobalCommitIdentity(None) CommitIdentity project.Home(None) *OpenedProject project.Issue(NumberOptions) Issue +project.JobLog(JobLogOptions) JobLog project.LinkPullRequest(LinkPullRequestOptions) None project.ListBranches(PathOptions) Branches project.ListCheckouts(PathOptions) []Worktree @@ -1430,6 +1431,15 @@ Issue { url string } +JobLogOptions { + path string + url string +} + +JobLog { + steps []JobStep +} + LinkPullRequestOptions { session string path string @@ -3241,6 +3251,14 @@ GitCommit { head,omitempty bool } +JobStep { + name string + state string + startedAt string + completedAt string + lines []string +} + ChecksRollup { passed int failed int @@ -3299,6 +3317,7 @@ CheckItem { startedAt string completedAt string required bool + hasLog bool } PRCommit { diff --git a/internal/project/forge.go b/internal/project/forge.go index 659cd8e2e..877be4d4a 100644 --- a/internal/project/forge.go +++ b/internal/project/forge.go @@ -36,6 +36,8 @@ type forge interface { // wtPath; accountDir names whose account the call runs as. checkoutPullRequest(accountDir, wtPath string, number int) error checkLog(dir string, lines int) (api.CheckLog, error) + // jobLog is the whole log of the job whose page a check's URL names. + jobLog(path, page string) (api.JobLog, error) } // Forge answers which forge opts.Path's remote points at. diff --git a/internal/project/gitlabchecks.go b/internal/project/gitlabchecks.go index b7c4c9579..0a0873ba2 100644 --- a/internal/project/gitlabchecks.go +++ b/internal/project/gitlabchecks.go @@ -94,7 +94,8 @@ func jobChecks(jobs []glabJob) (ChecksRollup, []CheckItem) { r.Pending++ } items = append(items, CheckItem{Name: j.Name, State: state, Description: j.Stage, URL: j.WebURL, - StartedAt: j.StartedAt, CompletedAt: j.FinishedAt, Required: !j.AllowFailure}) + StartedAt: j.StartedAt, CompletedAt: j.FinishedAt, Required: !j.AllowFailure, + HasLog: state != checkPending && j.StartedAt != "" && gitlabJobPage.MatchString(j.WebURL)}) } sort.SliceStable(items, func(i, k int) bool { return checkOrder[items[i].State] < checkOrder[items[k].State] }) return r, items @@ -155,6 +156,14 @@ var ( traceSection = regexp.MustCompile(`section_(start|end):\d+:([^\[\r\s]+)(?:\[[^\]]*\])?\r?(?:\x1b\[0K)?`) ) +// traceLine is a trace's line as the job printed it, and whether it carried a +// section marker of the runner's. +func traceLine(line string) (text string, marked bool) { + line = traceStamp.ReplaceAllString(line, "") + text = traceSection.ReplaceAllString(line, "") + return strings.TrimRight(terminalCode.ReplaceAllString(text, ""), "\r"), text != line +} + // traceSteps keeps the tail of the job's script section, or of the whole trace // when it has none (a job that failed setting up). func traceSteps(raw []byte, lines int) []api.StepLog { @@ -173,8 +182,7 @@ func traceSteps(raw []byte, lines int) []api.StepLog { sawScript = sawScript || inScript } } - line = traceSection.ReplaceAllString(line, "") - line = strings.TrimRight(terminalCode.ReplaceAllString(line, ""), "\r") + line, _ = traceLine(line) if line == "" && markers != nil { continue } diff --git a/internal/project/joblog.go b/internal/project/joblog.go new file mode 100644 index 000000000..a0de1fa87 --- /dev/null +++ b/internal/project/joblog.go @@ -0,0 +1,167 @@ +package project + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "regexp" + "strings" + "time" + + "github.com/lichdotdev/lich/api" +) + +var ( + // githubJobPage and gitlabJobPage take the repository and the job from a + // check's URL. Only these characters reach the endpoint built from them. + githubJobPage = regexp.MustCompile(`^https://[^/]+/([\w.-]+/[\w.-]+)/actions/runs/\d+/job/(\d+)`) + gitlabJobPage = regexp.MustCompile(`^https?://[^/]+/([\w./-]+)/-/jobs/(\d+)`) +) + +// stepOpeners are what the runner's first line of a step reads: a step of the +// workflow, an action's cleanup, and the job's own end. +var stepOpeners = []string{stepMarker, "Post job cleanup.", "Cleaning up orphan processes"} + +// JobLog reads the whole log of one finished job, the check at opts.URL. +func (s *Service) JobLog(_ context.Context, opts api.JobLogOptions) (api.JobLog, error) { + return s.forgeOf(opts.Path).jobLog(opts.Path, opts.URL) +} + +type githubJobStep struct { + Name string `json:"name"` + Conclusion string `json:"conclusion"` + StartedAt time.Time `json:"started_at"` + CompletedAt time.Time `json:"completed_at"` +} + +func (g githubForge) jobLog(path, page string) (api.JobLog, error) { + m := githubJobPage.FindStringSubmatch(page) + if m == nil { + return api.JobLog{}, fmt.Errorf("%q is not a GitHub Actions job", page) + } + endpoint := "repos/" + m[1] + "/actions/jobs/" + m[2] + out, err := g.s.gh(prReadTimeout, path, "api", endpoint) + if err != nil { + return api.JobLog{}, err + } + var job struct { + Steps []githubJobStep `json:"steps"` + } + if err := json.Unmarshal(out, &job); err != nil { + return api.JobLog{}, errUnreadableAnswer(err) + } + raw, err := g.rawJobLog(path, endpoint+"/logs") + if err != nil { + return api.JobLog{}, err + } + return api.JobLog{Steps: splitJobLog(raw, job.Steps)}, nil +} + +// rawJobLog downloads a job's log from the API, which serves it as soon as the +// job ends, where `gh run view --log` waits for its whole run. gh 2.102 refuses +// a response holding terminal escapes unless told to let it through, and an +// older gh does not know that flag; the escapes are dropped in splitJobLog. +func (g githubForge) rawJobLog(path, endpoint string) ([]byte, error) { + out, err := g.s.gh(checkLogTimeout, path, "api", "--allow-escape-sequences", endpoint) + if err != nil && strings.Contains(err.Error(), "unknown flag") { + return g.s.gh(checkLogTimeout, path, "api", endpoint) + } + return out, err +} + +// splitJobLog hands each line of a job's log to the step that wrote it. The log +// names no step, and a step's start is told to the second, so a line opens the +// next step when it is later than that second, or in it and reads as an opening. +func splitJobLog(raw []byte, steps []githubJobStep) []api.JobStep { + var out []api.JobStep + var starts []time.Time + for _, st := range steps { + if st.Conclusion == "skipped" { + continue + } + out = append(out, api.JobStep{Name: st.Name, State: stepState(st.Conclusion), + StartedAt: st.StartedAt.Format(time.RFC3339), CompletedAt: st.CompletedAt.Format(time.RFC3339)}) + starts = append(starts, st.StartedAt) + } + if len(out) == 0 { + out, starts = []api.JobStep{{}}, []time.Time{{}} + } + at := 0 + for line := range strings.SplitSeq(strings.TrimRight(string(raw), "\n"), "\n") { + stamp, text := splitStamp(line) + for at+1 < len(out) && opensStep(stamp, text, starts[at+1]) { + at++ + } + if text != "##[endgroup]" { + out[at].Lines = append(out[at].Lines, text) + } + } + return out +} + +func opensStep(stamp time.Time, text string, start time.Time) bool { + if stamp.IsZero() { + return false + } + second := stamp.Truncate(time.Second) + if second.After(start) { + return true + } + if second.Before(start) { + return false + } + for _, opener := range stepOpeners { + if strings.HasPrefix(text, opener) { + return true + } + } + return false +} + +// splitStamp reads a raw log line into its time, zero for a line that carries +// none, and its text. +func splitStamp(line string) (time.Time, string) { + line = strings.TrimPrefix(line, "\uFEFF") + stamp, text, _ := strings.Cut(line, " ") + at, err := time.Parse(time.RFC3339Nano, strings.TrimSuffix(stamp, "\r")) + if err != nil { + return time.Time{}, printed(line) + } + return at, printed(text) +} + +// printed is a line as a terminal leaves it: no escapes, and of a line a +// progress bar redrew over itself, the last drawing. +func printed(line string) string { + line = strings.TrimRight(terminalCode.ReplaceAllString(line, ""), "\r") + return line[strings.LastIndexByte(line, '\r')+1:] +} + +func stepState(conclusion string) string { + if isFailureConclusion(strings.ToUpper(conclusion)) { + return checkFailed + } + return checkPassed +} + +// jobLog is the job's trace with no steps: GitLab tells a job's sections apart +// only by the runner's own names for them. +func (g gitlabForge) jobLog(path, page string) (api.JobLog, error) { + m := gitlabJobPage.FindStringSubmatch(page) + if m == nil { + return api.JobLog{}, fmt.Errorf("%q is not a GitLab job", page) + } + raw, err := g.run(checkLogTimeout, path, "api", "projects/"+url.PathEscape(m[1])+"/jobs/"+m[2]+"/trace") + if err != nil { + return api.JobLog{}, err + } + step := api.JobStep{} + for line := range strings.SplitSeq(strings.TrimRight(string(raw), "\n"), "\n") { + text, marked := traceLine(line) + if text != "" || !marked { + step.Lines = append(step.Lines, printed(text)) + } + } + return api.JobLog{Steps: []api.JobStep{step}}, nil +} diff --git a/internal/project/joblog_test.go b/internal/project/joblog_test.go new file mode 100644 index 000000000..b4c9aa865 --- /dev/null +++ b/internal/project/joblog_test.go @@ -0,0 +1,148 @@ +package project + +import ( + "errors" + "slices" + "strings" + "testing" + "time" + + "github.com/lichdotdev/lich/api" +) + +const jobPage = "https://github.com/o/r/actions/runs/1/job/11" + +// jobAnswer and jobLogText are a failed job as GitHub's API serves it: steps +// told to the second, and a log that names none of them. +const ( + jobAnswer = `{"steps":[ + {"name":"Set up job","conclusion":"success","started_at":"2026-12-04T00:01:09Z","completed_at":"2026-12-04T00:01:11Z"}, + {"name":"Set up Go","conclusion":"success","started_at":"2026-12-04T00:01:11Z","completed_at":"2026-12-04T00:02:21Z"}, + {"name":"Backend tests","conclusion":"failure","started_at":"2026-12-04T00:02:21Z","completed_at":"2026-12-04T00:05:52Z"}, + {"name":"Publish","conclusion":"skipped","started_at":"2026-12-04T00:05:52Z","completed_at":"2026-12-04T00:05:52Z"}, + {"name":"Post Set up Go","conclusion":"success","started_at":"2026-12-04T00:05:52Z","completed_at":"2026-12-04T00:05:54Z"}]}` + jobLogText = "\uFEFF2026-12-04T00:01:09.2489700Z Current runner version: '2.337.0'\n" + + "2026-12-04T00:01:11.0100000Z Complete job name: test\n" + + "2026-12-04T00:01:11.5698460Z ##[group]Run actions/setup-go@v7\n" + + "2026-12-04T00:01:11.6000000Z ##[endgroup]\n" + + "2026-12-04T00:02:21.0230480Z go env\n" + + "2026-12-04T00:02:21.1510320Z ##[group]Run go test ./...\n" + + "2026-12-04T00:02:30.0000000Z \x1b[31mFAIL\x1b[0m\tx\r\n" + + "a line of its own, with no stamp\n" + + "2026-12-04T00:05:52.6083170Z ##[error]Process completed with exit code 1.\n" + + "2026-12-04T00:05:52.7704800Z Post job cleanup.\n" +) + +func jobLogGH(log string, refuseFlag bool) ghRunner { + return func(_ time.Duration, _, _ string, args ...string) ([]byte, error) { + if slices.Contains(args, "--allow-escape-sequences") && refuseFlag { + return nil, errors.New("unknown flag: --allow-escape-sequences") + } + switch args[len(args)-1] { + case "repos/o/r/actions/jobs/11": + return []byte(jobAnswer), nil + case "repos/o/r/actions/jobs/11/logs": + if log == "" { + return nil, errors.New("HTTP 410") + } + return []byte(log), nil + } + return nil, errors.New("unexpected call") + } +} + +func TestJobLogHandsEachLineToItsStep(t *testing.T) { + t.Parallel() + want := []api.JobStep{ + {Name: "Set up job", State: checkPassed, Lines: []string{"Current runner version: '2.337.0'", "Complete job name: test"}}, + {Name: "Set up Go", State: checkPassed, Lines: []string{"##[group]Run actions/setup-go@v7", "go env"}}, + {Name: "Backend tests", State: checkFailed, Lines: []string{"##[group]Run go test ./...", "FAIL\tx", + "a line of its own, with no stamp", "##[error]Process completed with exit code 1."}}, + {Name: "Post Set up Go", State: checkPassed, Lines: []string{"Post job cleanup."}}, + } + for _, refuse := range []bool{false, true} { + log, err := (&Service{runner: jobLogGH(jobLogText, refuse)}).JobLog(t.Context(), api.JobLogOptions{Path: t.TempDir(), URL: jobPage}) + if err != nil { + t.Fatal(err) + } + if len(log.Steps) != len(want) { + t.Fatalf("steps = %+v, want %d", log.Steps, len(want)) + } + for i, w := range want { + got := log.Steps[i] + if got.Name != w.Name || got.State != w.State || !slices.Equal(got.Lines, w.Lines) { + t.Errorf("step %d = %+v, want %+v", i, got, w) + } + } + if s := log.Steps[2]; s.StartedAt != "2026-12-04T00:02:21Z" || s.CompletedAt != "2026-12-04T00:05:52Z" { + t.Errorf("the failed step ran %s to %s", s.StartedAt, s.CompletedAt) + } + } +} + +func TestJobLogFailures(t *testing.T) { + t.Parallel() + s := &Service{runner: jobLogGH("", false)} + for _, page := range []string{"https://ci.example.com/7", "https://github.com/o/r/../x/actions/runs/1/job/11", ""} { + if _, err := s.JobLog(t.Context(), api.JobLogOptions{Path: t.TempDir(), URL: page}); err == nil { + t.Errorf("%q read a log", page) + } + } + if _, err := s.JobLog(t.Context(), api.JobLogOptions{Path: t.TempDir(), URL: jobPage}); err == nil { + t.Error("an expired log is not an error") + } + if steps := splitJobLog([]byte("one\ntwo\n"), nil); len(steps) != 1 || len(steps[0].Lines) != 2 { + t.Errorf("a job with no steps = %+v, want its lines whole", steps) + } +} + +func TestGitLabJobLogIsTheWholeTrace(t *testing.T) { + t.Parallel() + var asked string + g := gitlabForge{run: func(_ time.Duration, _ string, args ...string) ([]byte, error) { + asked = args[len(args)-1] + return fixture(t, "trace_failed.txt"), nil + }} + log, err := g.jobLog(".", "https://gitlab.com/group/sub/proj/-/jobs/42") + if err != nil { + t.Fatal(err) + } + if asked != "projects/group%2Fsub%2Fproj/jobs/42/trace" { + t.Errorf("asked for %q", asked) + } + text := strings.Join(log.Steps[0].Lines, "\n") + if len(log.Steps) != 1 || !strings.Contains(text, "DONE 33 tests, 1 failure") || !strings.Contains(text, "Uploading artifacts") { + t.Errorf("the trace is not whole:\n%s", text) + } + if strings.ContainsAny(text, "\x1b\r") || strings.Contains(text, "section_") { + t.Errorf("the trace keeps markers or escapes:\n%q", text) + } + if _, err := g.jobLog(".", jobPage); err == nil { + t.Error("a GitHub job read as a GitLab one") + } +} + +func TestOnlyAFinishedJobHasALog(t *testing.T) { + t.Parallel() + items := toCheckItems([]checkItem{ + {Name: "failed", Status: "COMPLETED", Conclusion: "FAILURE", DetailsURL: jobPage}, + {Name: "running", Status: "IN_PROGRESS", DetailsURL: jobPage}, + {Name: "skipped", Status: "COMPLETED", Conclusion: "SKIPPED", DetailsURL: jobPage}, + {Context: "ci/legacy", State: "ERROR", TargetURL: "https://ci.example.com/7"}, + }) + for _, it := range items { + if it.HasLog != (it.Name == "failed") { + t.Errorf("%s: HasLog = %v", it.Name, it.HasLog) + } + } + _, jobs := jobChecks([]glabJob{ + {Name: "done", Status: "success", StartedAt: "2026-12-04T00:00:00Z", WebURL: "https://gitlab.com/g/p/-/jobs/1"}, + {Name: "never ran", Status: "skipped", WebURL: "https://gitlab.com/g/p/-/jobs/2"}, + {Name: "running", Status: "running", StartedAt: "2026-12-04T00:00:00Z", WebURL: "https://gitlab.com/g/p/-/jobs/3"}, + }) + for _, it := range jobs { + if it.HasLog != (it.Name == "done") { + t.Errorf("GitLab %s: HasLog = %v", it.Name, it.HasLog) + } + } +} diff --git a/internal/project/prchecks.go b/internal/project/prchecks.go index 2bdefed82..0f3edb643 100644 --- a/internal/project/prchecks.go +++ b/internal/project/prchecks.go @@ -102,13 +102,15 @@ func toCheckItems(items []checkItem) []CheckItem { } out := make([]CheckItem, 0, len(items)) for _, it := range items { + state, page := checkState(it), firstNonEmpty(it.DetailsURL, it.TargetURL) out = append(out, CheckItem{ Name: firstNonEmpty(it.Name, it.Context), - State: checkState(it), + State: state, Description: firstNonEmpty(it.WorkflowName, it.Description), - URL: firstNonEmpty(it.DetailsURL, it.TargetURL), + URL: page, StartedAt: it.StartedAt, CompletedAt: it.CompletedAt, + HasLog: state != checkPending && it.Conclusion != "SKIPPED" && githubJobPage.MatchString(page), }) } sort.SliceStable(out, func(i, j int) bool { diff --git a/internal/routes/project.go b/internal/routes/project.go index 2859c7341..91423ef9d 100644 --- a/internal/routes/project.go +++ b/internal/routes/project.go @@ -11,6 +11,7 @@ import ( func Project(d *rpc.Handler, s *project.Service) { rpc.Handle(d, api.ProjectShowCode, s.ShowCode) rpc.Handle(d, api.ProjectCheckLog, s.CheckLog) + rpc.Handle(d, api.ProjectJobLog, s.JobLog) projectFiles(d, s) projectChanges(d, s) projectCommits(d, s) diff --git a/native/backend/pulls.go b/native/backend/pulls.go index edfbc0ded..af3fe4f16 100644 --- a/native/backend/pulls.go +++ b/native/backend/pulls.go @@ -139,12 +139,20 @@ func (c *Client) PullRequestDiff(ctx context.Context, path string, number int) ( type CommitRangeDiff = api.CommitRangeDiff +// JobLog is a finished job's log, by step. +type JobLog = api.JobLog + // CommitRangeDiff is the diff of a pull request's commits first to last // alone, from first's parent. func (c *Client) CommitRangeDiff(ctx context.Context, path, first, last string) (CommitRangeDiff, error) { return callMethod(ctx, c, api.ProjectCommitRangeDiff, api.CommitRangeOptions{Path: path, First: first, Last: last}) } +// JobLog is the whole log of the finished job at a check's url. +func (c *Client) JobLog(ctx context.Context, path, url string) (JobLog, error) { + return callMethod(ctx, c, api.ProjectJobLog, api.JobLogOptions{Path: path, URL: url}) +} + // PullRequestMergeBase is the commit pull request number's diff is taken // from: the old side of every file in it. func (c *Client) PullRequestMergeBase(ctx context.Context, path string, number int) (string, error) { From b4ba7bd348f4b02517537bd60587b644eb496d1b Mon Sep 17 00:00:00 2001 From: omartelo Date: Fri, 4 Dec 2026 00:40:51 -0300 Subject: [PATCH 2/2] Redraw the Pulls screen --- CHANGELOG.md | 2 + docs/ceilings.md | 10 + native/DESIGN.md | 54 +- native/cmd/lich-native/chat_items.go | 25 +- native/cmd/lich-native/dock_comments.go | 47 +- native/cmd/lich-native/dock_review_file.go | 38 +- native/cmd/lich-native/forge_store_test.go | 6 +- native/cmd/lich-native/pulls.go | 10 +- native/cmd/lich-native/pulls_avatar.go | 7 +- native/cmd/lich-native/pulls_checks.go | 135 +++++ native/cmd/lich-native/pulls_comment_edit.go | 109 ++-- native/cmd/lich-native/pulls_commit_range.go | 63 +- native/cmd/lich-native/pulls_commits.go | 72 +++ native/cmd/lich-native/pulls_conversation.go | 538 ++++-------------- native/cmd/lich-native/pulls_edit.go | 76 +-- native/cmd/lich-native/pulls_files.go | 121 ++-- native/cmd/lich-native/pulls_i18n_test.go | 10 +- native/cmd/lich-native/pulls_keys.go | 10 +- native/cmd/lich-native/pulls_line.go | 134 +++++ native/cmd/lich-native/pulls_list.go | 402 +++++-------- native/cmd/lich-native/pulls_list_test.go | 162 ++++-- native/cmd/lich-native/pulls_log.go | 461 +++++++++++++++ native/cmd/lich-native/pulls_log_test.go | 149 +++++ native/cmd/lich-native/pulls_logic.go | 189 +++--- native/cmd/lich-native/pulls_logic_test.go | 33 +- native/cmd/lich-native/pulls_overview.go | 270 +++++++++ native/cmd/lich-native/pulls_panels.go | 372 ++---------- native/cmd/lich-native/pulls_skeleton.go | 167 ++---- native/cmd/lich-native/pulls_skeleton_tabs.go | 97 +--- .../lich-native/pulls_skeleton_tabs_test.go | 6 +- native/cmd/lich-native/pulls_store.go | 26 +- native/cmd/lich-native/pulls_store_test.go | 32 +- native/cmd/lich-native/pulls_submit.go | 2 +- native/cmd/lich-native/pulls_thread.go | 313 ++++++++++ native/cmd/lich-native/pulls_thread_test.go | 57 ++ native/cmd/lich-native/pulls_view.go | 386 +++++-------- native/cmd/lich-native/pulls_write.go | 67 +++ native/cmd/lich-native/stale_pulls_test.go | 31 +- native/cmd/ui-gallery/sections_coverage.go | 6 +- native/i18n/locales/en/pulls.json | 90 ++- native/i18n/locales/en/session.json | 2 + native/i18n/locales/en/tourPulls.json | 2 +- native/i18n/locales/es/pulls.json | 90 ++- native/i18n/locales/es/session.json | 2 + native/i18n/locales/es/tourPulls.json | 2 +- native/i18n/locales/ja/pulls.json | 86 ++- native/i18n/locales/ja/session.json | 2 + native/i18n/locales/ja/tourPulls.json | 2 +- native/i18n/locales/ko/pulls.json | 83 ++- native/i18n/locales/ko/session.json | 2 + native/i18n/locales/ko/tourPulls.json | 2 +- native/i18n/locales/pt-br/pulls.json | 90 ++- native/i18n/locales/pt-br/session.json | 2 + native/i18n/locales/pt-br/tourPulls.json | 2 +- native/i18n/locales/ru/pulls.json | 102 ++-- native/i18n/locales/ru/session.json | 2 + native/i18n/locales/ru/tourPulls.json | 2 +- native/i18n/locales/zh-cn/pulls.json | 86 ++- native/i18n/locales/zh-cn/session.json | 2 + native/i18n/locales/zh-cn/tourPulls.json | 2 +- native/ui/textarea.go | 8 +- 61 files changed, 3111 insertions(+), 2247 deletions(-) create mode 100644 native/cmd/lich-native/pulls_checks.go create mode 100644 native/cmd/lich-native/pulls_commits.go create mode 100644 native/cmd/lich-native/pulls_line.go create mode 100644 native/cmd/lich-native/pulls_log.go create mode 100644 native/cmd/lich-native/pulls_log_test.go create mode 100644 native/cmd/lich-native/pulls_overview.go create mode 100644 native/cmd/lich-native/pulls_thread.go create mode 100644 native/cmd/lich-native/pulls_thread_test.go create mode 100644 native/cmd/lich-native/pulls_write.go diff --git a/CHANGELOG.md b/CHANGELOG.md index f08efbbfe..26671be48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,9 +18,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Install an agent from Settings, on this computer or on a server.** In Settings › Providers a provider that is not installed has an Install button that runs its official installer on the scope's machine; a project on a server with no agent installed offers the same from its empty screen. - **A chat waiting on the sessions it asked says which ones, and lets you stop it.** Over the message box, Waiting on names each session still owing an answer, one that needs you first with what it needs, a click opening it; Stop ends the turn. Only on Claude Code. - **An agent is told when a merged pull request conflicts with what it is working on.** When the pull request of another session's checkout merges, the agents in the repository's other checkouts whose work conflicts with it get a note naming the files, at their next edit or command. An idle session is not woken for it; not in Cursor CLI's chat. +- **Read a check's log without leaving lich.** On a pull request's Checks tab, click a finished GitHub Actions or GitLab job: its steps open beside the list of checks, with the failed one unfolded at its first error. The log can be searched and copied; a running job and other services' checks still open in the browser. ### 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. - **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 processor they took. Answers also come in more smoothly, about thirty updates a second instead of twenty. diff --git a/docs/ceilings.md b/docs/ceilings.md index 5c306a564..3e689940b 100644 --- a/docs/ceilings.md +++ b/docs/ceilings.md @@ -1383,6 +1383,16 @@ work when nobody knows it and that the call site never shows. The mechanism and without comparing them — noreply forms, vanity domains and org aliases make a string comparison a false-positive farm. The Commits tab of the Pulls screen lists each commit's author and compares it with nothing either, so a branch built under the wrong identity says so nowhere in lich. +- **A check's log opens in the window only once its job is over, and only for GitHub Actions and GitLab jobs** + (`internal/project/joblog.go`): neither forge serves a running job's log whole, and another service's check is + a link. Such a check opens its page in the browser. GitHub's log is one text with no step in it, so it is cut + at the steps' own start times, which are whole seconds: a line printed in the second a step changed can stand + under its neighbour. A GitLab trace names its sections only by the runner's own words for them, so it opens as + one log with no steps. +- **Ready to merge on the Pulls list is what a list row says** (`needOf`, `native/cmd/lich-native/pulls_logic.go`): + no draft, no failing or running check, and no review asked for or refused. A row does not carry whether the + branch conflicts with its base, and a GitLab row carries no checks, so one that cannot merge can stand there; + opening it says so. - **A checkout is GitLab only when its remote says so, and glab is the judge of a self-hosted one** (`internal/project/forge.go` `forgeOf`): the remote is origin, else the first one git lists. github.com is GitHub, gitlab.com is GitLab, and any other host is GitLab only when `glab config get token --host ` diff --git a/native/DESIGN.md b/native/DESIGN.md index e15dffc69..215544e9e 100644 --- a/native/DESIGN.md +++ b/native/DESIGN.md @@ -95,7 +95,7 @@ look on every page (`browser_notes_view.go`), and Windows' close button hovers i | --- | --- | | `Canvas` | the ground the islands float on | | `Background` | full screens inside the stage (Settings, Pulls) and code blocks set inside a raised surface | -| `Sidebar`, `Card`, `Popover` | islands and raised parts: sidebar, dock, a thread or comment box, menus, dialogs | +| `Sidebar`, `Card`, `Popover` | islands and raised parts: sidebar, dock, a code or log island and the box being written in on Pulls, menus, dialogs | | `Accent` | hover and selection fill | | `MutedForeground` | secondary text, icons at rest, paths, meta, the tree's links and neutral rings | | `Border` | input edges and the island hairline | @@ -291,10 +291,10 @@ Every list row is padded `Space(1.5)` (6px, `rowInset`; `navRowPadX` and `pullsR the window's lists read on one grid, the sidebar's tree's: - **The node column** starts at 14px from the island's edge and is 22px wide: a tree row's ring sits in it, - and so does a list row's leading icon, centred in a box of the ring's width (`inNodeColumn`), its centre at - 25px with the ring's. + and so does a list row's leading icon, a Pulls row's state included, centred in a box of the ring's width + (`inNodeColumn`), its centre at 25px with the ring's. - **The label** follows the column `Space(1.5)` after it, at 42px, in a tree row and an icon row alike. -- **A row with no icon** (a Pulls row, a search hit) starts its text in the node column, at 14px. +- **A row with no icon** (a search hit) starts its text in the node column, at 14px. A screen body follows its rows: the Pulls body sits at 14px (`pullsPadX`), where its rows start. @@ -1049,8 +1049,38 @@ dock's do. A failure is git's first line in `Destructive` `TextXS` left of Commit, the rest in its tooltip, and the message stays. -### Pulls: Files and Commits - +### Pulls + +Every tab is one list on the screen's own `Background`, a line a row (`pullsLine`, 34dp): the state's glyph in the +node column, the text at 42px (`pullsTextX`), the facts after it in muted `TextXS`, who and when in columns at the +right. No card, rule or zebra separates the rows; a group is a muted uppercase heading with its count +(`pullsHeading`) and the space over it. A line out of room drops its last facts first and cuts the title last +(`lineText`). + +- **The list is sorted by what each one needs** (`needOf`): Ready to merge, Needs work, In review, Drafts; a group + with nothing in it is left out, and Closed and Merged have no groups. A row says its one reason (a failed count, + Changes requested, checks done of all) and nothing when it is ready. The filter is a `Bare` input on the node + column, with no box: it is the head of the list, not a field of a form. +- **The head** is two strips: back, the title with its pencil, number and diff size, and the actions at the right; + under it the tabs, ghost, and the stepper through the list. The actions are what the state calls for (Fix, Send + open threads, Submit review, outline), then Go to session (ghost), Merge (filled) and `⋯` last. In a narrow + island they wrap under the title. A pull request that is over keeps a disabled ghost naming how it ended in + Merge's place. +- **Overview** is the description at a reading width and the facts in a column at its right, a line each + (`factLine`): branches, conflicts, checks, a reviewer with what they said, the sessions and checkout it has here. + A fact it does not have is left out, never "none". A narrow island puts the facts on top. Editing swaps the + description for its box with the text where the prose was, and the facts stay still. +- **Conversation** has no boxes around what was said: an avatar, the name and age, the text under them. A thread is + a folding line with its file over its code, the lines it is about in an edged `Sidebar` island, then its talk. A + comment's own actions are in a `⋯` under the pointer. Only the box being written in is filled (`writeBox`), + with `Textarea.Bare` inside it, so the one surface on the page is where the keyboard is. +- **Files** gives each file a header on the `Background` and its code in an edged `Sidebar` island under it, where + its threads sit between the lines. The dock's Review keeps the header inside the card. +- **Checks** are grouped Failed, Running and Passed. A finished job opens its log in the same tab (`pulls_log.go`): + the checks stay in a column at the left under All checks, and the log is an edged `Sidebar` island at the right, + its steps (GitLab's has none) folding lines with the failed one open and scrolled to its first error. The log's text is mono + `TextXS`; only what the runner marked an error or a warning takes a tone. A narrow island shows the log alone + with a back button. A check with no log to read here opens its page. - **Viewed is kept** (`pulls_viewed.go`): a file ticked comes back ticked and folded after a restart while its diff is the same. One whose diff moved comes back unticked and open, "changed since your review" in `TextXS` `ToneWait` after its path, and the Files bar's left says "2 files changed since your review on Nov 24", muted @@ -1061,17 +1091,17 @@ dock's do. oldest first, a check in a `Space(4)` column, the short oid in mono muted, the title and its age at the right; the row under the pointer ends in Shift's key cap (`⇧`) with "range", where the key acts, and no line under the list spells it out. A click picks one commit and shuts the panel, Shift+click stretches a contiguous run and - keeps it open. While a run is shown the bar says, muted, which run and that - comments and Viewed are off, and the line menu offers only adding the file to a session: the run's lines are + keeps it open. While a run is shown the chip names it, with an ✕ back to all + of them, and the bar says, muted, that comments and Viewed are off, and the line menu offers only adding the file to a session: the run's lines are not the pull request's. On a Commits row, a ghost "View changes" shows under the pointer and opens Files on that commit alone; the row's click still opens its body. -- **States are glyphs** (`pullState`): Open, Merged, Closed, Draft, Approved, Changes requested and Resolved are +- **States are glyphs** (`pullState`): Open, Merged, Closed, Draft, Approved and Changes requested are a glyph in the state's tone, each word the glyph's semantic label; a branch with nothing in the way of a merge says nothing. A draft is muted, on a list row and in the head alike, since amber on a row is the verdict waiting on its reviewer. - **Actions** stand at the right. In a comment, reply or edit box, Cancel then the action, which wears - Ctrl+Enter's cap (`ctrlEnterCap`, Cmd+Enter on macOS) or `↵`'s where Enter sends; Resolve is filled at its - thread line's end (outline once resolved); Merge ends the header's actions and Commit ends the merge strip; a - pending comment's Discard is destructive. + Ctrl+Enter's cap (`ctrlEnterCap`, Cmd+Enter on macOS) or `↵`'s where Enter sends. A thread's are ghost `SizeXS` + after its talk: Send to session, then Resolve, which folds it away. A pending comment's Edit and Discard are the + same small neutral ghosts: what Discard drops was never sent. - **A pull request linked by hand** (`linkpr_panel.go`): the session's card menu has Link pull request…, a `DropdownPanel` (`Space(75)` wide) with one field for `#N` or a GitHub or GitLab URL, Cancel (ghost) and a primary Link disabled while the field is empty, not a dialog. The linked pull request wears the `link` glyph diff --git a/native/cmd/lich-native/chat_items.go b/native/cmd/lich-native/chat_items.go index 5ef140eeb..e557d28c1 100644 --- a/native/cmd/lich-native/chat_items.go +++ b/native/cmd/lich-native/chat_items.go @@ -648,7 +648,7 @@ func expandTabs(s string) string { return strings.ReplaceAll(s, "\t", hunkTab) } // chatDiff is a tool's diff as a small window on the window's background: the // file's name and its +added -deleted, then the hunks, each -// added or removed line in its tone, as a thread's hunk is (hunkTail). +// added or removed line in its tone. func chatDiff(gtx C, th *ui.Theme, diff string) D { name, added, deleted, body := splitDiff(diff) children := make([]layout.FlexChild, 0, len(body)+2) @@ -916,3 +916,26 @@ func chatTick(gtx C, since time.Time) { elapsed := max(gtx.Now.Sub(since), 0) gtx.Execute(op.InvalidateCmd{At: since.Add(elapsed.Truncate(time.Second) + time.Second)}) } + +// hunkTint is how strongly an added or removed line tints its row, and +// hunkTab what a tab expands to: the mono font has no glyph for one. +const ( + hunkTint = 0.12 + hunkTab = " " +) + +func hunkLine(gtx C, th *ui.Theme, line string) D { + fg, tint := th.MutedForeground, th.Background + switch { + case strings.HasPrefix(line, "+"): + fg, tint = th.TonePass, ui.MixOKLab(th.Background, th.TonePass, hunkTint) + case strings.HasPrefix(line, "-"): + fg, tint = th.Destructive, ui.MixOKLab(th.Background, th.Destructive, hunkTint) + } + gtx.Constraints.Min.X = gtx.Constraints.Max.X + return layout.Background{}.Layout(gtx, + func(gtx C) D { return ui.Fill(gtx, tint, 0) }, + func(gtx C) D { + return th.Text(ui.TextXS, strings.ReplaceAll(line, "\t", hunkTab)).Mono().In(fg).Truncated().Layout(gtx) + }) +} diff --git a/native/cmd/lich-native/dock_comments.go b/native/cmd/lich-native/dock_comments.go index 3b5649587..c731f5616 100644 --- a/native/cmd/lich-native/dock_comments.go +++ b/native/cmd/lich-native/dock_comments.go @@ -238,20 +238,43 @@ func (c *commentComposer) commit(store *commentStore, target string) { c.close() } -// layout draws the box while open; it is zero-sized when closed. -func (c *commentComposer) layout(gtx C, th *ui.Theme, store *commentStore, target string) D { +// ready takes the frame's input and answers whether the box is still open. +func (c *commentComposer) ready(gtx C, store *commentStore, target string) bool { if !c.shown { - return D{} + return false } c.editor.Submit = !c.review c.filed(gtx, store, target) - if !c.shown { - return D{} - } - if c.focus { + if c.shown && c.focus { gtx.Execute(key.FocusCmd{Tag: &c.editor}) c.focus = false } + return c.shown +} + +// words are what the box adds to and asks for; only one of the two reaches +// GitHub. +func (c *commentComposer) words() (action, prompt, keys string) { + if c.review { + return i18n.T("diff.reviewSlots.addToReview"), i18n.T("diff.reviewSlots.reviewPlaceholder"), ctrlEnterCap() + } + return i18n.T("diff.reviewSlots.addToBatch"), i18n.T("diff.reviewSlots.sessionPlaceholder"), "↵" +} + +// write draws the box as everything on the Pulls screen is written in. +func (c *commentComposer) write(gtx C, th *ui.Theme, store *commentStore, target string) D { + if !c.ready(gtx, store, target) { + return D{} + } + action, prompt, keys := c.words() + return writeBox{editor: &c.editor, placeholder: prompt, action: action, keys: keys, send: &c.add, cancel: &c.cancel}.layout(gtx, th) +} + +// layout draws the box while open; it is zero-sized when closed. +func (c *commentComposer) layout(gtx C, th *ui.Theme, store *commentStore, target string) D { + if !c.ready(gtx, store, target) { + return D{} + } gtx.Constraints.Min.X = gtx.Constraints.Max.X on := th.On(th.Sidebar) return layout.Background{}.Layout(gtx, @@ -280,15 +303,9 @@ func (c *commentComposer) heading() string { // box is CommentBox: the field (max-h-64), then Add and Cancel. func (c *commentComposer) box(th *ui.Theme) layout.Widget { return func(gtx C) D { - label, prompt := i18n.T("diff.reviewSlots.addToBatch"), i18n.T("diff.reviewSlots.sessionPlaceholder") - if c.review { - label, prompt = i18n.T("diff.reviewSlots.addToReview"), i18n.T("diff.reviewSlots.reviewPlaceholder") - } + label, prompt, keys := c.words() add := th.Button(&c.add, label) - add.Size, add.Disabled, add.Keys = ui.SizeSM, strings.TrimSpace(c.editor.Text()) == "", "↵" - if c.review { - add.Keys = ctrlEnterCap() - } + add.Size, add.Disabled, add.Keys = ui.SizeSM, strings.TrimSpace(c.editor.Text()) == "", keys cancel := th.Button(&c.cancel, i18n.T("common.action.cancel")) cancel.Size, cancel.Variant = ui.SizeSM, ui.VariantGhost buttons := []layout.FlexChild{layout.Flexed(1, func(gtx C) D { return D{Size: image.Pt(gtx.Constraints.Min.X, 0)} }), layout.Rigid(cancel.Layout), ui.Gap(2), layout.Rigid(add.Layout)} diff --git a/native/cmd/lich-native/dock_review_file.go b/native/cmd/lich-native/dock_review_file.go index 339ab0174..6eaddf44f 100644 --- a/native/cmd/lich-native/dock_review_file.go +++ b/native/cmd/lich-native/dock_review_file.go @@ -1,10 +1,14 @@ package main import ( + "image" "log" "gioui.org/font" "gioui.org/layout" + "gioui.org/op" + "gioui.org/op/clip" + "gioui.org/op/paint" "gioui.org/unit" "github.com/lichdotdev/godemirror" @@ -144,22 +148,41 @@ func (c *fileCard) layout(gtx C, p *reviewPanel) D { return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { return c.header(gtx, p) }), layout.Rigid(func(gtx C) D { - if !c.open { + switch { + case !c.open: return D{} + case p.pr != nil: + return codeIsland(gtx, p.th, func(gtx C) D { return c.body(gtx, p) }) } return c.body(gtx, p) }), ) } -// header is the sticky row (bg-sidebar px-2 py-1 text-xs gap-2), ruled -// underneath while the file is open. +// codeIsland is w on th's surface with rounded corners and a hairline, as tall +// as w. +func codeIsland(gtx C, th *ui.Theme, w layout.Widget) D { + macro := op.Record(gtx.Ops) + dims := layout.Inset{Left: 1, Right: 1}.Layout(gtx, w) + call := macro.Stop() + r := gtx.Dp(ui.RadiusLG) + defer clip.UniformRRect(image.Rectangle{Max: dims.Size}, r).Push(gtx.Ops).Pop() + paint.Fill(gtx.Ops, th.Surface) + call.Add(gtx.Ops) + ui.IslandBorder(gtx, dims.Size, r, th.Over(th.Border)) + return dims +} + +// header is the sticky row (bg-sidebar px-2 py-1 text-xs gap-2); on the Pulls +// screen it is on the screen's own surface, over the island of its code. func (c *fileCard) header(gtx C, p *reviewPanel) D { - th := p.th - on := th.On(th.Sidebar) + on := p.th.On(p.th.Sidebar) + if p.pr != nil { + on = p.th.On(p.th.Background) + } gtx.Constraints.Min.X = gtx.Constraints.Max.X dims := layout.Background{}.Layout(gtx, - func(gtx C) D { return ui.Fill(gtx, th.Sidebar, 0) }, + func(gtx C) D { return ui.Fill(gtx, on.Surface, 0) }, func(gtx C) D { return layout.Inset{Left: ui.Space(2), Right: ui.Space(2), Top: ui.Space(1), Bottom: ui.Space(1)}.Layout(gtx, func(gtx C) D { return c.headerRow(gtx, on, p) @@ -373,6 +396,9 @@ func (c *fileCard) composerBlock(gtx C) D { c.composer.toReview = p.pr.toReview } return p.spot(gtx, tourReviewComposer, func(gtx C) D { + if p.pr != nil { + return c.composer.write(gtx, p.th, p.comments, p.target) + } return composerSlot.Layout(gtx, func(gtx C) D { return c.composer.layout(gtx, p.th, p.comments, p.target) }) }) } diff --git a/native/cmd/lich-native/forge_store_test.go b/native/cmd/lich-native/forge_store_test.go index e987bd146..bca3f4e32 100644 --- a/native/cmd/lich-native/forge_store_test.go +++ b/native/cmd/lich-native/forge_store_test.go @@ -219,11 +219,11 @@ func TestPullsScreenOnGitLabWaitsForTheForgeAndNeverAsksGitHub(t *testing.T) { } release.Do(func() { close(hold) }) r.waitFor(t, "!7") + if !r.shows("Filter merge requests") || !r.shows("New merge request") { + t.Errorf("the index does not say merge requests:\n%s", r.drawn()) + } r.clickLabel(t, "Fix the thing") - // The skeleton already says Merge requests, and its shimmer never goes - // still: wait for what only the detail draws. r.waitFor(t, "fix → main") - r.waitFor(t, "Merge requests") if r.shows(i18n.T("pulls.pullRequestView.tab.conversation")) { t.Error("a merge request shows Conversation") } diff --git a/native/cmd/lich-native/pulls.go b/native/cmd/lich-native/pulls.go index 797ec83e5..4fde6cbab 100644 --- a/native/cmd/lich-native/pulls.go +++ b/native/cmd/lich-native/pulls.go @@ -69,7 +69,6 @@ type pullsScreen struct { branchPR int branch string // the checkout's branch, which the index's New names state pullsState - filter ui.TabsState // cursor is the index row the keyboard is on, by number; it is drawn // only once the keyboard moved it, so a mouse user sees no selection. cursor int @@ -227,13 +226,13 @@ func (p *pullsScreen) awaitAccount(gtx C, th *ui.Theme, act *pullsAction) D { if p.selected == 0 { return p.indexLayout(gtx, th, pullsRead[[]backend.PRSummary]{}, act) } - return p.view.withToolbar(gtx, th, p, func(gtx C) D { return skeletonHeading(gtx, th) }, p.view.detailSkeleton(th)) + return p.view.loadingLayout(gtx, th, p) } -// visible is the index's rows under its filter and query, the order the +// visible is the index's rows under its query, the order the // detail's previous and next walk. func (p *pullsScreen) visible(rows []backend.PRSummary) []backend.PRSummary { - return filterPulls(rows, pullsFilter(p.filter.Selected), p.query.Text()) + return filterPulls(rows, p.state, p.query.Text()) } // openPR shows pull request n, the index's cursor following it. Both it and @@ -243,13 +242,14 @@ func (p *pullsScreen) openPR(n int) { p.store.invalidate() } -// backToIndex leaves the pull request for the index, its filter, query and +// backToIndex leaves the pull request for the index, its query and // cursor as they were. func (p *pullsScreen) backToIndex() { if p.selected != 0 { p.cursor = p.selected } p.selected = 0 + p.view.log.close() p.store.invalidate() } diff --git a/native/cmd/lich-native/pulls_avatar.go b/native/cmd/lich-native/pulls_avatar.go index 7a2fb257f..684393244 100644 --- a/native/cmd/lich-native/pulls_avatar.go +++ b/native/cmd/lich-native/pulls_avatar.go @@ -5,16 +5,17 @@ import ( "image" "gioui.org/layout" + "gioui.org/unit" "github.com/lichdotdev/lich/native/i18n" "github.com/lichdotdev/lich/native/ui" ) -// An author's avatar sits in a gutter beside the entry, GitHub's way: the +// An author's avatar sits in the lists' glyph column, GitHub's way: the // column of faces is what the eye scans a conversation by. var ( - authorAvatarSize = ui.Space(6) - authorAvatarGap = ui.Space(2.5) + authorAvatarSize = unit.Dp(2 * sessionTreeRingR) + authorAvatarGap = pullsLineGap ) // author is who wrote an entry: their login and the address of their picture, diff --git a/native/cmd/lich-native/pulls_checks.go b/native/cmd/lich-native/pulls_checks.go new file mode 100644 index 000000000..88eedc6e5 --- /dev/null +++ b/native/cmd/lich-native/pulls_checks.go @@ -0,0 +1,135 @@ +package main + +import ( + "image/color" + + "gioui.org/font" + "gioui.org/layout" + "gioui.org/unit" + + "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" +) + +// checkGroups are a pull request's checks by state, what asks for work first. +var checkGroups = []string{"failed", "pending", "passed"} + +func checkGroupLabel(state string) string { + switch state { + case "failed": + return i18n.T("pulls.pullsChecks.group.failed") + case "pending": + return i18n.T("pulls.pullsChecks.group.running") + } + return i18n.T("pulls.pullsChecks.group.passed") +} + +// checkGlyph is a check's state, or a step's. +func checkGlyph(th *ui.Theme, state string) (*icons.Icon, color.NRGBA) { + switch state { + case "failed": + return icPullX, th.Destructive + case "pending": + return icPullRunning, th.ToneWait + } + return icPullCheck, th.TonePass +} + +// checksTab is the Checks tab: every check grouped by state, or the log of +// the one that was opened beside them. +func (v *pullView) checksTab(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, act *pullsAction) D { + for _, c := range d.CheckRuns { + if clickableOf(v.checkClicks, c.Name+"\n"+c.URL).Clicked(gtx) { + v.openCheck(c, act) + } + } + if c, ok := v.log.check(d); ok { + return v.logLayout(gtx, th, p, d, c, act) + } + return v.panelList(gtx, th, v.checkRows(gtx, th, d, false)) +} + +// openCheck shows a finished job's log here; any other check is read on the +// page it links to. +func (v *pullView) openCheck(c backend.CheckItem, act *pullsAction) { + switch { + case c.HasLog: + v.log.show(c.URL) + case c.URL != "": + act.external = c.URL + } +} + +// checkRows is a heading and its lines for each state some check is in. beside +// the log a line is only the name and how long it took. +func (v *pullView) checkRows(gtx C, th *ui.Theme, d backend.PRDetail, beside bool) []layout.Widget { + if len(d.CheckRuns) == 0 { + return []layout.Widget{func(gtx C) D { return pullsNote(gtx, th, i18n.T("pulls.pullsChecks.none")) }} + } + now := gtx.Now + var rows []layout.Widget + for _, state := range checkGroups { + heading, count := len(rows), 0 + rows = append(rows, nil) + for _, c := range d.CheckRuns { + if c.State != state { + continue + } + count++ + click := clickableOf(v.checkClicks, c.Name+"\n"+c.URL) + took := checkDuration(c.StartedAt, c.CompletedAt, now) + rows = append(rows, func(gtx C) D { return checkRow(gtx, th, c, click, beside && c.URL == v.log.url, beside, took) }) + } + if count == 0 { + rows = rows[:heading] + continue + } + top := ui.Space(4) + if heading == 0 { + top = ui.Space(1) + if beside { + top = ui.Space(2) + } + } + rows[heading] = func(gtx C) D { return pullsHeading(gtx, th, checkGroupLabel(state), count, top) } + } + return rows +} + +// checkTimeWidth is the column of how long a check took. +var checkTimeWidth = unit.Dp(64) + +// checkRow is a check's line: its state, its name and description, whether +// the base requires it, and how long it took. +func checkRow(gtx C, th *ui.Theme, c backend.CheckItem, click *ui.Clickable, on, short bool, took string) D { + return pullsLine(gtx, th, click, on, func(gtx C, th *ui.Theme) D { + ic, fg := checkGlyph(th, c.State) + title := th.Text(ui.TextSM, c.Name).Weight(font.Medium).Layout + time := th.Text(ui.TextXS, took).Mono().Muted().Layout + lead := []layout.FlexChild{ + layout.Rigid(lineGlyph(th, ic, checkGroupLabel(c.State), fg)), + layout.Rigid(layout.Spacer{Width: pullsLineGap}.Layout), + } + if short { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, append(lead, + layout.Flexed(1, ui.Spanning(title)), ui.Gap(2), layout.Rigid(time))...) + } + required := "" + if c.Required { + required = i18n.T("pulls.pullsChecks.required") + } + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, append(lead, + layout.Flexed(1, ui.Spanning(func(gtx C) D { + if c.Description == "" { + return title(gtx) + } + return lineText(gtx, naturalWidth(gtx, title), title, th.Text(ui.TextXS, c.Description).Muted().Layout) + })), + ui.Gap(2), + layout.Rigid(th.Text(ui.TextXS, required).Muted().Layout), + ui.FixedColumn(checkTimeWidth, ui.AlignEnd(time)), + )...) + }) +} diff --git a/native/cmd/lich-native/pulls_comment_edit.go b/native/cmd/lich-native/pulls_comment_edit.go index 05c9626af..3cbbc834c 100644 --- a/native/cmd/lich-native/pulls_comment_edit.go +++ b/native/cmd/lich-native/pulls_comment_edit.go @@ -86,49 +86,67 @@ func (s *talkState) startEdit(t commentTarget) { s.focusEdit = t.key() } -// commentHead is an entry's byline with the ⋯ beside it, which is gone while -// the entry is being edited. -func (v *pullView) commentHead(gtx C, th *ui.Theme, p *pullsScreen, t commentTarget, byline layout.Widget) D { +// comment is an entry beside its author's avatar: head over content, with the +// ⋯ at the line's end only while the pointer is on the entry or its menu is +// open. content nil is an entry that says nothing more. +func (v *pullView) comment(gtx C, th *ui.Theme, p *pullsScreen, t commentTarget, who author, head, content layout.Widget) D { + s := &v.talk + over, ok := s.over[t.key()] + if !ok { + over = new(hoverArea) + s.over[t.key()] = over + } + over.read(gtx) + dims := p.withAvatar(gtx, th, who, func(gtx C) D { + children := []layout.FlexChild{layout.Rigid(func(gtx C) D { + gtx.Constraints.Min.Y = gtx.Dp(authorAvatarSize) + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Flexed(1, ui.Spanning(head)), + layout.Rigid(func(gtx C) D { return v.commentMore(gtx, th, p, t, over.over) }), + ) + })} + if content != nil { + children = append(children, ui.VGap(0.5), layout.Rigid(content)) + } + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, children...) + }) + over.watch(gtx, image.Rectangle{Max: dims.Size}) + return dims +} + +// commentMore is an entry's ⋯, drawing nothing while it has no say: nothing +// to offer, the entry being edited, or the pointer elsewhere. +func (v *pullView) commentMore(gtx C, th *ui.Theme, p *pullsScreen, t commentTarget, over bool) D { s := &v.talk entries := s.commentEntries(t) if len(entries) == 0 || s.editing[t.key()] { - return byline(gtx) - } - more := func(gtx C) D { - b := th.Button(clickableOf(s.moreClicks, t.key()), "") - b.Icon, b.Variant, b.Size = icPullMore, ui.VariantGhost, ui.SizeIconXS - return v.withTip(gtx, th, p, "more:"+t.key(), i18n.T("pulls.reviewThread.more"), b.Layout) + return D{} } menu, ok := s.menus[t.key()] if !ok { menu = new(ui.MenuState) s.menus[t.key()] = menu } - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, byline), - layout.Rigid(func(gtx C) D { return th.DropdownMenu(p.root, menu, entries).Layout(gtx, more) }), - ) + if !over && !menu.Opened() { + return D{} + } + return th.DropdownMenu(p.root, menu, entries).Layout(gtx, func(gtx C) D { + b := th.Button(clickableOf(s.moreClicks, t.key()), "") + b.Icon, b.Variant, b.Size = icPullMore, ui.VariantGhost, ui.SizeIconXS + // No taller than the name's line, which it must not move. + dims := v.withTip(gtx, th, p, "more:"+t.key(), i18n.T("pulls.reviewThread.more"), b.Layout) + dims.Size.Y = min(dims.Size.Y, gtx.Dp(authorAvatarSize)) + return dims + }) } -// threadComment is one comment of a thread beside its author's avatar: its -// byline over its body, or over the box editing it. +// threadComment is one comment of a thread, or the box editing it. func (v *pullView) threadComment(gtx C, th *ui.Theme, p *pullsScreen, t commentTarget, c backend.PRThreadComment, act *pullsAction, now time.Time) D { - editing := v.talk.editing[t.key()] - return p.withAvatar(gtx, th, author{c.Author, c.Avatar}, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return v.commentHead(gtx, th, p, t, func(gtx C) D { return byline(gtx, th, c.Author, "", c.Date, now) }) - }), - layout.Rigid(func(gtx C) D { - return layout.Inset{Top: ui.Space(0.5)}.Layout(gtx, func(gtx C) D { - if editing { - return v.editBox(gtx, th, t, act) - } - return th.Text(ui.TextSM, c.Body).Wrapped().Layout(gtx) - }) - }), - ) - }) + content := th.Text(ui.TextSM, c.Body).Wrapped().Layout + if v.talk.editing[t.key()] { + content = func(gtx C) D { return v.editBox(gtx, th, t, act) } + } + return v.comment(gtx, th, p, t, author{c.Author, c.Avatar}, func(gtx C) D { return byline(gtx, th, c.Author, "", c.Date, now) }, content) } // editBox rewrites an entry in place; Save sends it as it stands. A review's @@ -141,34 +159,19 @@ func (v *pullView) editBox(gtx C, th *ui.Theme, t commentTarget, act *pullsActio gtx.Execute(keyFocus(ed)) s.focusEdit = "" } - save, cancel := clickableOf(s.sendClicks, key), clickableOf(s.cancelClicks, key) + save := clickableOf(s.sendClicks, key) body := strings.TrimSpace(ed.Text()) if (save.Clicked(gtx) || ctrlEnter(gtx, ed)) && body != "" { act.edit = &commentEdit{target: t, body: body} } - busy := v.busyNow() == "edit:"+key - label := i18n.T("pulls.reviewThread.save") - if busy { - label = i18n.T("pulls.reviewThread.saving") + box := writeBox{editor: ed, action: i18n.T("pulls.reviewThread.save"), send: save, cancel: clickableOf(s.cancelClicks, key), busy: v.busyNow() == "edit:"+key} + if box.busy { + box.action = i18n.T("pulls.reviewThread.saving") } - saveB := th.Button(save, label) - saveB.Size, saveB.Disabled, saveB.Keys = ui.SizeSM, body == "" || busy, ctrlEnterCap() - cancelB := th.Button(cancel, i18n.T("common.action.cancel")) - cancelB.Size, cancelB.Variant = ui.SizeSM, ui.VariantGhost - var buttons []layout.FlexChild if t.kind == reviewSummary { - buttons = append(buttons, layout.Rigid(th.Text(ui.TextXS, i18n.T("pulls.reviewThread.verdictStays")).Muted().Layout)) - } - buttons = append(buttons, layout.Flexed(1, func(gtx C) D { return D{Size: image.Pt(gtx.Constraints.Min.X, 0)} }), layout.Rigid(cancelB.Layout), ui.Gap(2), layout.Rigid(saveB.Layout)) - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - ta := th.Textarea(ed, "") - ta.Resize = &s.fieldOf(key).resize - return ta.Layout(gtx) - }), - ui.VGap(2), - layout.Rigid(func(gtx C) D { return layout.Flex{Alignment: layout.Middle}.Layout(gtx, buttons...) }), - ) + box.note = i18n.T("pulls.reviewThread.verdictStays") + } + return box.layout(gtx, th) } // editComment sends an edit to the address its kind lives at; the re-read diff --git a/native/cmd/lich-native/pulls_commit_range.go b/native/cmd/lich-native/pulls_commit_range.go index c110a0608..dbd4a8e84 100644 --- a/native/cmd/lich-native/pulls_commit_range.go +++ b/native/cmd/lich-native/pulls_commit_range.go @@ -2,7 +2,6 @@ package main import ( "image" - "image/color" "slices" "strconv" "time" @@ -26,9 +25,10 @@ var commitPickWidth = unit.Dp(360) type commitPick struct { url, first, last, anchor string - panel ui.DropdownPanelState - all ui.Clickable - rows map[string]*ui.Clickable + panel ui.DropdownPanelState + face, drop ui.Clickable + all ui.Clickable + rows map[string]*ui.Clickable // views are the Commits tab's View changes, by oid. views map[string]*ui.Clickable } @@ -59,30 +59,57 @@ func (k *commitPick) pick(url string, commits []backend.PRCommit, i int, extend func (k *commitPick) clear() { k.first, k.last, k.anchor = "", "", "" } -// commitPicker is the Files tab's chip naming the commits shown, and the -// panel that picks them. +// commitChipWidth is how much of a commit's headline the chip shows. +var commitChipWidth = unit.Dp(320) + +// commitPicker is what the Files tab shows and the panel that picks it: All +// commits, or the picked ones filled, with their hash and the × that goes +// back to all. func (v *pullView) commitPicker(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail) D { k := &v.pick - label := i18n.T("pulls.pullsFiles.allCommits") - if from, to, ok := k.span(d.URL, d.Commits); ok { + if k.drop.Clicked(gtx) { + k.clear() + gtx.Execute(op.InvalidateCmd{}) + } + label, run := i18n.T("pulls.pullsFiles.allCommits"), "" + from, to, picked := k.span(d.URL, d.Commits) + switch { + case picked && from == to: + label, run = d.Commits[from].Headline, shortOID(d.Commits[from].OID) + case picked: label = i18n.T("pulls.pullsFiles.commits", i18n.Args{"count": to - from + 1}) + run = shortOID(d.Commits[from].OID) + ".." + shortOID(d.Commits[to].OID) } pop := th.DropdownPanel(p.root, &k.panel, commitPickWidth, func(gtx C, th *ui.Theme) D { return v.commitPickList(gtx, th, d) }) - return pop.Layout(gtx, func(gtx C) D { - return buttonFace(gtx, th, true, k.panel.Opened(), false, func(gtx C, th *ui.Theme, fg color.NRGBA) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(th.Text(ui.TextXS, label).In(fg).Layout), - ui.Gap(1), - layout.Rigid(func(gtx C) D { return icPullDown.Layout(gtx, chatCrumbGlyph, fg) }), - ) - }) - }) + chip := func(gtx C) D { + gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(commitChipWidth)) + b := th.Button(&k.face, label) + b.Icon, b.Variant, b.Size = icPullDown, ui.VariantGhost, ui.SizeXS + if picked { + b.Variant = ui.VariantSecondary + } + return pop.Layout(gtx, b.Layout) + } + if !picked { + return chip(gtx) + } + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(chip), + ui.Gap(2), + layout.Rigid(th.Text(ui.TextXS, run).Mono().Muted().Layout), + ui.Gap(0.5), + layout.Rigid(func(gtx C) D { + b := th.Button(&k.drop, "") + b.Icon, b.Variant, b.Size = icPullX, ui.VariantGhost, ui.SizeIconXS + return v.withTip(gtx, th, p, "allCommits", i18n.T("pulls.pullsFiles.allCommits"), b.Layout) + }), + ) } // commitPickList is the panel: All commits with the count, each commit -// oldest first, then the Shift+click hint. +// oldest first. func (v *pullView) commitPickList(gtx C, th *ui.Theme, d backend.PRDetail) D { k := &v.pick from, to, ranged := k.span(d.URL, d.Commits) diff --git a/native/cmd/lich-native/pulls_commits.go b/native/cmd/lich-native/pulls_commits.go new file mode 100644 index 000000000..7bfda4dc4 --- /dev/null +++ b/native/cmd/lich-native/pulls_commits.go @@ -0,0 +1,72 @@ +package main + +import ( + "strings" + "time" + + "gioui.org/font" + "gioui.org/layout" + + "github.com/lichdotdev/lich/native/backend" + "github.com/lichdotdev/lich/native/i18n" + "github.com/lichdotdev/lich/native/ui" +) + +// commitRows is the Commits tab: a line per commit, its body behind a click. +func (v *pullView) commitRows(gtx C, th *ui.Theme, d backend.PRDetail) []layout.Widget { + if len(d.Commits) == 0 { + return []layout.Widget{func(gtx C) D { return pullsNote(gtx, th, i18n.T("pulls.pullsCommits.none")) }} + } + now := gtx.Now + rows := make([]layout.Widget, len(d.Commits)) + for i, c := range d.Commits { + open := boolOf(v.commitOpen, c.OID) + click := clickableOf(v.commitClicks, c.OID) + body := strings.TrimSpace(c.Body) + rows[i] = func(gtx C) D { + if click.Clicked(gtx) && body != "" { + open.Value = !open.Value + } + line := func(gtx C) D { + return commitRow(gtx, th, c, click, body != "", open.Value, now, func(gtx C) D { return v.viewChanges(gtx, th, d, i) }) + } + if !open.Value { + return line(gtx) + } + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Rigid(line), + layout.Rigid(func(gtx C) D { + gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(overviewProseWidth+2*pullsPadX)) + return layout.Inset{Left: pullsTextX, Right: pullsPadX, Top: ui.Space(0.5), Bottom: ui.Space(2.5)}.Layout(gtx, + th.Text(ui.TextSM, body).Muted().Wrapped().Layout) + }), + ) + } + } + return rows +} + +// commitRow is a commit's line: the chevron when it has a body to open, its +// headline and short oid, view while the pointer is on it, who and when. +func commitRow(gtx C, th *ui.Theme, c backend.PRCommit, click *ui.Clickable, hasBody, open bool, now time.Time, view layout.Widget) D { + return pullsLine(gtx, th, click, false, func(gtx C, th *ui.Theme) D { + narrow := gtx.Constraints.Max.X < gtx.Dp(lineWhoMin) + children := []layout.FlexChild{ + layout.Rigid(inNodeColumn(func(gtx C) D { + if !hasBody { + return D{} + } + return foldIcon(open).Layout(gtx, ui.Space(3.5), th.MutedForeground) + })), + layout.Rigid(layout.Spacer{Width: pullsLineGap}.Layout), + layout.Flexed(1, ui.Spanning(func(gtx C) D { + title := th.Text(ui.TextSM, c.Headline).Weight(font.Medium).Layout + return lineText(gtx, naturalWidth(gtx, title), title, th.Text(ui.TextXS, shortOID(c.OID)).Mono().Muted().Layout) + })), + } + if click.Hovered() { + children = append(children, ui.Gap(2), layout.Rigid(view)) + } + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, append(children, lineWho(th, narrow, authorOf(c), shortAge(c.Date, now))...)...) + }) +} diff --git a/native/cmd/lich-native/pulls_conversation.go b/native/cmd/lich-native/pulls_conversation.go index 8d1932c4e..7faac7803 100644 --- a/native/cmd/lich-native/pulls_conversation.go +++ b/native/cmd/lich-native/pulls_conversation.go @@ -1,12 +1,12 @@ package main import ( - "fmt" - "image" + "path/filepath" "strings" "time" "gioui.org/font" + "gioui.org/io/key" "gioui.org/layout" "gioui.org/widget" @@ -21,7 +21,7 @@ type talkState struct { folds map[string]*ui.Bool foldClicks map[string]*ui.Clickable replying map[string]bool - replyFields map[string]*replyField + replyFields map[string]*widget.Editor replyClicks map[string]*ui.Clickable sendClicks map[string]*ui.Clickable cancelClicks map[string]*ui.Clickable @@ -31,6 +31,12 @@ type talkState struct { editing map[string]bool focusEdit string menus map[string]*ui.MenuState + // over is which entries the pointer is on, by their target's key: their ⋯ + // shows only then. + over map[string]*hoverArea + // hunks are the threads' code as diffs, by thread; cells measures them. + hunks map[string]*chatEditDiff + cells chatDiffCells moreClicks map[string]*ui.Clickable deleting *commentTarget deleteShown commentTarget @@ -40,8 +46,8 @@ type talkState struct { showResolved ui.Bool resolvedTap ui.Clickable comment widget.Editor - commentSize ui.TextareaResize commentSend ui.Clickable + commentDrop ui.Clickable discards map[int]*ui.Clickable edits map[int]*ui.Clickable pendingEdit pendingEdit @@ -53,38 +59,29 @@ type pendingEdit struct { open bool index int editor widget.Editor - resize ui.TextareaResize save, cancel ui.Clickable } func (s *talkState) init() { s.folds, s.foldClicks = map[string]*ui.Bool{}, map[string]*ui.Clickable{} - s.replying, s.replyFields = map[string]bool{}, map[string]*replyField{} + s.replying, s.replyFields = map[string]bool{}, map[string]*widget.Editor{} s.replyClicks, s.sendClicks = map[string]*ui.Clickable{}, map[string]*ui.Clickable{} s.cancelClicks, s.resolveClick = map[string]*ui.Clickable{}, map[string]*ui.Clickable{} s.toSession = map[string]*ui.Clickable{} s.editing, s.menus, s.moreClicks = map[string]bool{}, map[string]*ui.MenuState{}, map[string]*ui.Clickable{} + s.over, s.hunks = map[string]*hoverArea{}, map[string]*chatEditDiff{} s.discards, s.edits = map[int]*ui.Clickable{}, map[int]*ui.Clickable{} } -// replyField is one thread's reply box: its text and the height it was -// dragged to. -type replyField struct { - editor widget.Editor - resize ui.TextareaResize -} - -func (s *talkState) fieldOf(id string) *replyField { - f, ok := s.replyFields[id] +func (s *talkState) editorOf(id string) *widget.Editor { + ed, ok := s.replyFields[id] if !ok { - f = new(replyField) - s.replyFields[id] = f + ed = new(widget.Editor) + s.replyFields[id] = ed } - return f + return ed } -func (s *talkState) editorOf(id string) *widget.Editor { return &s.fieldOf(id).editor } - // talkClicks carries out the clicks that add or drop rows, before the rows // are built. func (v *pullView) talkClicks(gtx C, pending *pendingReview) { @@ -119,28 +116,20 @@ func (e *pendingEdit) clicks(gtx C, pending *pendingReview) { } } -// conversationRows is PullsConversation: the pending review, the timeline, -// the resolved threads behind their count, and the box for a comment on the -// pull request itself. +// conversationRows is everything said on the pull request in one column: the +// timeline, the resolved threads behind their count, the review being written +// and the box for a comment on the pull request itself. func (v *pullView) conversationRows(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, act *pullsAction) []layout.Widget { read := p.store.conversation(p.project.Path, d.Number) - switch { - case read.val == nil && read.err != "": + if read.val == nil { return []layout.Widget{func(gtx C) D { - return th.PanelNotice(i18n.T("pulls.pullsConversation.readFailed", i18n.Args{"error": read.err}), pullsPadX).Layout(gtx) + return talkColumn(gtx, th.Text(ui.TextSM, i18n.T("pulls.pullsConversation.readFailed", i18n.Args{"error": read.err})).Muted().Wrapped().Layout) }} - case read.val == nil: - return []layout.Widget{func(gtx C) D { return th.PanelNotice(i18n.T("pulls.pullsConversation.loading"), pullsPadX).Layout(gtx) }} } items, resolved := conversationTimeline(read.val) now := gtx.Now v.talkClicks(gtx, v.pendingOf(d.URL)) - rows := v.pendingRows(th, v.pendingOf(d.URL)) - if len(items) == 0 && len(resolved) == 0 { - rows = append(rows, func(gtx C) D { - return th.PanelNotice(i18n.T("pulls.pullsConversation.nothingYet"), pullsPadX).Layout(gtx) - }) - } + var rows []layout.Widget for _, it := range items { switch { case it.review != nil: @@ -152,21 +141,31 @@ func (v *pullView) conversationRows(gtx C, th *ui.Theme, p *pullsScreen, d backe target := commentTarget{kind: prComment, id: c.ID, body: c.Body, canEdit: c.CanEdit, canDelete: c.CanDelete} rows = append(rows, v.talkEntry(th, p, "comment:"+c.Date+c.Author, author{c.Author, c.Avatar}, "", target, c.Date, now, act)) default: - t := *it.thread - rows = append(rows, func(gtx C) D { return v.threadCard(gtx, th, p, d, t, act, now) }) + rows = append(rows, v.threadRow(th, p, d, *it.thread, act, now, 0)) } } if len(resolved) > 0 { rows = append(rows, func(gtx C) D { return v.resolvedToggle(gtx, th, len(resolved)) }) if v.talk.showResolved.Value { for _, t := range resolved { - rows = append(rows, func(gtx C) D { return v.threadCard(gtx, th, p, d, t, act, now) }) + rows = append(rows, v.threadRow(th, p, d, t, act, now, pullsTextX-pullsPadX)) } } } + rows = append(rows, v.pendingRows(th, p, v.pendingOf(d.URL))...) return append(rows, func(gtx C) D { return v.commentBox(gtx, th, act) }) } +// talkGap is half the room between two entries. +var talkGap = ui.Space(2.5) + +// talkColumn is an entry of the conversation: the description's column, with +// its half of the room between entries. +func talkColumn(gtx C, w layout.Widget) D { + gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(overviewProseWidth+2*pullsPadX)) + return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: talkGap, Bottom: talkGap}.Layout(gtx, w) +} + func verdictLine(r backend.PRReview) string { if v, ok := reviewVerdict(r.State); ok { return v @@ -180,26 +179,16 @@ func verdictLine(r backend.PRReview) string { func (v *pullView) talkEntry(th *ui.Theme, p *pullsScreen, key string, who author, verdict string, target commentTarget, date string, now time.Time, act *pullsAction) layout.Widget { body := strings.TrimSpace(target.body) return func(gtx C) D { - editing := v.talk.isEditing(gtx, target) - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(3), Bottom: ui.Space(1)}.Layout(gtx, func(gtx C) D { - return p.withAvatar(gtx, th, who, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return v.commentHead(gtx, th, p, target, func(gtx C) D { return byline(gtx, th, who.login, verdict, date, now) }) - }), - layout.Rigid(func(gtx C) D { - if !editing && body == "" { - return D{} - } - return layout.Inset{Top: ui.Space(1)}.Layout(gtx, func(gtx C) D { - if editing { - return v.editBox(gtx, th, target, act) - } - return v.md.Layout(gtx, th, key, body, act.open) - }) - }), - ) - }) + content := func(gtx C) D { return v.md.Layout(gtx, th, key, body, act.open) } + switch { + case v.talk.isEditing(gtx, target): + content = func(gtx C) D { return v.editBox(gtx, th, target, act) } + case body == "": + content = nil + } + return talkColumn(gtx, func(gtx C) D { + head := func(gtx C) D { return byline(gtx, th, who.login, verdict, date, now) } + return v.comment(gtx, th, p, target, who, head, content) }) } } @@ -213,400 +202,117 @@ func byline(gtx C, th *ui.Theme, author, verdict, date string, now time.Time) D if verdict != "" { children = append(children, ui.Gap(1.5), layout.Rigid(th.Text(ui.TextSM, verdict).Muted().Layout)) } - if at := parsedTime(date); !at.IsZero() { - children = append(children, ui.Gap(2), layout.Rigid(th.Text(ui.TextXS, agoLabel(at.Unix(), now)).Muted().Layout)) + if date != "" { + children = append(children, ui.Gap(1.5), layout.Rigid(th.Text(ui.TextXS, shortAge(date, now)).Mono().Muted().Layout)) } return layout.Flex{Alignment: layout.Baseline}.Layout(gtx, children...) } -// threadCard is ReviewThread: the anchor and its badges over GitHub's hunk, -// the comments, then Reply and Resolve; a resolved thread starts folded. -func (v *pullView) threadCard(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, t backend.PRReviewThread, act *pullsAction, now time.Time) D { - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(3)}.Layout(gtx, func(gtx C) D { - return v.threadBox(gtx, th, p, d, t, act, now) - }) -} - -// threadBox is the thread's card itself, folded to its header or open; the -// Conversation tab and the diff share its fold. -func (v *pullView) threadBox(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, t backend.PRReviewThread, act *pullsAction, now time.Time) D { - s := &v.talk - fold := boolOf(s.folds, t.ID) - if _, seen := s.foldClicks[t.ID]; !seen { - fold.Value = !t.IsResolved - } - foldClick := clickableOf(s.foldClicks, t.ID) - if foldClick.Clicked(gtx) { - fold.Value = !fold.Value - } - return layout.Background{}.Layout(gtx, - func(gtx C) D { return ui.Fill(gtx, th.Sidebar, ui.RadiusMD) }, - func(gtx C) D { - on := th.On(th.Sidebar) - return layout.UniformInset(ui.Space(3)).Layout(gtx, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return foldClick.Layout(gtx, func(gtx C) D { return threadHeader(gtx, on, t, fold.Value, p.threadSentLabel(t.ID)) }) - }), - layout.Rigid(func(gtx C) D { - if !fold.Value { - return D{} - } - return v.threadBody(gtx, on, p, d, t, act, now) - }), - ) - }) - }) -} - -func threadHeader(gtx C, th *ui.Theme, t backend.PRReviewThread, open bool, sent string) D { - chevron := icPullRight - if open { - chevron = icPullDown - } - start := t.StartLine - if start == t.Line { - start = 0 - } - anchor := lineAnchor(start, t.Line) - children := []layout.FlexChild{ - layout.Rigid(func(gtx C) D { return chevron.Layout(gtx, ui.Space(3.5), th.MutedForeground) }), - ui.Gap(1.5), - layout.Flexed(1, func(gtx C) D { - return th.Text(ui.TextXS, t.Path+" · "+anchor).Mono().Truncated().Layout(gtx) - }), - } - if t.IsOutdated { - children = append(children, ui.Gap(2), layout.Rigid(th.Text(ui.TextXS, i18n.T("pulls.pullsConversation.outdated")).In(th.ToneWait).Layout)) - } - if sent != "" && !t.IsResolved { - children = append(children, ui.Gap(2), layout.Rigid(th.Text(ui.TextXS, sent).Muted().Layout)) - } - if t.IsResolved { - children = append(children, ui.Gap(2), layout.Rigid(func(gtx C) D { - return pullState(gtx, th, icPullCheck, i18n.T("pulls.reviewThread.resolved"), th.TonePass) - })) - } - children = append(children, ui.Gap(2), layout.Rigid(th.Text(ui.TextXS, fmt.Sprint(len(t.Comments))).Muted().Layout)) - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, children...) -} - -func (v *pullView) threadBody(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, t backend.PRReviewThread, act *pullsAction, now time.Time) D { - var rows []layout.FlexChild - if len(t.Comments) > 0 && t.Comments[0].DiffHunk != "" { - rows = append(rows, layout.Rigid(func(gtx C) D { - return layout.Inset{Top: ui.Space(2)}.Layout(gtx, func(gtx C) D { return hunkTail(gtx, th, t.Comments[0].DiffHunk) }) - })) - } - editing := false - for i, c := range t.Comments { - target := threadTarget(t, c) - editing = v.talk.isEditing(gtx, target) || editing - if i > 0 { - rows = append(rows, layout.Rigid(func(gtx C) D { - return layout.Spacer{Height: ui.Space(2.5)}.Layout(gtx) - })) - } - rows = append(rows, layout.Rigid(func(gtx C) D { - return layout.Inset{Top: ui.Space(2.5)}.Layout(gtx, func(gtx C) D { return v.threadComment(gtx, th, p, target, c, act, now) }) - })) - } - if !editing { - rows = append(rows, layout.Rigid(func(gtx C) D { - return layout.Inset{Top: ui.Space(2.5)}.Layout(gtx, func(gtx C) D { return v.threadActions(gtx, th, p, d, t, act) }) - })) - } - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, rows...) -} - -// lineAnchor names the line a comment sits on, or the lines it spans from a -// positive start. -func lineAnchor(start, line int) string { - if start > 0 { - return i18n.T("pulls.pullsConversation.lines", i18n.Args{"start": start, "end": line}) - } - return i18n.T("pulls.pullsConversation.line", i18n.Args{"line": line}) -} - -// hunkLines is ThreadHunk's tail: the last lines of GitHub's hunk, the ones -// the thread is about. -const hunkLines = 4 - -// hunkTint is how strongly an added or removed line tints its row, and -// hunkTab what a tab expands to: the mono font has no glyph for one. -const ( - hunkTint = 0.12 - hunkTab = " " -) - -// hunkTail sits the code on the window's background, apart from the -// comments on the thread's surface. -func hunkTail(gtx C, th *ui.Theme, hunk string) D { - lines := strings.Split(strings.TrimRight(hunk, "\n"), "\n") - lines = lines[max(0, len(lines)-hunkLines):] - var children []layout.FlexChild - for _, line := range lines { - children = append(children, layout.Rigid(func(gtx C) D { return hunkLine(gtx, th, line) })) - } - return layout.Background{}.Layout(gtx, - func(gtx C) D { return ui.Fill(gtx, th.Background, ui.RadiusSM) }, - func(gtx C) D { - return layout.UniformInset(ui.Space(2)).Layout(gtx, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, children...) - }) - }) -} - -func hunkLine(gtx C, th *ui.Theme, line string) D { - fg, tint := th.MutedForeground, th.Background - switch { - case strings.HasPrefix(line, "+"): - fg, tint = th.TonePass, ui.MixOKLab(th.Background, th.TonePass, hunkTint) - case strings.HasPrefix(line, "-"): - fg, tint = th.Destructive, ui.MixOKLab(th.Background, th.Destructive, hunkTint) - } - gtx.Constraints.Min.X = gtx.Constraints.Max.X - return layout.Background{}.Layout(gtx, - func(gtx C) D { return ui.Fill(gtx, tint, 0) }, - func(gtx C) D { - return th.Text(ui.TextXS, strings.ReplaceAll(line, "\t", hunkTab)).Mono().In(fg).Truncated().Layout(gtx) - }) -} - -// threadActions is Reply and Resolve, with Send to session at the end, or -// the reply box while one is written. -func (v *pullView) threadActions(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, t backend.PRReviewThread, act *pullsAction) D { - s := &v.talk - reply, resolve := clickableOf(s.replyClicks, t.ID), clickableOf(s.resolveClick, t.ID) - if reply.Clicked(gtx) { - s.replying[t.ID] = true - gtx.Execute(keyFocus(s.editorOf(t.ID))) - } - if resolve.Clicked(gtx) { - act.resolve = &threadResolve{id: t.ID, resolved: !t.IsResolved} - } - if clickableOf(s.cancelClicks, t.ID).Clicked(gtx) { - s.replying[t.ID] = false - } - if s.replying[t.ID] { - return v.replyBox(gtx, th, d, t, act) - } - busy := v.busyNow() - label := i18n.T("pulls.reviewThread.resolve") - if t.IsResolved { - label = i18n.T("pulls.reviewThread.reopen") - } - replyB := th.Button(reply, i18n.T("pulls.reviewThread.reply")) - replyB.Variant, replyB.Size = ui.VariantOutline, ui.SizeSM - resolveB := th.Button(resolve, label) - resolveB.Size, resolveB.Disabled = ui.SizeSM, busy == "resolve:"+t.ID - if t.IsResolved { - resolveB.Variant = ui.VariantOutline - } - // Resolve settles the thread: filled, at the line's end - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { return D{Size: image.Pt(gtx.Constraints.Min.X, 0)} }), - layout.Rigid(replyB.Layout), ui.Gap(2), - layout.Rigid(func(gtx C) D { return v.toSessionButton(gtx, th, p, d, t, act) }), ui.Gap(2), - layout.Rigid(resolveB.Layout)) -} - -// toSessionButton is Send to session, Open in session while the branch's -// checkout has no session; nothing on a thread that cannot go. -func (v *pullView) toSessionButton(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, t backend.PRReviewThread, act *pullsAction) D { - if !canSendThreads(d) || !p.threadSendable(t) { - return D{} - } - click := clickableOf(v.talk.toSession, t.ID) - busy := v.busyNow() == "threads" - if click.Clicked(gtx) && !busy { - act.threads = []backend.PRReviewThread{t} - } - label, tip := i18n.T("pulls.pulls.openInSession"), "" - if id, _ := p.reviewSession(d); id != "" { - label, tip = i18n.T("pulls.threadSend.send"), i18n.T("pulls.threadSend.sendTip", i18n.Args{"name": p.sessionLabel(id)}) - } - b := th.Button(click, label) - b.Icon, b.Variant, b.Size, b.Disabled = icPullSession, ui.VariantGhost, ui.SizeSM, busy - return v.withTip(gtx, th, p, "toSession:"+t.ID, tip, b.Layout) -} - -// sendOpenThreads is Send open threads, beside the hand-off in the header: -// every open thread not yet sent, in one prompt; nil when there is none. -func (v *pullView) sendOpenThreads(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, busy string, act *pullsAction) layout.Widget { - threads := p.sendableThreads(p.store.conversation(p.project.Path, d.Number).val) - if !canSendThreads(d) || len(threads) == 0 { - return nil - } - if v.talk.allToSession.Clicked(gtx) && busy == "" { - act.threads = threads - } - return func(gtx C) D { - b := th.Button(&v.talk.allToSession, i18n.T("pulls.threadSend.sendAll", i18n.Args{"count": len(threads)})) - b.Icon, b.Variant, b.Size, b.Disabled = icPullSession, ui.VariantOutline, ui.SizeSM, busy != "" - return b.Layout(gtx) - } -} - -func (v *pullView) replyBox(gtx C, th *ui.Theme, d backend.PRDetail, t backend.PRReviewThread, act *pullsAction) D { - s := &v.talk - ed := s.editorOf(t.ID) - send, cancel := clickableOf(s.sendClicks, t.ID), clickableOf(s.cancelClicks, t.ID) - submit := send.Clicked(gtx) || ctrlEnter(gtx, ed) - body := strings.TrimSpace(ed.Text()) - if submit && body != "" && len(t.Comments) > 0 { - act.reply = &threadReply{commentID: t.Comments[len(t.Comments)-1].ID, body: body, thread: t.ID} - } - busy := v.busyNow() == "reply:"+t.ID - label := i18n.T("pulls.reviewThread.reply") - if busy { - label = i18n.T("pulls.commentBox.sending") - } - sendB := th.Button(send, label) - sendB.Size, sendB.Disabled, sendB.Keys = ui.SizeSM, body == "" || busy, ctrlEnterCap() - cancelB := th.Button(cancel, i18n.T("common.action.cancel")) - cancelB.Size, cancelB.Variant = ui.SizeSM, ui.VariantGhost - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - ta := th.Textarea(ed, i18n.T("pulls.reviewThread.replyPlaceholder")) - ta.Resize = &s.fieldOf(t.ID).resize - return ta.Layout(gtx) - }), - ui.VGap(2), - layout.Rigid(func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, layout.Flexed(1, func(gtx C) D { return D{Size: image.Pt(gtx.Constraints.Min.X, 0)} }), layout.Rigid(cancelB.Layout), ui.Gap(2), layout.Rigid(sendB.Layout)) - }), - ) -} - +// resolvedToggle is the line that folds the resolved threads. func (v *pullView) resolvedToggle(gtx C, th *ui.Theme, n int) D { s := &v.talk label := i18n.T("pulls.pullsConversation.resolved", i18n.Args{"count": n}) - chevron := icPullRight - if s.showResolved.Value { - chevron = icPullDown - } - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(4)}.Layout(gtx, func(gtx C) D { - return s.resolvedTap.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { return chevron.Layout(gtx, ui.Space(3.5), th.MutedForeground) }), - ui.Gap(1.5), - layout.Rigid(th.Text(ui.TextXS, label).Muted().Layout), - ) - }) + gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(overviewProseWidth+2*pullsPadX)) + return pullsLine(gtx, th, &s.resolvedTap, false, func(gtx C, th *ui.Theme) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(inNodeColumn(func(gtx C) D { return foldIcon(s.showResolved.Value).Layout(gtx, ui.Space(3.5), th.MutedForeground) })), + layout.Rigid(layout.Spacer{Width: pullsLineGap}.Layout), + layout.Rigid(th.Text(ui.TextSM, label).Muted().Layout), + ) }) } -// commentBox is the box for a comment on the pull request as a whole. +// commentBox is the box for a comment on the pull request as a whole, one +// line until it is written in. func (v *pullView) commentBox(gtx C, th *ui.Theme, act *pullsAction) D { s := &v.talk + if s.commentDrop.Clicked(gtx) { + s.comment.SetText("") + gtx.Execute(key.FocusCmd{}) + } body := strings.TrimSpace(s.comment.Text()) if (s.commentSend.Clicked(gtx) || ctrlEnter(gtx, &s.comment)) && body != "" { act.comment = body } - busy := v.busyNow() == "comment" - label := i18n.T("pulls.pullsConversation.comment") - if busy { - label = i18n.T("pulls.commentBox.sending") + box := writeBox{editor: &s.comment, placeholder: i18n.T("pulls.pullsConversation.commentOn"), action: i18n.T("pulls.pullsConversation.comment"), + send: &s.commentSend, cancel: &s.commentDrop, busy: v.busyNow() == "comment", + resting: s.comment.Len() == 0 && !gtx.Focused(&s.comment)} + if box.busy { + box.action = i18n.T("pulls.commentBox.sending") } - send := th.Button(&s.commentSend, label) - send.Size, send.Disabled, send.Keys = ui.SizeSM, body == "" || busy, ctrlEnterCap() - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(5), Bottom: ui.Space(5)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(th.SectionHeading(i18n.T("pulls.pullsConversation.commentOn")).Layout), - ui.VGap(2), - layout.Rigid(func(gtx C) D { - ta := th.Textarea(&s.comment, i18n.T("pulls.pullsConversation.commentPlaceholder")) - ta.Resize = &s.commentSize - return ta.Layout(gtx) - }), - ui.VGap(2), - layout.Rigid(func(gtx C) D { - gtx.Constraints.Min.X = gtx.Constraints.Max.X - return layout.Flex{}.Layout(gtx, layout.Flexed(1, func(gtx C) D { return D{Size: image.Pt(gtx.Constraints.Min.X, 0)} }), layout.Rigid(send.Layout)) - }), - ) + return talkColumn(gtx, func(gtx C) D { + return layout.Inset{Top: talkGap, Bottom: talkGap}.Layout(gtx, func(gtx C) D { return box.layout(gtx, th) }) }) } -// pendingRows is the review being written: each line comment, discardable, -// until the review is submitted. -func (v *pullView) pendingRows(th *ui.Theme, r *pendingReview) []layout.Widget { +// pendingRows is the review being written: each line comment as an entry of +// the viewer's own, until the review is submitted. +func (v *pullView) pendingRows(th *ui.Theme, p *pullsScreen, r *pendingReview) []layout.Widget { comments := r.snapshot() - if len(comments) == 0 { - return nil - } - rows := []layout.Widget{func(gtx C) D { - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(4)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Baseline}.Layout(gtx, - layout.Rigid(th.SectionHeading(i18n.T("pulls.pullsConversation.pendingHead")).Layout), - ui.Gap(2), - layout.Rigid(th.Text(ui.TextXS, i18n.T("pulls.pullsConversation.pendingNote")).Muted().Layout), - ) - }) - }} + rows := make([]layout.Widget, len(comments)) for i, c := range comments { - rows = append(rows, func(gtx C) D { return v.pendingRow(gtx, th, i, c) }) + rows[i] = func(gtx C) D { + return talkColumn(gtx, func(gtx C) D { return v.pendingEntry(gtx, th, p, i, c) }) + } } return rows } -// pendingRow is one line comment of the review being written, with Edit and -// Discard, or the box rewording it. -func (v *pullView) pendingRow(gtx C, th *ui.Theme, i int, c backend.ReviewComment) D { - s := &v.talk - discard, edit := clickableAt(s.discards, i), clickableAt(s.edits, i) - editing := s.pendingEdit.open && s.pendingEdit.index == i - body := func(gtx C) D { return th.Text(ui.TextSM, c.Body).Wrapped().Layout(gtx) } - if editing { - body = func(gtx C) D { return v.pendingEditBox(gtx, th) } - } - editB := th.Button(edit, i18n.T("pulls.pullsConversation.edit")) - editB.Size, editB.Variant = ui.SizeSM, ui.VariantGhost - discardB := th.Button(discard, i18n.T("pulls.pullsConversation.discard")) - discardB.Size, discardB.Variant = ui.SizeSM, ui.VariantDestructive - anchor := lineAnchor(c.StartLine, c.Line) - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(2)}.Layout(gtx, func(gtx C) D { - return layout.Flex{}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(th.Text(ui.TextXS, c.Path+" · "+anchor).Mono().Muted().Layout), - layout.Rigid(body), - ) - }), - layout.Rigid(func(gtx C) D { - if editing { - return D{} - } - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, layout.Rigid(editB.Layout), ui.Gap(1), layout.Rigid(discardB.Layout)) - }), - ) - }) -} - -// pendingEditBox is the reply box's shape over the comment being reworded; -// pendingEdit.clicks carries out its buttons. -func (v *pullView) pendingEditBox(gtx C, th *ui.Theme) D { - e := &v.talk.pendingEdit - saveB := th.Button(&e.save, i18n.T("pulls.pullsConversation.save")) - saveB.Size, saveB.Disabled = ui.SizeSM, strings.TrimSpace(e.editor.Text()) == "" - cancelB := th.Button(&e.cancel, i18n.T("common.action.cancel")) - cancelB.Size, cancelB.Variant = ui.SizeSM, ui.VariantGhost - return layout.Inset{Top: ui.Space(1)}.Layout(gtx, func(gtx C) D { +// pendingEntry is one line comment of the review being written, with Edit and +// Discard beside the line it is on, or the box rewording it. +func (v *pullView) pendingEntry(gtx C, th *ui.Theme, p *pullsScreen, i int, c backend.ReviewComment) D { + you := author{login: i18n.T("pulls.pullsConversation.you")} + return p.withAvatar(gtx, th, you, func(gtx C) D { return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { - ta := th.Textarea(&e.editor, "") - ta.Resize = &e.resize - return ta.Layout(gtx) + gtx.Constraints.Min.Y = gtx.Dp(authorAvatarSize) + return layout.W.Layout(gtx, func(gtx C) D { + return byline(gtx, th, you.login, i18n.T("pulls.pullsConversation.pendingNote"), "", gtx.Now) + }) }), - ui.VGap(2), + ui.VGap(0.5), layout.Rigid(func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, layout.Rigid(saveB.Layout), ui.Gap(2), layout.Rigid(cancelB.Layout)) + return v.pendingBody(gtx, th, i, c, func(gtx C) D { return fileAnchor(gtx, th, c.Path, lineAnchor(c.StartLine, c.Line)) }) }), ) }) } +// pendingBody is a pending comment's text over where, what says where it +// stands, and its Edit and Discard; or the box rewording it. +func (v *pullView) pendingBody(gtx C, th *ui.Theme, i int, c backend.ReviewComment, where layout.Widget) D { + s := &v.talk + if e := &s.pendingEdit; e.open && e.index == i { + return writeBox{editor: &e.editor, action: i18n.T("pulls.pullsConversation.save"), send: &e.save, cancel: &e.cancel}.layout(gtx, th) + } + edit := th.Button(clickableAt(s.edits, i), i18n.T("pulls.pullsConversation.edit")) + edit.Size, edit.Variant = ui.SizeXS, ui.VariantGhost + discard := th.Button(clickableAt(s.discards, i), i18n.T("pulls.pullsConversation.discard")) + discard.Size, discard.Variant = ui.SizeXS, ui.VariantGhost + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Rigid(th.Text(ui.TextSM, c.Body).Wrapped().Layout), + ui.VGap(1), + layout.Rigid(func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Flexed(1, ui.Spanning(where)), + ui.Gap(2), layout.Rigid(edit.Layout), + ui.Gap(1), layout.Rigid(discard.Layout), + ) + }), + ) +} + +// fileAnchor is a file's icon and name with the lines a comment is on. +func fileAnchor(gtx C, th *ui.Theme, path, lines string) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(th.FileIcon(path, ui.Space(3.5)).Layout), + ui.Gap(1.5), + layout.Rigid(th.Text(ui.TextXS, filepath.Base(path)).Weight(font.Medium).Layout), + ui.Gap(1.5), + layout.Rigid(th.Text(ui.TextXS, lines).Mono().Muted().Layout), + ) +} + func (v *pullView) pendingOf(url string) *pendingReview { r, ok := v.pending[url] if !ok { diff --git a/native/cmd/lich-native/pulls_edit.go b/native/cmd/lich-native/pulls_edit.go index 6f19399a5..cea289af7 100644 --- a/native/cmd/lich-native/pulls_edit.go +++ b/native/cmd/lich-native/pulls_edit.go @@ -1,17 +1,12 @@ package main import ( - "io" "strings" "time" - "gioui.org/font" - "gioui.org/io/clipboard" "gioui.org/io/key" - "gioui.org/layout" "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" @@ -38,8 +33,6 @@ type editState struct { preview ui.IconActionState save ui.Clickable cancel ui.Clickable - more ui.Clickable - menu ui.MenuState // heldTitle and heldBody are what was sent, shown until a read caught up. heldTitle, heldBody heldEdit @@ -148,36 +141,6 @@ func (v *pullView) editClicks(gtx C, d backend.PRDetail, act *pullsAction) { } } -// pullTitle is the title with the pencil that opens the edit right after its -// last word (none on a GitLab merge request), or the field editing it. -func (v *pullView) pullTitle(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, act *pullsAction) D { - s := &v.edit - return layout.Flex{}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { - if s.editing(d) { - return v.titleField(gtx, th, d, act) - } - if v.forge == api.ForgeGitLab { - l := th.Text(pullsTitleSize, d.Title).Weight(font.SemiBold) - l.MaxLines = 0 - return l.Layout(gtx) - } - return layout.Flex{}.Layout(gtx, - layout.Rigid(func(gtx C) D { - gtx.Constraints.Max.X = max(gtx.Constraints.Max.X-gtx.Dp(ui.Space(7)), 0) - l := th.Text(pullsTitleSize, d.Title).Weight(font.SemiBold) - l.MaxLines = 0 - return l.Layout(gtx) - }), - ui.Gap(1), - layout.Rigid(func(gtx C) D { - return th.IconAction(p.root, &s.open, icPullEdit, i18n.T("pulls.pullRequestView.edit"), false).Layout(gtx) - }), - ) - }), - ) -} - // titleField is the title being edited. Enter and Tab go on to the // description, Ctrl+Enter saves; Escape does nothing, so a stray one never // throws a long description away. @@ -208,7 +171,7 @@ func (v *pullView) titleField(gtx C, th *ui.Theme, d backend.PRDetail, act *pull gtx.Execute(keyFocus(&s.body)) } in := th.Input(&s.title, "") - in.TextSize, in.Disabled = pullsTitleSize, busy + in.Height, in.Disabled = ui.Space(8), busy return in.Layout(gtx) } @@ -219,49 +182,17 @@ func (v *pullView) editActions(gtx C, th *ui.Theme) D { s := &v.edit busy := v.busyNow() == editBusy cancel := th.Button(&s.cancel, i18n.T("common.action.cancel")) - cancel.Variant, cancel.Size, cancel.Disabled = ui.VariantOutline, ui.SizeSM, busy + cancel.Variant, cancel.Size, cancel.Disabled = ui.VariantGhost, ui.SizeSM, busy label := i18n.T("pulls.pullsOverview.save") if busy { label = i18n.T("pulls.pullsOverview.saving") } save := th.Button(&s.save, label) - save.Size, save.Disabled = ui.SizeSM, busy + save.Size, save.Disabled, save.Keys = ui.SizeSM, busy, ctrlEnterCap() return ui.Wrap{GapX: ui.Space(2), GapY: ui.Space(2), Justify: ui.JustifyEnd}.Layout(gtx, ui.WrapItem(cancel.Layout), ui.WrapItem(save.Layout)) } -// descriptionHeading is the Description heading, with the ⋯ that copies the -// description, or while it is edited the toggle that previews it. -func (v *pullView) descriptionHeading(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail) D { - s := &v.edit - heading := th.SectionHeading(i18n.T("pulls.pullsOverview.description")).Layout - if s.editing(d) { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, heading), - layout.Rigid(func(gtx C) D { return v.previewToggle(gtx, th, p) }), - ) - } - var copied string - entries := []ui.MenuEntry{ - {Label: i18n.T("pulls.pullsOverview.copyLink"), OnClick: func() { copied = d.URL }}, - {Label: i18n.T("pulls.pullsOverview.copyMarkdown"), Disabled: strings.TrimSpace(d.Body) == "", OnClick: func() { copied = d.Body }}, - } - b := th.Button(&s.more, "") - b.Icon, b.Variant, b.Size = icPullMore, ui.VariantGhost, ui.SizeIconXS - dims := layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, heading), - layout.Rigid(func(gtx C) D { - return v.withTip(gtx, th, p, "description", i18n.T("pulls.reviewThread.more"), func(gtx C) D { - return th.DropdownMenu(p.root, &s.menu, entries).Layout(gtx, b.Layout) - }) - }), - ) - if copied != "" { - gtx.Execute(clipboard.WriteCmd{Type: "application/text", Data: io.NopCloser(strings.NewReader(copied))}) - } - return dims -} - // previewToggle swaps the description's editor for its Markdown rendered and // back, as a Markdown file's card does in the Review. func (v *pullView) previewToggle(gtx C, th *ui.Theme, p *pullsScreen) D { @@ -293,6 +224,7 @@ func (v *pullView) descriptionEditor(gtx C, th *ui.Theme, d backend.PRDetail, ac ta := th.Textarea(&s.body, i18n.T("pulls.pullsOverview.descriptionPlaceholder")) ta.Mono, ta.Disabled, ta.Scrollbar = true, busy, &s.bodyBar ta.MinHeight, ta.MaxHeight = h, h + ta.PadRight = previewInset + ui.Space(6) + previewInset return ta.Layout(gtx) } diff --git a/native/cmd/lich-native/pulls_files.go b/native/cmd/lich-native/pulls_files.go index 8738c467e..e50483de6 100644 --- a/native/cmd/lich-native/pulls_files.go +++ b/native/cmd/lich-native/pulls_files.go @@ -147,14 +147,16 @@ func (v *pullView) filesTab(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDet if target != d.URL { files.comments.move(d.URL, target) } - files.th, files.light, files.code, files.target, files.checkout = th, in.light, in.code, target, p.prCheckout(d) + files.th, files.light, files.code, files.target, files.checkout = th.On(th.Sidebar), in.light, in.code, target, p.prCheckout(d) files.inject, files.submit = in.injector(session), in.submitter(session) switch { // The cards fold by their ticks when first read, so they wait for them. case !read.loaded, !viewed.loaded: return v.skeletonFiles(gtx, th) case read.err != "": - notice := th.PanelNotice(i18n.T("pulls.pullsFiles.loadFailed", i18n.Args{"error": read.err}), pullsPadX).Layout + notice := func(gtx C) D { + return pullsNote(gtx, th, i18n.T("pulls.pullsFiles.loadFailed", i18n.Args{"error": read.err})) + } if key == d.URL { return notice(gtx) } @@ -214,7 +216,8 @@ func (v *pullView) filesBody(gtx C, th *ui.Theme) D { if v.tree.hidden { return D{} } - return th.VerticalRule(gtx) + // The room treeHandle starts after. + return D{Size: image.Pt(gtx.Dp(1), gtx.Constraints.Max.Y)} }), layout.Flexed(1, func(gtx C) D { gtx.Constraints.Min = gtx.Constraints.Max @@ -230,7 +233,7 @@ func (v *pullView) filesBody(gtx C, th *ui.Theme) D { return dims } -// treeHandle lays the tree's resize handle out past the rule, over the +// treeHandle lays the tree's resize handle out past the tree, over the // cards' margin: on the tree's own edge its lit strip would cover the // tree's scrollbar. Its box starts at the tree's left edge, which a drag // leaves in place, so the handle reads the drag as a right-edge panel's. @@ -289,7 +292,7 @@ func (v *pullView) treeLayout(gtx C, th *ui.Theme) D { // filesToolbar is the tree's toggle, the commit picker, the files changed // since the review and "N of M viewed" (or, for picked commits, which ones // and that they take no comment or tick), and the dock's split and -// collapse-all toggles; the diff's size sits on the tab strip. +// collapse-all toggles. func (v *pullView) filesToolbar(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail) D { files := v.files if v.tree.toggle.Click.Clicked(gtx) { @@ -299,26 +302,28 @@ func (v *pullView) filesToolbar(gtx C, th *ui.Theme, p *pullsScreen, d backend.P if v.tree.hidden { treeIcon, treeLabel = icPullShow, i18n.T("pulls.pullsFiles.showTree") } - return layout.Inset{Left: ui.Space(2), Right: ui.Space(2), Top: ui.Space(1.5), Bottom: ui.Space(1.5)}.Layout(gtx, func(gtx C) D { + return layout.Inset{Left: ui.Space(3), Right: ui.Space(3), Bottom: 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 th.IconAction(v.root, &v.tree.toggle, treeIcon, treeLabel, false).Layout(gtx) }), ui.Gap(2), layout.Rigid(func(gtx C) D { return v.commitPicker(gtx, th, p, d) }), - ui.Gap(2), - layout.Rigid(func(gtx C) D { return v.filesProgress(gtx, th) }), - layout.Flexed(1, func(gtx C) D { return D{Size: gtx.Constraints.Min} }), + ui.Gap(3), + layout.Flexed(1, ui.Spanning(func(gtx C) D { return v.filesProgress(gtx, th) })), layout.Rigid(func(gtx C) D { return files.layoutActions(gtx, th) }), ) }) } -// filesProgress is the files changed since the review and "N of M viewed", -// or for picked commits the run and that it takes no comment or tick. +// filesProgress is "N of M viewed", the files changed since the review once +// any did, or for picked commits that they take no comment or tick. func (v *pullView) filesProgress(gtx C, th *ui.Theme) D { files := v.files - if base := files.pr.base; base != "" { - run := shortOID(base) + ".." + shortOID(files.pr.head) - return th.Text(ui.TextXS, i18n.T("pulls.pullsFiles.rangeNote", i18n.Args{"range": run})).Muted().Layout(gtx) + note := func(text string) D { return th.Text(ui.TextXS, text).Muted().Layout(gtx) } + if files.pr.base != "" { + return note(i18n.T("pulls.pullsFiles.rangeNote")) + } + if n, at := files.pr.viewed.changedSince(files.order, func(path string) string { return files.cards[path].gitHash }); n > 0 { + return note(i18n.T("pulls.pullsFiles.filesChangedSinceReview", i18n.Args{"count": n, "date": reviewDay(at, gtx.Now)})) } viewed := 0 for _, path := range files.order { @@ -326,22 +331,7 @@ func (v *pullView) filesProgress(gtx C, th *ui.Theme) D { viewed++ } } - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { return v.changedSinceReview(gtx, th) }), - layout.Rigid(th.Text(ui.TextXS, i18n.T("pulls.pullsFiles.viewed", i18n.Args{"viewed": viewed, "total": len(files.order)})).Muted().Layout), - ) -} - -// changedSinceReview is how many files moved since they were ticked and the -// day of the last tick, nothing while none did. -func (v *pullView) changedSinceReview(gtx C, th *ui.Theme) D { - files := v.files - n, at := files.pr.viewed.changedSince(files.order, func(path string) string { return files.cards[path].gitHash }) - if n == 0 { - return D{} - } - text := i18n.T("pulls.pullsFiles.filesChangedSinceReview", i18n.Args{"count": n, "date": reviewDay(at, gtx.Now)}) - return layout.Inset{Right: ui.Space(3)}.Layout(gtx, th.Text(ui.TextXS, text).Muted().Layout) + return note(i18n.T("pulls.pullsFiles.viewed", i18n.Args{"viewed": viewed, "total": len(files.order)})) } // inlineFrame is what the threads hung in the diff are drawn with this @@ -405,47 +395,46 @@ func (v *pullView) inlineThread(gtx C, id string) D { if len(t.Comments) > 0 { t.Comments[0].DiffHunk = "" } - return composerSlot.Layout(gtx, func(gtx C) D { return v.threadBox(gtx, f.th, f.p, f.d, t, f.act, f.now) }) + return threadSlot.Layout(gtx, func(gtx C) D { return v.threadInline(gtx, f.th.On(f.th.Sidebar), t) }) } return D{} } +// threadSlot is the room a thread or a pending comment keeps in the diff. +var threadSlot = layout.Inset{Left: ui.Space(3), Right: ui.Space(3), Top: ui.Space(2.5), Bottom: ui.Space(2.5)} + +// threadInline is a thread on the code's own surface: what was said, under the +// line that folds it once it is resolved or folded. +func (v *pullView) threadInline(gtx C, th *ui.Theme, t backend.PRReviewThread) D { + f := v.inline + open := v.threadOpen(gtx, t) + talk := func(gtx C) D { return v.threadTalk(gtx, th, f.p, f.d, t, f.act, f.now) } + if open && !t.IsResolved { + return talk(gtx) + } + fact := threadFact(f.p, t, open) + if t.IsResolved { + fact = i18n.T("pulls.reviewThread.resolved") + } + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Rigid(func(gtx C) D { + return th.NavRow(gtx, v.talk.foldClicks[t.ID], false, pullsLineHeight, 0, func(gtx C, th *ui.Theme) D { + return threadLine(gtx, th, t, open, fact, false) + }) + }), + layout.Rigid(func(gtx C) D { + if !open { + return D{} + } + return layout.Inset{Top: ui.Space(1)}.Layout(gtx, talk) + }), + ) +} + // inlinePending is a comment waiting for the review to be submitted, with // the Conversation tab's Edit and Discard: talkClicks carries them out. func (v *pullView) inlinePending(gtx C, i int, c backend.ReviewComment) D { - th := v.inline.th - s := &v.talk - editing := s.pendingEdit.open && s.pendingEdit.index == i - return composerSlot.Layout(gtx, func(gtx C) D { - return layout.Background{}.Layout(gtx, - func(gtx C) D { return ui.Fill(gtx, th.Sidebar, ui.RadiusMD) }, - func(gtx C) D { - on := th.On(th.Sidebar) - return layout.UniformInset(ui.Space(3)).Layout(gtx, func(gtx C) D { - body := func(gtx C) D { return on.Text(ui.TextSM, c.Body).Wrapped().Layout(gtx) } - if editing { - body = func(gtx C) D { return v.pendingEditBox(gtx, on) } - } - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, on.Text(ui.TextXS, i18n.T("pulls.pullsConversation.pendingNote")).In(on.ToneWait).Layout), - layout.Rigid(func(gtx C) D { - if editing { - return D{} - } - editB := on.Button(clickableAt(s.edits, i), i18n.T("pulls.pullsConversation.edit")) - editB.Size, editB.Variant = ui.SizeSM, ui.VariantGhost - discardB := on.Button(clickableAt(s.discards, i), i18n.T("pulls.pullsConversation.discard")) - discardB.Size, discardB.Variant = ui.SizeSM, ui.VariantDestructive - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, layout.Rigid(editB.Layout), ui.Gap(1), layout.Rigid(discardB.Layout)) - }), - ) - }), - ui.VGap(1), - layout.Rigid(body), - ) - }) - }) - }) + th := v.inline.th.On(v.inline.th.Sidebar) + note := th.Text(ui.TextXS, i18n.T("pulls.pullsConversation.pendingNote")).In(th.ToneWait).Layout + return threadSlot.Layout(gtx, func(gtx C) D { return v.pendingBody(gtx, th, i, c, note) }) } diff --git a/native/cmd/lich-native/pulls_i18n_test.go b/native/cmd/lich-native/pulls_i18n_test.go index c550f7033..c1326aa13 100644 --- a/native/cmd/lich-native/pulls_i18n_test.go +++ b/native/cmd/lich-native/pulls_i18n_test.go @@ -168,19 +168,19 @@ func TestRunningRemovalNamesTheWorktreeAndCountsTheSessions(t *testing.T) { } } -func TestPullsStateAndFilterLabelsFollowTheInterfaceLanguage(t *testing.T) { +func TestPullsStateAndGroupLabelsFollowTheInterfaceLanguage(t *testing.T) { if got := pullsMerged.label(); got != "Merged" { t.Errorf("state = %q", got) } - if got := filterFailing.label(); got != "Failing" { - t.Errorf("filter = %q", got) + if got := groupWork.label(); got != "Needs work" { + t.Errorf("group = %q", got) } i18n.SetCurrent(i18n.PtBR) defer i18n.SetCurrent(i18n.EN) if got := pullsClosed.none(); got != "Nenhum pull request fechado." { t.Errorf("pt-BR none = %q", got) } - if got := filterDrafts.label(); got != "Rascunhos" { - t.Errorf("pt-BR filter = %q", got) + if got := groupDrafts.label(); got != "Rascunhos" { + t.Errorf("pt-BR group = %q", got) } } diff --git a/native/cmd/lich-native/pulls_keys.go b/native/cmd/lich-native/pulls_keys.go index 3b613423f..42a9c5d82 100644 --- a/native/cmd/lich-native/pulls_keys.go +++ b/native/cmd/lich-native/pulls_keys.go @@ -11,7 +11,8 @@ import ( // keys carries out the screen's keys: on the index, j/k or the arrows move // the cursor, Enter opens its pull request and / goes to the field; on a pull -// request, Escape goes back to the index and Alt with an arrow steps along it. +// request, Escape closes the log in view, then goes back to the index, and Alt +// with an arrow steps along it. // They are read only while nothing holds the keyboard and no dialog is up, so // a field, a menu or a dialog keeps its own keys. func (p *pullsScreen) keys(gtx C, rows []backend.PRSummary) { @@ -46,6 +47,10 @@ func (p *pullsScreen) key(gtx C, name key.Name, rows []backend.PRSummary) { if p.selected != 0 { switch name { case key.NameEscape: + if p.view.log.url != "" { + p.view.log.close() + return + } p.backToIndex() case key.NameUpArrow: p.stepPR(rows, -1) @@ -71,7 +76,8 @@ func (p *pullsScreen) key(gtx C, name key.Name, rows []backend.PRSummary) { // moveCursor moves the index's cursor delta rows and keeps its row in view. func (p *pullsScreen) moveCursor(rows []backend.PRSummary, delta int) { p.cursor, p.keyed = stepAlong(rows, p.cursor, delta), true - i := p.cursorAt(rows) + at := p.cursorAt(rows) + i := slices.IndexFunc(indexItems(rows, p.state), func(it indexItem) bool { return it.count == 0 && it.row == at }) if pos := p.rows.Position; i >= 0 && (i <= pos.First || i >= pos.First+pos.Count-1) { p.rows.ScrollTo(max(i-delta, 0)) } diff --git a/native/cmd/lich-native/pulls_line.go b/native/cmd/lich-native/pulls_line.go new file mode 100644 index 000000000..5cb0a78ba --- /dev/null +++ b/native/cmd/lich-native/pulls_line.go @@ -0,0 +1,134 @@ +package main + +import ( + "image" + "image/color" + "strconv" + + "gioui.org/layout" + "gioui.org/op" + "gioui.org/unit" + + "github.com/lichdotdev/lich/native/backend" + "github.com/lichdotdev/lich/native/ui" + "github.com/lichdotdev/lich/native/ui/icons" +) + +// The Pulls screen's lists are one line a row, the sidebar's: a glyph in the +// rings' column, the text in the names', who and when in columns at the right. +var ( + pullsLineHeight = unit.Dp(34) + pullsLineGap = ui.Space(1.5) + lineWhoWidth = ui.Space(22) + lineWhenWidth = ui.Space(10) + // pullsTextX is where the lines' text starts, from the island's edge. + pullsTextX = pullsPadX + 2*sessionTreeRingR + pullsLineGap +) + +// lineWhoMin is the narrowest line that names its author: under it the title +// takes the room. +var lineWhoMin = unit.Dp(560) + +// pullsLine is one row of a list: content, inset as the sidebar's rows. +func pullsLine(gtx C, th *ui.Theme, click *ui.Clickable, on bool, content func(gtx C, th *ui.Theme) D) D { + return layout.Inset{Left: pullsRowEdge, Right: pullsRowEdge}.Layout(gtx, func(gtx C) D { + return th.NavRow(gtx, click, on, pullsLineHeight, pullsRowPadX, content) + }) +} + +// lineGlyph is a line's leading glyph in the rings' column. +func lineGlyph(th *ui.Theme, ic *icons.Icon, word string, fg color.NRGBA) layout.Widget { + return inNodeColumn(func(gtx C) D { return pullState(gtx, th, ic, word, fg) }) +} + +// lineText is a line's title and the facts after it. Where they do not all +// fit whole the last facts go first, and then the title is cut: the first +// fact, the number or the hash, always stays. +// want is the title's natural width. +func lineText(gtx C, want int, title layout.Widget, facts ...layout.Widget) D { + gtx.Constraints.Min = image.Point{} + room := gtx.Constraints.Max.X + gap := gtx.Dp(ui.Space(2)) + widths := 0 + for _, f := range facts { + widths += gap + naturalWidth(gtx, f) + } + for len(facts) > 1 && want+widths > room { + widths -= gap + naturalWidth(gtx, facts[len(facts)-1]) + facts = facts[:len(facts)-1] + } + children := []layout.FlexChild{layout.Rigid(func(gtx C) D { + gtx.Constraints.Max.X = max(min(want, room-widths), 0) + return title(gtx) + })} + for _, f := range facts { + children = append(children, ui.Gap(2), layout.Rigid(f)) + } + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, children...) +} + +// naturalWidth is how wide w draws itself given all the room it wants. +func naturalWidth(gtx C, w layout.Widget) int { + defer op.Record(gtx.Ops).Stop() + gtx.Constraints = layout.Constraints{Max: image.Pt(maxLineWidth, gtx.Constraints.Max.Y)} + return w(gtx).Size.X +} + +// maxLineWidth is wider than any line; the shaper overflows past 1<<24. +const maxLineWidth = 1 << 20 + +// lineWho is who and when in their columns at a line's end. +func lineWho(th *ui.Theme, narrow bool, who, when string) []layout.FlexChild { + age := ui.FixedColumn(lineWhenWidth, ui.AlignEnd(th.Text(ui.TextXS, when).Mono().Muted().Layout)) + if narrow { + return []layout.FlexChild{ui.Gap(2), age} + } + return []layout.FlexChild{ui.Gap(6), ui.FixedColumn(lineWhoWidth, th.Text(ui.TextXS, who).Muted().Layout), age} +} + +// pullsHeading is the heading over a group of lines and how many it has, +// where their glyphs start. +func pullsHeading(gtx C, th *ui.Theme, label string, count int, top unit.Dp) D { + heading := th.SectionHeading(label) + heading.Size = ui.Text2XS + return layout.Inset{Left: pullsPadX, Top: top, Bottom: ui.Space(1)}.Layout(gtx, func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(heading.Layout), + ui.Gap(1.5), + layout.Rigid(th.Text(ui.TextXS, strconv.Itoa(count)).Muted().Layout), + ) + }) +} + +// pullsNote is the one muted line a list says in place of its rows. +func pullsNote(gtx C, th *ui.Theme, text string) D { + return layout.Inset{Left: pullsTextX, Right: pullsPadX, Top: ui.Space(2)}.Layout(gtx, th.Text(ui.TextSM, text).Muted().Wrapped().Layout) +} + +// skeletonLine is a line while its list loads: the glyph, a title title wide +// of the room, and what its right columns hold. +func skeletonLine(gtx C, th *ui.Theme, title float32) D { + gtx.Constraints.Min.X = gtx.Constraints.Max.X + return layout.Inset{Left: pullsPadX, Right: pullsPadX}.Layout(gtx, func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(inNodeColumn(th.SkeletonBar(ui.Space(3.5), pullsLineHeight, ui.Space(3.5)).Layout)), + layout.Rigid(layout.Spacer{Width: pullsLineGap}.Layout), + layout.Flexed(1, func(gtx C) D { + full := gtx.Metric.PxToDp(gtx.Constraints.Max.X) + d := th.SkeletonBar(full*unit.Dp(title), pullsLineHeight, ui.Space(3)).Layout(gtx) + d.Size.X = gtx.Constraints.Max.X + return d + }), + layout.Rigid(th.SkeletonBar(ui.Space(18), pullsLineHeight, ui.Space(3)).Layout), + ) + }) +} + +// authorOf is the name a commit is credited to, its GitHub login when it has +// one. +func authorOf(c backend.PRCommit) string { + if c.Login != "" { + return c.Login + } + return c.Name +} diff --git a/native/cmd/lich-native/pulls_list.go b/native/cmd/lich-native/pulls_list.go index ee1f76ad8..ec25acc11 100644 --- a/native/cmd/lich-native/pulls_list.go +++ b/native/cmd/lich-native/pulls_list.go @@ -2,26 +2,26 @@ package main import ( "fmt" + "image" "image/color" - "math" "path/filepath" + "strconv" + "strings" "time" "gioui.org/font" "gioui.org/layout" "gioui.org/op" - "gioui.org/unit" "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" ) func (s pullsState) label() string { switch s { - case pullsApproved: - return i18n.T("pulls.pullsStats.approved") case pullsClosed: return i18n.T("pulls.pullsStats.closed") case pullsMerged: @@ -32,8 +32,6 @@ func (s pullsState) label() string { func (s pullsState) none() string { switch s { - case pullsApproved: - return i18n.T("pulls.pullsList.none.approved") case pullsClosed: return i18n.T("pulls.pullsList.none.closed") case pullsMerged: @@ -45,8 +43,6 @@ func (s pullsState) none() string { // noneMergeRequests is none for a GitLab project's merge requests. func (s pullsState) noneMergeRequests() string { switch s { - case pullsApproved: - return i18n.T("pulls.pullsList.noneGitLab.approved") case pullsClosed: return i18n.T("pulls.pullsList.noneGitLab.closed") case pullsMerged: @@ -55,90 +51,72 @@ func (s pullsState) noneMergeRequests() string { return i18n.T("pulls.pullsList.noneGitLab.open") } -// indexLayout is the index: one header line with the field (the state menu -// inside it), the counted quick filters and New, then a row per pull request. +// indexLayout is the index: the field, the state it lists and New on one +// line, then a line per pull request, grouped by what each one needs. func (p *pullsScreen) indexLayout(gtx C, th *ui.Theme, list pullsRead[[]backend.PRSummary], act *pullsAction) D { if p.create.Clicked(gtx) { act.create = true } - counts := filterCounts(list.val, p.query.Text()) + if p.clearQuery.Clicked(gtx) { + p.query.SetText("") + gtx.Execute(keyFocus(&p.query)) + } return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { return p.indexHeader(gtx, th, counts) }), + layout.Rigid(func(gtx C) D { return p.indexHeader(gtx, th) }), layout.Flexed(1, func(gtx C) D { - // Read after the filter tabs took their click. return p.tour.Anchor(gtx, tourPullsList, func(gtx C) D { return p.rowList(gtx, th, list, p.visible(list.val)) }) }), ) } -// indexSearchWidth is the index's field with the state menu in it, wide -// enough for its hint. -var indexSearchWidth = unit.Dp(420) - -// indexHeader is the field, then at the right the quick filters and New. -func (p *pullsScreen) indexHeader(gtx C, th *ui.Theme, counts [pullsFilterCount]int) D { - tabs := p.filterTabs(th, counts) +func (p *pullsScreen) indexHeader(gtx C, th *ui.Theme) D { return layout.UniformInset(pullsToolbarPad).Layout(gtx, func(gtx C) D { gtx.Constraints.Min.X = gtx.Constraints.Max.X return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { return p.searchField(gtx, th) }), - ui.Gap(2), - layout.Rigid(func(gtx C) D { - return p.tour.Anchor(gtx, tourPullsFilter, func(gtx C) D { return tabs.Layout(gtx) }) + layout.Flexed(1, func(gtx C) D { + return p.tour.Anchor(gtx, tourPullsFilter, func(gtx C) D { return p.searchField(gtx, th) }) }), ui.Gap(2), + layout.Rigid(func(gtx C) D { return p.stateButton(gtx, th) }), + ui.Gap(2), layout.Rigid(func(gtx C) D { b := th.Button(&p.create, i18n.T(forgeKey(p.forge(), "pulls.pullsNav.create", "pulls.pullsNav.createGitLab"))) - b.Icon, b.Variant, b.Size = icPullOut, ui.VariantOutline, ui.SizeSM + b.Icon, b.Variant, b.Size = icServerAdd, ui.VariantSecondary, ui.SizeSM return b.Layout(gtx) }), ) }) } -// searchField is the filter field, the state menu leading it. It holds the -// line's free width, so the filters and New sit at the right edge, and gives -// it up first when the line is narrow. -func (p *pullsScreen) searchField(gtx C, th *ui.Theme) D { - field := th.InputGroup(&p.query, i18n.T("pulls.pullsList.searchHint")) - field.Width, field.Height, field.TextSize, field.Clear = indexSearchWidth, ui.Space(8), ui.TextXS, &p.clearQuery - inner := field.Inner() - field.Start = ui.InputGroupAddon{Button: true, Items: []layout.Widget{ - func(gtx C) D { return p.stateButton(gtx, inner) }, - inner.InputGroupIcon(icPullSearch), - }} - d := field.Layout(gtx) - d.Size.X = gtx.Constraints.Max.X - return d -} +// bareInputPad is the room a bare ui.Input keeps at its sides. +var bareInputPad = ui.Space(2.5) -func (p *pullsScreen) filterTabs(th *ui.Theme, counts [pullsFilterCount]int) ui.TabsStyle { - triggers := make([]ui.TabsTrigger, pullsFilterCount) - for i := range triggers { - n := counts[i] - count := filterCountColor(th, pullsFilter(i), n) - triggers[i] = ui.TabsTrigger{Text: pullsFilter(i).label(), Trailing: func(gtx C) D { - return th.Text(ui.TextXS, fmt.Sprint(n)).In(count).Layout(gtx) - }} +// searchField is the filter with no box, a line of the list under it: the +// magnifier in the glyphs' column, the text where the titles start and the × +// that empties it right after. +func (p *pullsScreen) searchField(gtx C, th *ui.Theme) D { + hint := i18n.T(forgeKey(p.forge(), "pulls.pullsList.searchHint", "pulls.pullsList.searchHintGitLab")) + field := th.Input(&p.query, hint) + field.Bare, field.Height = true, ui.Space(8) + left := pullsTextX - pullsToolbarPad + d := layout.Inset{Left: left - bareInputPad}.Layout(gtx, field.Layout) + place := func(x int, w layout.Widget) { + macro := op.Record(gtx.Ops) + inner := gtx + inner.Constraints.Min = image.Point{} + size := w(inner).Size + call := macro.Stop() + defer op.Offset(image.Pt(x, (d.Size.Y-size.Y)/2)).Push(gtx.Ops).Pop() + call.Add(gtx.Ops) } - tabs := th.Tabs(&p.filter, triggers...) - tabs.Variant = ui.TabsVariantGhost - return tabs -} - -// emptyFilterOpacity fades a filter with nothing in it, the chip's opacity-40. -const emptyFilterOpacity = 0.4 - -// filterCountColor reads a filter's state off its count: a failing pull -// request in the destructive color, an empty filter faded. -func filterCountColor(th *ui.Theme, f pullsFilter, n int) color.NRGBA { - switch { - case n == 0: - return ui.Alpha(th.MutedForeground, emptyFilterOpacity) - case f == filterFailing: - return th.Destructive + place(gtx.Dp(rowInset), inNodeColumn(func(gtx C) D { return icPullSearch.Layout(gtx, ui.Space(3.5), th.MutedForeground) })) + if text := p.query.Text(); text != "" { + x := gtx.Dp(left) + naturalWidth(gtx, th.Text(ui.TextSM, text).Layout) + gtx.Dp(ui.Space(1.5)) + b := th.Button(&p.clearQuery, "") + b.Icon, b.Variant, b.Size = icPullX, ui.VariantGhost, ui.SizeIconXS + place(min(x, d.Size.X-gtx.Dp(ui.Space(6))), b.Layout) } - return th.MutedForeground + return d } // stateButton is the state the index lists, a menu of the states it can list. @@ -147,8 +125,8 @@ func (p *pullsScreen) stateButton(gtx C, th *ui.Theme) D { for i, s := range pullsStates { entries[i] = ui.MenuEntry{Kind: ui.MenuRadioItem, Label: s.label(), Checked: s == p.state, OnClick: func() { p.state = s }} } - b := th.InputGroupButton(&p.stateClick, p.state.label()) - b.Icon = icPullDown + b := th.Button(&p.stateClick, p.state.label()) + b.Icon, b.Variant, b.Size = icPullDown, ui.VariantGhost, ui.SizeSM return th.DropdownMenu(p.root, &p.stateMenu, entries).Layout(gtx, b.Layout) } @@ -157,19 +135,30 @@ func (p *pullsScreen) rowList(gtx C, th *ui.Theme, list pullsRead[[]backend.PRSu case !list.loaded: return listSkeleton(gtx, th) case list.err != "": - return th.Notice(list.err).Layout(gtx) + return pullsNote(gtx, th, list.err) case len(list.val) == 0 && p.forge() == api.ForgeGitLab: - return th.Notice(p.state.noneMergeRequests()).Layout(gtx) + return pullsNote(gtx, th, p.state.noneMergeRequests()) case len(list.val) == 0: - return th.Notice(p.state.none()).Layout(gtx) + return pullsNote(gtx, th, p.state.none()) case len(rows) == 0: - return th.Notice(i18n.T("pulls.pullsList.noMatch")).Layout(gtx) + return pullsNote(gtx, th, i18n.T("pulls.pullsList.noMatch")) } now := gtx.Now if p.cursorAt(rows) < 0 { p.cursor = rows[0].Number } - return th.ThinScrollArea(&p.rows).Layout(gtx, len(rows), func(gtx C, i int) D { return p.row(gtx, th, rows[i], now) }) + items := indexItems(rows, p.state) + return th.ThinScrollArea(&p.rows).Layout(gtx, len(items), func(gtx C, i int) D { + item := items[i] + if item.count == 0 { + return p.row(gtx, th, rows[item.row], now) + } + top := ui.Space(4) + if i == 0 { + top = ui.Space(2) + } + return pullsHeading(gtx, th, item.group.label(), item.count, top) + }) } // cursorAt is the cursor's row in rows, -1 when it is not among them. @@ -177,17 +166,8 @@ func (p *pullsScreen) cursorAt(rows []backend.PRSummary) int { return position(rows, p.cursor) } -// The index row's columns at its right: the checks, the verdict and the -// checkout, each its own width so they line up down the index. -var ( - rowChecksWidth = unit.Dp(88) - rowVerdictWidth = unit.Dp(150) - rowCheckoutWidth = unit.Dp(150) -) - -// row is one pull request across the index: "#N title" over who, when and -// its branch, then its checks, verdict and checkout in columns. The cursor's -// row is filled once the keyboard moved it, rounded as the sidebar's rows. +// row is one pull request's line, filled while the cursor the keyboard moved +// is on it. func (p *pullsScreen) row(gtx C, th *ui.Theme, pr backend.PRSummary, now time.Time) D { click := p.rowClicks[pr.Number] if click == nil { @@ -195,89 +175,97 @@ func (p *pullsScreen) row(gtx C, th *ui.Theme, pr backend.PRSummary, now time.Ti p.rowClicks[pr.Number] = click } checkout, _ := p.checkedOut(pr.HeadRefName) - gtx.Constraints.Min.X = gtx.Constraints.Max.X - return click.Layout(gtx, func(gtx C) D { - bg := th.Surface - switch { - case pr.Number == p.cursor && p.keyed: - bg = th.Accent - case click.Hovered(): - bg = th.Over(ui.Alpha(th.Accent, ghostHoverFill)) - } - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return layout.Background{}.Layout(gtx, - func(gtx C) D { return ui.Fill(gtx, bg, ui.RadiusMD) }, - func(gtx C) D { - return layout.Inset{Left: pullsRowEdge, Right: pullsRowEdge}.Layout(gtx, func(gtx C) D { - return rowContent(gtx, th.On(bg), pr, checkoutName(checkout), p.forge(), now) - }) - }) - }), - ) - }) -} - -func rowContent(gtx C, th *ui.Theme, pr backend.PRSummary, checkout, forge string, now time.Time) D { - return layout.Inset{Left: pullsRowPadX, Right: pullsRowPadX, Top: pullsRowPadY, Bottom: pullsRowPadY}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { return rowTitle(gtx, th, pr, forge) }), - ui.VGap(1), - layout.Rigid(func(gtx C) D { return rowMeta(gtx, th, pr, now) }), - ) - }), - ui.Gap(4), - layout.Rigid(func(gtx C) D { return rowSide(gtx, th, pr, checkout) }), - ) + text := func(gtx C, w layout.Widget) D { + tip := th.TooltipCard(p.root, p.view.tip("row:"+strconv.Itoa(pr.Number)), func(gtx C) D { return rowTip(gtx, th, pr, checkoutName(checkout)) }) + tip.Side = ui.SideBottom + return tip.Layout(gtx, w) + } + return pullsLine(gtx, th, click, pr.Number == p.cursor && p.keyed, func(gtx C, th *ui.Theme) D { + return rowContent(gtx, th, pr, p.forge(), now, text) }) } -func rowTitle(gtx C, th *ui.Theme, pr backend.PRSummary, forge string) D { - return layout.Flex{}.Layout(gtx, - layout.Rigid(th.Text(ui.TextSM, changeRef(forge, pr.Number)).Mono().Muted().Layout), - ui.Gap(1.5), +// rowContent is the line: what the pull request needs as a glyph, its title, +// number and branch, then the one fact about it, who and when. text wraps the +// title's part. +func rowContent(gtx C, th *ui.Theme, pr backend.PRSummary, forge string, now time.Time, text func(gtx C, w layout.Widget) D) D { + ic, fg, fact := rowNeed(th, pr) + narrow := gtx.Constraints.Max.X < gtx.Dp(lineWhoMin) + facts := []layout.Widget{th.Text(ui.TextXS, changeRef(forge, pr.Number)).Mono().Muted().Layout} + if pr.HeadRefName != "" { + facts = append(facts, th.Text(ui.TextXS, pr.HeadRefName).Mono().Muted().Layout) + } + word := fact + if word == "" { + word = needOf(pr).group().label() + } + children := []layout.FlexChild{ + layout.Rigid(lineGlyph(th, ic, word, fg)), + layout.Rigid(layout.Spacer{Width: pullsLineGap}.Layout), layout.Flexed(1, func(gtx C) D { - l := th.Text(ui.TextSM, pr.Title).Weight(font.Medium) - l.MaxLines = 1 - return l.Layout(gtx) + full := gtx.Constraints.Max.X + d := text(gtx, func(gtx C) D { + title := th.Text(ui.TextSM, pr.Title).Weight(font.Medium).Layout + return lineText(gtx, naturalWidth(gtx, title), title, facts...) + }) + d.Size.X = full + return d }), - ) + ui.Gap(2), + layout.Rigid(th.Text(ui.TextXS, fact).Muted().Layout), + } + children = append(children, lineWho(th, narrow, pr.Author, shortAge(pr.UpdatedAt, now))...) + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, children...) } -// rowSide is the row's columns: the checks, the verdict worth acting on and -// the checkout the branch sits in, which shows only where it fits whole. -func rowSide(gtx C, th *ui.Theme, pr backend.PRSummary, checkout string) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - ui.FixedColumn(rowChecksWidth, ui.AlignEnd(func(gtx C) D { - if verdictOf(pr.Checks) == verdictNone { - return D{} - } - return checksChip(gtx, th, pr.Checks) - })), - ui.FixedColumn(rowVerdictWidth, ui.AlignEnd(func(gtx C) D { return rowVerdict(gtx, th, pr) })), - ui.FixedColumn(rowCheckoutWidth, ui.AlignEnd(func(gtx C) D { - if checkout == "" { - return D{} - } - return wholeOrNothing(gtx, func(gtx C) D { return th.MetaGlyph(icCheckout, checkout, th.MutedForeground).Layout(gtx) }) - })), - ) +// rowNeed is what a pull request needs as its line draws it: the glyph, and +// the fact that explains it when the glyph is not enough. +func rowNeed(th *ui.Theme, pr backend.PRSummary) (ic *icons.Icon, fg color.NRGBA, fact string) { + switch pr.State { + case "MERGED": + return icPullMerged, th.MutedForeground, "" + case "CLOSED": + return icPullX, th.MutedForeground, "" + } + switch needOf(pr) { + case needFix: + return icPullX, th.Destructive, i18n.T("pulls.pullsList.checksFailed", i18n.Args{"count": pr.Checks.Failed}) + case needChanges: + return icPullX, th.Destructive, i18n.T("pulls.pullsStats.changesRequested") + case needChecks: + return icPullRunning, th.ToneWait, fmt.Sprintf("%d/%d", pr.Checks.Total-pr.Checks.Pending, pr.Checks.Total) + case needReviewer: + return icPullCheck2, th.ToneWait, i18n.T("pulls.pullsList.threadsResolved") + case needReview: + return icPullDashed, th.MutedForeground, i18n.T("pulls.pullsStats.reviewRequired") + case needReady: + return icPullDashed, th.MutedForeground, "" + } + return icPullCheck, th.TonePass, "" } -// rowVerdict is the review verdict worth acting on; REVIEW_REQUIRED, most -// rows' resting state, shows nothing. -func rowVerdict(gtx C, th *ui.Theme, pr backend.PRSummary) D { - switch { - case pr.ReviewDecision == "APPROVED": - return pullState(gtx, th, icPullCheck, i18n.T("pulls.pullsStats.approved"), th.TonePass) - case waitsOnReviewer(pr): - return pullState(gtx, th, icPullCheck2, i18n.T("pulls.pullsStats.changesRequested"), th.ToneWait) - case pr.ReviewDecision == "CHANGES_REQUESTED": - return pullState(gtx, th, icPullX, i18n.T("pulls.pullsStats.changesRequested"), th.Destructive) +// rowTip is what a line has no room for: the whole title, then where the +// branch is checked out, whether it is a fork's, the checks and the approval. +func rowTip(gtx C, th *ui.Theme, pr backend.PRSummary, checkout string) D { + on := th.On(th.Popover) + var facts []string + if checkout != "" { + facts = append(facts, i18n.T("pulls.pullsList.checkedOutIn", i18n.Args{"name": checkout})) + } + if pr.IsCrossRepository { + facts = append(facts, i18n.T("pulls.pullsList.fork")) + } + if _, text, _, ok := checksStat(th, pr.Checks); ok { + facts = append(facts, text) + } + if pr.ReviewDecision == "APPROVED" { + facts = append(facts, i18n.T("pulls.pullsStats.approved")) } - return D{} + lines := []layout.FlexChild{layout.Rigid(on.Text(ui.TextXS, pr.Title).Weight(font.Medium).Wrapped().Layout)} + if len(facts) > 0 { + lines = append(lines, ui.VGap(1), layout.Rigid(on.Text(ui.TextXS, strings.Join(facts, " · ")).Muted().Wrapped().Layout)) + } + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, lines...) } // checkoutName is the folder a PR's branch is checked out in, the name its @@ -289,112 +277,22 @@ func checkoutName(w backend.Worktree) string { return filepath.Base(w.Path) } -// rowMeta is the row's second line: who, when, the branch, and whether it is -// a draft or comes from a fork. The author truncates first. -func rowMeta(gtx C, th *ui.Theme, pr backend.PRSummary, now time.Time) D { - facts := []layout.FlexChild{ - layout.Rigid(func(gtx C) D { - gtx.Constraints.Min.X = 0 - return th.Text(ui.TextXS, pr.Author).Muted().Layout(gtx) - }), - ui.Gap(2), - layout.Rigid(th.Text(ui.TextXS, updatedAgo(pr.UpdatedAt, now)).Mono().Muted().Layout), - } - add := func(w layout.Widget) { facts = append(facts, ui.Gap(2), layout.Rigid(w)) } - if pr.HeadRefName != "" { - add(th.Text(ui.TextXS, pr.HeadRefName).Mono().Muted().Layout) - } - if pr.IsDraft { - // muted: amber on a row is the verdict waiting on its reviewer - add(func(gtx C) D { - return pullState(gtx, th, icPullDashed, i18n.T("pulls.pullsList.draft"), th.MutedForeground) - }) - } - if pr.IsCrossRepository { - add(th.Text(ui.TextXS, i18n.T("pulls.pullsList.fork")).Muted().Layout) - } - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, facts...) -} - // waitsOnReviewer is a CHANGES_REQUESTED verdict whose every thread is // resolved: GitHub keeps the verdict until the reviewer moves. func waitsOnReviewer(pr backend.PRSummary) bool { return pr.ReviewDecision == "CHANGES_REQUESTED" && pr.Threads.Total > 0 && pr.Threads.Open == 0 } -// wholeOrNothing draws w only when its natural width fits: a glyph cut in -// half reads as a broken row. -func wholeOrNothing(gtx C, w layout.Widget) D { - macro := op.Record(gtx.Ops) - natural := gtx - natural.Constraints.Max.X = math.MaxInt32 - d := w(natural) - call := macro.Stop() - if d.Size.X > gtx.Constraints.Max.X { - return D{} - } - call.Add(gtx.Ops) - return d -} - -// checksChip is a row's checks at a glance: how many have finished while -// any run, how many failed once one has, all of them once they pass. -func checksChip(gtx C, th *ui.Theme, c backend.ChecksRollup) D { - ic, fg, text := icPullCheck, th.TonePass, fmt.Sprintf("%d/%d", c.Passed, c.Total) - switch verdictOf(c) { - case verdictFailed: - ic, fg, text = icPullX, th.Destructive, i18n.T("pulls.pullsList.checksFailed", i18n.Args{"count": c.Failed}) - case verdictPending: - ic, fg, text = icPullRunning, th.ToneWait, fmt.Sprintf("%d/%d", c.Total-c.Pending, c.Total) - } - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { return pullGlyph(gtx, th, ic, ui.Space(3), fg) }), - ui.Gap(1), - layout.Rigid(th.Text(ui.TextXS, text).Mono().In(fg).Layout), - ) -} - // listSkeletonMaxRows bounds the skeleton under an unbounded height; no // island is that tall. const listSkeletonMaxRows = 60 -// listSkeleton is the index while it loads: as many rows as the island -// holds, each skeletonRow over a separator, as row draws them. -func listSkeleton(gtx C, th *ui.Theme) D { - titles := []float32{0.62, 0.48, 0.7, 0.55, 0.4, 0.66, 0.5} - rowHeight := gtx.Dp(2*pullsRowPadY+skeletonSMLine+ui.Space(1)+skeletonXSLine) + gtx.Dp(1) - count := min(gtx.Constraints.Max.Y/rowHeight+1, listSkeletonMaxRows) - var rows []layout.FlexChild - for i := range count { - title := titles[i%len(titles)] - rows = append(rows, layout.Rigid(func(gtx C) D { return skeletonRow(gtx, th, title) })) - } - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, rows...) -} +// skeletonTitles are the lines' title widths, of the room they have. +var skeletonTitles = []float32{0.42, 0.32, 0.5, 0.38, 0.28, 0.46, 0.35} -// skeletonRow is rowContent with a bar where its text lands: the number and -// title, the meta line under them, and the checks chip in its column. -func skeletonRow(gtx C, th *ui.Theme, title float32) D { - gtx.Constraints.Min.X = gtx.Constraints.Max.X - return layout.Inset{Left: pullsRowEdge + pullsRowPadX, Right: pullsRowEdge + pullsRowPadX, Top: pullsRowPadY, Bottom: pullsRowPadY}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { - full := gtx.Metric.PxToDp(gtx.Constraints.Max.X) - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return layout.Flex{}.Layout(gtx, - layout.Rigid(th.SkeletonBar(ui.Space(10), skeletonSMLine, ui.Space(3.5)).Layout), - ui.Gap(1.5), - layout.Rigid(th.SkeletonBar(full*unit.Dp(title), skeletonSMLine, ui.Space(3.5)).Layout), - ) - }), - ui.VGap(1), - layout.Rigid(th.SkeletonBar(full*unit.Dp(title)*0.6, skeletonXSLine, ui.Space(3)).Layout), - ) - }), - ui.Gap(4), - ui.FixedColumn(rowChecksWidth, ui.AlignEnd(th.SkeletonBar(ui.Space(9), skeletonXSLine, ui.Space(3)).Layout)), - layout.Rigid(layout.Spacer{Width: rowVerdictWidth + rowCheckoutWidth}.Layout), - ) +// listSkeleton is a list while it loads: as many lines as the island holds. +func listSkeleton(gtx C, th *ui.Theme) D { + return skeletonRows.Layout(gtx, func(gtx C, i int) D { + return skeletonLine(gtx, th, skeletonTitles[i%len(skeletonTitles)]) }) } diff --git a/native/cmd/lich-native/pulls_list_test.go b/native/cmd/lich-native/pulls_list_test.go index f3b26f67c..8a6d99f89 100644 --- a/native/cmd/lich-native/pulls_list_test.go +++ b/native/cmd/lich-native/pulls_list_test.go @@ -3,6 +3,7 @@ package main import ( "image" "image/color" + "slices" "testing" "time" @@ -19,10 +20,12 @@ import ( "github.com/lichdotdev/lich/native/ui" ) -const rowMetaHeight = 24 - -// rowMetaWidth is the index row's columns at 1x, wide enough for all three. -var rowMetaWidth = int(rowChecksWidth + rowVerdictWidth + rowCheckoutWidth) +// rowMetaWidth and rowMetaHeight are a line of the index at 1x, its author +// shown. +const ( + rowMetaWidth = 900 + rowMetaHeight = 34 +) var rowMetaNow = time.Date(2026, 10, 22, 12, 0, 0, 0, time.UTC) @@ -71,67 +74,130 @@ func requested(author string, threads backend.ThreadTally) backend.PRSummary { UpdatedAt: rowMetaNow.Add(-59 * time.Minute).Format(time.RFC3339)} } -// A long checkout beside the verdict never cuts it: the verdict is the one -// fact on the row worth acting on, and the checkout gives way. -func TestRowSideKeepsTheVerdictWhole(t *testing.T) { - th := rowMetaTheme(t) - pr := requested("ana", backend.ThreadTally{Open: 1, Total: 1}) - // the verdict alone, a glyph since words left the row (contract changed) - whole := inkWidth(t, func(gtx C) D { return rowVerdict(gtx, th, pr) }, th.Destructive) - got := inkWidth(t, func(gtx C) D { return rowSide(gtx, th, pr, "joao-vitorino-dos-santos_snk-rapid-quartz") }, th.Destructive) - if got < whole { - t.Errorf("verdict drew %dpx of its %dpx", got, whole) +// drawnRow is pr's line as the index draws it. +func drawnRow(th *ui.Theme, pr backend.PRSummary) layout.Widget { + return func(gtx C) D { + return pullsLine(gtx, th, new(ui.Clickable), false, func(gtx C, th *ui.Theme) D { + return rowContent(gtx, th, pr, api.ForgeGitHub, rowMetaNow, func(gtx C, w layout.Widget) D { return w(gtx) }) + }) } } -// GitHub keeps CHANGES_REQUESTED after every thread is resolved; the row then -// reads as waiting on the reviewer, as the pull request's heading does. -func TestRowVerdictFollowsTheThreads(t *testing.T) { +// What a pull request needs is the one thing its line says, so what blocks it +// first wins, and a draft waits on its author whatever its checks say. GitHub +// keeps CHANGES_REQUESTED after every thread is resolved; the line then waits +// on the reviewer. +func TestNeedOfIsWhatBlocksFirst(t *testing.T) { + failed, running, passed := backend.ChecksRollup{Total: 2, Failed: 1}, backend.ChecksRollup{Total: 2, Pending: 1}, backend.ChecksRollup{Total: 2, Passed: 2} + open, settled := backend.ThreadTally{Open: 1, Total: 3}, backend.ThreadTally{Total: 3} + cases := []struct { + name string + pr backend.PRSummary + want pullNeed + group pullsGroup + }{ + {"nothing asked of it", backend.PRSummary{}, needNothing, groupReady}, + {"approved and green", backend.PRSummary{Checks: passed, ReviewDecision: "APPROVED"}, needNothing, groupReady}, + {"approved and red", backend.PRSummary{Checks: failed, ReviewDecision: "APPROVED"}, needFix, groupWork}, + {"changes asked", backend.PRSummary{Checks: running, ReviewDecision: "CHANGES_REQUESTED", Threads: open}, needChanges, groupWork}, + {"changes asked with no thread", backend.PRSummary{ReviewDecision: "CHANGES_REQUESTED"}, needChanges, groupWork}, + {"every thread resolved", backend.PRSummary{ReviewDecision: "CHANGES_REQUESTED", Threads: settled}, needReviewer, groupReview}, + {"resolved but red", backend.PRSummary{Checks: failed, ReviewDecision: "CHANGES_REQUESTED", Threads: settled}, needFix, groupWork}, + {"running before the review it needs", backend.PRSummary{Checks: running, ReviewDecision: "REVIEW_REQUIRED"}, needChecks, groupReview}, + {"a review asked for", backend.PRSummary{Checks: passed, ReviewDecision: "REVIEW_REQUIRED"}, needReview, groupReview}, + {"a red draft", backend.PRSummary{Checks: failed, IsDraft: true}, needReady, groupDrafts}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := needOf(c.pr); got != c.want || got.group() != c.group { + t.Errorf("need %v in group %v, want %v in %v", got, got.group(), c.want, c.group) + } + }) + } +} + +// Amber on a line is a wait that will end by itself or on its reviewer; red is +// the author's move, and a draft is neither. +func TestRowColorSaysWhoseMoveItIs(t *testing.T) { th := rowMetaTheme(t) cases := []struct { - name string - threads backend.ThreadTally - red bool + name string + pr backend.PRSummary + red, amber bool }{ - {"an open thread is the author's move", backend.ThreadTally{Open: 1, Total: 3}, true}, - {"no threads leaves only the verdict", backend.ThreadTally{}, true}, - {"every thread resolved is the reviewer's move", backend.ThreadTally{Open: 0, Total: 3}, false}, + {"an open thread is the author's", requested("ana", backend.ThreadTally{Open: 1, Total: 3}), true, false}, + {"every thread resolved is the reviewer's", requested("ana", backend.ThreadTally{Total: 3}), false, true}, + {"a draft is nobody's", backend.PRSummary{Author: "ana", IsDraft: true}, false, false}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - pr := requested("ana", c.threads) - meta := func(gtx C) D { return rowVerdict(gtx, th, pr) } - red, amber := inkWidth(t, meta, th.Destructive) > 0, inkWidth(t, meta, th.ToneWait) > 0 - if red != c.red || amber == c.red { - t.Errorf("red %v amber %v, want red %v", red, amber, c.red) + row := drawnRow(th, c.pr) + if red, amber := inkWidth(t, row, th.Destructive) > 0, inkWidth(t, row, th.ToneWait) > 0; red != c.red || amber != c.amber { + t.Errorf("red %v amber %v, want %v and %v", red, amber, c.red, c.amber) } }) } } -func TestWholeOrNothingDropsWhatWouldBeCut(t *testing.T) { - wide := func(gtx C) D { return D{Size: image.Pt(50, 10)} } - gtx := layout.Context{Ops: new(op.Ops), Constraints: layout.Constraints{Max: image.Pt(40, 10)}} - if d := wholeOrNothing(gtx, wide); d.Size.X != 0 { - t.Errorf("40px for 50px drew %dpx, want nothing", d.Size.X) +// The last facts go before the title is cut, and the first one never goes. +func TestLineTextDropsItsLastFactsFirst(t *testing.T) { + box := func(w int, drawn *int) layout.Widget { + return func(gtx C) D { + *drawn = min(w, gtx.Constraints.Max.X) + return D{Size: image.Pt(*drawn, 10)} + } } - gtx.Constraints.Max.X = 50 - if d := wholeOrNothing(gtx, wide); d.Size.X != 50 { - t.Errorf("50px for 50px drew %dpx, want all of it", d.Size.X) + cases := []struct { + room int + title, first, other int + }{ + {200, 100, 30, 40}, + {150, 100, 30, 0}, + {100, 62, 30, 0}, + } + for _, c := range cases { + gtx := layout.Context{Ops: new(op.Ops), Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Constraints{Max: image.Pt(c.room, 20)}} + var title, first, other int + d := lineText(gtx, 100, box(100, &title), box(30, &first), box(40, &other)) + if title != c.title || first != c.first || d.Size.X > c.room { + t.Errorf("in %dpx the title took %d and the first fact %d of %d, want %d and %d", c.room, title, first, d.Size.X, c.title, c.first) + } + if want := c.title + 8 + c.first + min(c.other, 1)*(8+c.other); d.Size.X != want { + t.Errorf("in %dpx the line is %dpx, want %d", c.room, d.Size.X, want) + } } } -// Amber on a row is the verdict waiting on its reviewer; a draft beside it is -// the pull request's state, drawn muted so the two never read as one. -func TestRowMetaDraftLeavesAmberToTheVerdict(t *testing.T) { - th := rowMetaTheme(t) - pr := backend.PRSummary{Author: "ana", IsDraft: true, UpdatedAt: rowMetaNow.Add(-5 * time.Hour).Format(time.RFC3339)} - meta := func(gtx C) D { return rowMeta(gtx, th, pr, rowMetaNow) } - if amber := inkWidth(t, meta, th.ToneWait); amber > 0 { - t.Errorf("a draft with no verdict drew %dpx of amber", amber) +func TestIndexItemsHeadEachGroupWithItsCount(t *testing.T) { + list := []backend.PRSummary{ + {Number: 1, UpdatedAt: "2026-01-01T00:00:00Z"}, + {Number: 2, UpdatedAt: "2026-01-04T00:00:00Z", IsDraft: true}, + {Number: 3, UpdatedAt: "2026-01-02T00:00:00Z", Checks: backend.ChecksRollup{Total: 1, Failed: 1}}, + {Number: 4, UpdatedAt: "2026-01-03T00:00:00Z"}, + } + rows := filterPulls(list, pullsOpen, "") + if got := numbers(rows); !slices.Equal(got, []int{4, 1, 3, 2}) { + t.Fatalf("open rows = %v, want them by group and newest first", got) + } + want := []indexItem{{group: groupReady, count: 2}, {row: 0}, {row: 1}, {group: groupWork, count: 1}, {row: 2}, {group: groupDrafts, count: 1}, {row: 3}} + if got := indexItems(rows, pullsOpen); !slices.Equal(got, want) { + t.Errorf("items = %+v, want %+v", got, want) + } + if got := indexItems(rows, pullsMerged); len(got) != len(rows) { + t.Errorf("merged ones have headings: %+v", got) + } +} + +func TestShortAgeIsOneUnit(t *testing.T) { + for ago, want := range map[time.Duration]string{ + 10 * time.Second: "1m", 59 * time.Minute: "59m", 5 * time.Hour: "5h", 49 * time.Hour: "2d", 15 * 24 * time.Hour: "2w", + } { + if got := shortAge(rowMetaNow.Add(-ago).Format(time.RFC3339), rowMetaNow); got != want { + t.Errorf("%v ago = %q, want %q", ago, got, want) + } } - if muted := inkWidth(t, meta, th.MutedForeground); muted == 0 { - t.Error("the draft badge drew nothing") + if got := shortAge("", rowMetaNow); got != "" { + t.Errorf("no date = %q", got) } } @@ -166,8 +232,8 @@ func TestListSkeletonRowIsALoadedRowsHeight(t *testing.T) { gtx := layout.Context{Ops: new(op.Ops), Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Constraints{Max: image.Pt(1200, 800)}} pr := backend.PRSummary{Number: 1003, Title: "feat: a title", Author: "ana", HeadRefName: "feat/x", UpdatedAt: rowMetaNow.Format(time.RFC3339), Checks: backend.ChecksRollup{Total: 7}} - loaded := rowContent(gtx, th, pr, "fuzzy-pine", api.ForgeGitHub, rowMetaNow).Size.Y - if got := skeletonRow(gtx, th, 0.5).Size.Y; got != loaded { + loaded := drawnRow(th, pr)(gtx).Size.Y + if got := skeletonLine(gtx, th, 0.5).Size.Y; got != loaded { t.Errorf("skeleton row is %dpx tall, a loaded row %dpx", got, loaded) } } diff --git a/native/cmd/lich-native/pulls_log.go b/native/cmd/lich-native/pulls_log.go new file mode 100644 index 000000000..83da7f094 --- /dev/null +++ b/native/cmd/lich-native/pulls_log.go @@ -0,0 +1,461 @@ +package main + +import ( + "cmp" + "fmt" + "image/color" + "io" + "slices" + "strconv" + "strings" + "time" + + "gioui.org/font" + "gioui.org/io/clipboard" + "gioui.org/io/key" + "gioui.org/layout" + "gioui.org/unit" + "gioui.org/widget" + "gioui.org/widget/material" + + "github.com/lichdotdev/lich/api" + "github.com/lichdotdev/lich/native/backend" + "github.com/lichdotdev/lich/native/i18n" + "github.com/lichdotdev/lich/native/ui" +) + +// The log's columns: the checks at the sidebar's width, the log in what is +// left; an island narrower than logSplitWidth shows the log alone. +var ( + logSideWidth = unit.Dp(256) + logSplitWidth = unit.Dp(720) + logFindWidth = unit.Dp(220) + logLineGap = ui.Space(0.5) +) + +// logErrorContext is how many lines of a failed step are shown over its first +// error when the log opens on it. +const logErrorContext = 8 + +// logAt is a line of a job's log: the step's index and the line's in it. +type logAt struct{ step, line int } + +// logView is the log open beside the checks: the job at url, "" for none. +type logView struct { + url string + side widget.List + rows widget.List + // open is which steps are unfolded, nil until the log arrived. + open []bool + steps []*ui.Clickable + + back, backTop ui.Clickable + find, copy, external ui.IconActionState + + finding bool + query widget.Editor + // matches is every line holding found, at the one last jumped to. + found string + matches []logAt + at int +} + +func (l *logView) show(url string) { + if l.url == url { + return + } + side := l.side + *l = logView{url: url, side: side} + l.rows.Axis, l.side.Axis = layout.Vertical, layout.Vertical +} + +func (l *logView) close() { l.url = "" } + +// check is the check whose log is open, ok false for none, or for one a new +// run has since replaced. +func (l *logView) check(d backend.PRDetail) (backend.CheckItem, bool) { + if l.url == "" { + return backend.CheckItem{}, false + } + i := slices.IndexFunc(d.CheckRuns, func(c backend.CheckItem) bool { return c.URL == l.url && c.HasLog }) + if i < 0 { + l.close() + return backend.CheckItem{}, false + } + return d.CheckRuns[i], true +} + +// arrive opens the steps that failed, on the first error, once the log is +// read. A step with no name has no line to open it from. +func (l *logView) arrive(steps []api.JobStep) { + if l.open != nil && len(l.open) == len(steps) { + return + } + l.found, l.matches = "", nil + l.open, l.steps = make([]bool, len(steps)), make([]*ui.Clickable, len(steps)) + first := -1 + for i, st := range steps { + l.steps[i] = new(ui.Clickable) + l.open[i] = st.State == "failed" || st.Name == "" + if first < 0 && st.State == "failed" { + first = i + } + } + if first < 0 { + return + } + line := slices.IndexFunc(steps[first].Lines, func(s string) bool { return strings.HasPrefix(s, logError) }) + if line <= logErrorContext { + l.rows.ScrollTo(l.item(steps, logAt{first, -1})) + return + } + l.rows.ScrollTo(l.item(steps, logAt{first, line - logErrorContext})) +} + +// items is how many rows the open steps make; a line of -1 is the step's own. +func (l *logView) items(steps []api.JobStep) int { + return l.item(steps, logAt{len(steps), -1}) +} + +// item is at's row. +func (l *logView) item(steps []api.JobStep, at logAt) int { + n := 0 + for i := range at.step { + n++ + if l.open[i] { + n += len(steps[i].Lines) + } + } + return n + at.line + 1 +} + +// locate is the step and line of row i, item's inverse. +func (l *logView) locate(steps []api.JobStep, i int) logAt { + for s := range steps { + if i == 0 { + return logAt{s, -1} + } + i-- + if !l.open[s] { + continue + } + if i < len(steps[s].Lines) { + return logAt{s, i} + } + i -= len(steps[s].Lines) + } + return logAt{} +} + +// search keeps matches in step with the field, jumping to the first one of a +// new text. +func (l *logView) search(steps []api.JobStep) { + text := strings.ToLower(l.query.Text()) + if text == l.found { + return + } + l.found, l.matches, l.at = text, nil, 0 + if text == "" { + return + } + for s, st := range steps { + for i, line := range st.Lines { + if strings.Contains(strings.ToLower(line), text) { + l.matches = append(l.matches, logAt{s, i}) + } + } + } + l.jump(steps, 0) +} + +// jump goes delta matches along, round at the ends, opening the step it lands +// in. +func (l *logView) jump(steps []api.JobStep, delta int) { + if len(l.matches) == 0 { + return + } + l.at = (l.at + delta + len(l.matches)) % len(l.matches) + to := l.matches[l.at] + l.open[to.step] = true + l.rows.ScrollTo(max(l.item(steps, to)-logErrorContext, 0)) +} + +// logLayout is the checks beside the log of c. +func (v *pullView) logLayout(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, c backend.CheckItem, act *pullsAction) D { + l := &v.log + if l.back.Clicked(gtx) || l.backTop.Clicked(gtx) { + l.close() + p.store.invalidate() + } + panel := func(gtx C) D { + return layout.Inset{Left: pullsRowEdge, Right: pullsRowEdge, Bottom: pullsRowEdge}.Layout(gtx, func(gtx C) D { + return pullsIsland(gtx, th, th.Sidebar, func(gtx C, th *ui.Theme) D { + return layout.UniformInset(ui.Space(2)).Layout(gtx, func(gtx C) D { return v.logPanel(gtx, th, p, c, act) }) + }) + }) + } + if gtx.Constraints.Max.X < gtx.Dp(logSplitWidth) { + return panel(gtx) + } + rows := append([]layout.Widget{func(gtx C) D { return v.allChecks(gtx, th) }}, v.checkRows(gtx, th, d, true)...) + return layout.Flex{}.Layout(gtx, + ui.FixedColumn(logSideWidth+2*pullsRowEdge, func(gtx C) D { + gtx.Constraints.Min.Y = gtx.Constraints.Max.Y + list := th.ThinScrollArea(&l.side) + return list.Layout(gtx, len(rows), func(gtx C, i int) D { return rows[i](gtx) }) + }), + layout.Flexed(1, panel), + ) +} + +// allChecks leads back to the whole list. +func (v *pullView) allChecks(gtx C, th *ui.Theme) D { + return pullsLine(gtx, th, &v.log.back, false, func(gtx C, th *ui.Theme) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(inNodeColumn(func(gtx C) D { return icPullBack.Layout(gtx, ui.Space(3.5), th.MutedForeground) })), + layout.Rigid(layout.Spacer{Width: pullsLineGap}.Layout), + layout.Rigid(th.Text(ui.TextSM, i18n.T("pulls.pullsChecks.all")).Muted().Layout), + ) + }) +} + +// logPanel is the log under what the job is. +func (v *pullView) logPanel(gtx C, th *ui.Theme, p *pullsScreen, c backend.CheckItem, act *pullsAction) D { + l := &v.log + read := p.store.jobLog(p.project.Path, c.URL) + steps := read.val.Steps + if read.err == "" && read.loaded { + l.arrive(steps) + l.search(steps) + } + if l.external.Click.Clicked(gtx) { + act.external = c.URL + } + if l.copy.Click.Clicked(gtx) { + gtx.Execute(clipboard.WriteCmd{Type: "application/text", Data: io.NopCloser(strings.NewReader(logText(steps)))}) + } + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Rigid(func(gtx C) D { return v.logHeader(gtx, th, p, c, steps) }), + layout.Flexed(1, func(gtx C) D { + switch { + case read.err != "": + note := i18n.T("pulls.pullsChecks.logFailed", i18n.Args{"error": read.err}) + return layout.Inset{Left: rowInset, Right: rowInset}.Layout(gtx, th.Text(ui.TextSM, note).Muted().Wrapped().Layout) + case !read.loaded: + return skeletonRows.Layout(gtx, func(gtx C, i int) D { return skeletonLine(gtx, th, skeletonTitles[i%len(skeletonTitles)]) }) + } + return v.logRows(gtx, th, steps) + }), + ) +} + +// logHeader is the job's name, workflow and result, then the search, the copy +// of the whole log and its page. +func (v *pullView) logHeader(gtx C, th *ui.Theme, p *pullsScreen, c backend.CheckItem, steps []api.JobStep) D { + l := &v.log + if l.find.Click.Clicked(gtx) { + l.finding = !l.finding + l.query.SetText("") + if l.finding { + gtx.Execute(keyFocus(&l.query)) + } + } + title := th.Text(ui.TextSM, c.Name).Weight(font.Medium).Layout + facts := []layout.Widget{th.Text(ui.TextXS, logResult(c, gtx.Now)).Muted().Layout} + if c.Description != "" { + facts = slices.Insert(facts, 0, th.Text(ui.TextXS, c.Description).Muted().Layout) + } + action := func(icon layout.Widget) layout.FlexChild { + return layout.Rigid(func(gtx C) D { return layout.Inset{Left: ui.Space(1)}.Layout(gtx, icon) }) + } + narrow := gtx.Constraints.Max.X < gtx.Dp(logSplitWidth-2*pullsRowEdge-logSideWidth) + children := []layout.FlexChild{ + layout.Rigid(func(gtx C) D { + if !narrow { + return D{} + } + b := th.Button(&l.backTop, "") + b.Icon, b.Variant, b.Size = icPullBack, ui.VariantGhost, ui.SizeIconXS + return layout.Inset{Right: ui.Space(1)}.Layout(gtx, func(gtx C) D { + return v.withTip(gtx, th, p, "allChecks", i18n.T("pulls.pullsChecks.all"), b.Layout) + }) + }), + layout.Flexed(1, ui.Spanning(func(gtx C) D { return lineText(gtx, naturalWidth(gtx, title), title, facts...) })), + layout.Rigid(func(gtx C) D { return v.logFind(gtx, th, steps) }), + action(th.IconAction(p.root, &l.find, icPullSearch, i18n.T("pulls.pullsChecks.search"), l.finding).Layout), + action(th.IconAction(p.root, &l.copy, icMenuCopy, i18n.T("pulls.pullsChecks.copyLog"), false).Layout), + action(th.IconAction(p.root, &l.external, icPullOut, i18n.T(forgeKey(v.forge, "pulls.pullsEmptyState.openOnGitHub", "pulls.pullsEmptyState.openOnGitLab")), false).Layout), + } + return layout.Inset{Left: rowInset, Right: rowInset, Top: ui.Space(1), Bottom: ui.Space(2)}.Layout(gtx, func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, children...) + }) +} + +// logFind is the search's field and which match is shown. Enter goes to the +// next one, Shift+Enter to the one before and Escape closes it. +func (v *pullView) logFind(gtx C, th *ui.Theme, steps []api.JobStep) D { + l := &v.log + if !l.finding { + return D{} + } + for { + ev, ok := gtx.Event( + key.Filter{Focus: &l.query, Name: key.NameReturn, Optional: key.ModShift}, + key.Filter{Focus: &l.query, Name: key.NameEscape}, + ) + if !ok { + break + } + e, ok := ev.(key.Event) + switch { + case !ok || e.State != key.Press: + case e.Name == key.NameEscape: + l.finding = false + l.query.SetText("") + gtx.Execute(key.FocusCmd{}) + case e.Modifiers.Contain(key.ModShift): + l.jump(steps, -1) + default: + l.jump(steps, 1) + } + } + count := "" + if l.found != "" { + count = fmt.Sprintf("%d/%d", min(l.at+1, len(l.matches)), len(l.matches)) + } + field := th.Input(&l.query, i18n.T("pulls.pullsChecks.search")) + field.Width, field.Height, field.TextSize = logFindWidth, ui.Space(7), ui.TextXS + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(th.Text(ui.TextXS, count).Mono().Muted().Layout), + ui.Gap(2), + layout.Rigid(field.Layout), + ) +} + +func (v *pullView) logRows(gtx C, th *ui.Theme, steps []api.JobStep) D { + l := &v.log + for i, click := range l.steps { + if click.Clicked(gtx) && len(steps[i].Lines) > 0 { + l.open[i] = !l.open[i] + } + } + list := th.ScrollArea(&l.rows) + list.AnchorStrategy = material.Overlay + return list.Layout(gtx, l.items(steps), func(gtx C, i int) D { + at := l.locate(steps, i) + st := steps[at.step] + switch { + case at.line >= 0: + return l.lineRow(gtx, th, st, at) + case st.Name == "": + return D{} + } + return stepRow(gtx, th, l.steps[at.step], st, l.open[at.step]) + }) +} + +// stepRow is a step's line, which folds what it printed. +func stepRow(gtx C, th *ui.Theme, click *ui.Clickable, st api.JobStep, open bool) D { + return th.NavRow(gtx, click, false, pullsLineHeight, rowInset, func(gtx C, th *ui.Theme) D { + ic, fg := checkGlyph(th, st.State) + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(inNodeColumn(func(gtx C) D { + if len(st.Lines) == 0 { + return D{} + } + return foldIcon(open).Layout(gtx, ui.Space(3.5), th.MutedForeground) + })), + layout.Rigid(layout.Spacer{Width: pullsLineGap}.Layout), + layout.Rigid(func(gtx C) D { return pullState(gtx, th, ic, checkGroupLabel(st.State), fg) }), + ui.Gap(2), + layout.Flexed(1, ui.Spanning(th.Text(ui.TextSM, st.Name).Layout)), + ui.Gap(2), + layout.Rigid(th.Text(ui.TextXS, checkDuration(st.StartedAt, st.CompletedAt, gtx.Now)).Mono().Muted().Layout), + ) + }) +} + +// lineRow is a numbered line of a step, filled while the search found it. +func (l *logView) lineRow(gtx C, th *ui.Theme, st api.JobStep, at logAt) D { + text, fg := logLine(th, st.Lines[at.line]) + number := strconv.Itoa(at.line + 1) + digits := strings.Repeat("0", max(len(strconv.Itoa(len(st.Lines))), 3)) + var bg color.NRGBA + if i, ok := slices.BinarySearchFunc(l.matches, at, func(a, b logAt) int { + return cmp.Or(cmp.Compare(a.step, b.step), cmp.Compare(a.line, b.line)) + }); ok { + bg = th.Over(ui.Alpha(th.ToneWait, 0.15)) + if i == l.at { + bg = th.Over(ui.Alpha(th.ToneWait, 0.35)) + } + } + inset := layout.Inset{Left: rowInset, Right: rowInset} + if at.line == 0 { + inset.Top = ui.Space(2) + } + if at.line == len(st.Lines)-1 { + inset.Bottom = ui.Space(2) + } + gtx.Constraints.Min.X = gtx.Constraints.Max.X + return inset.Layout(gtx, func(gtx C) D { + return layout.Background{}.Layout(gtx, + func(gtx C) D { return ui.Fill(gtx, bg, 0) }, + func(gtx C) D { + return layout.Inset{Top: logLineGap / 2, Bottom: logLineGap / 2}.Layout(gtx, func(gtx C) D { + width := naturalWidth(gtx, th.Text(ui.TextXS, digits).Mono().Layout) + return layout.Flex{}.Layout(gtx, + ui.FixedColumn(gtx.Metric.PxToDp(width), ui.AlignEnd(th.Text(ui.TextXS, number).Mono().Muted().Layout)), + ui.Gap(3.5), + layout.Flexed(1, th.Text(ui.TextXS, text).Mono().In(fg).Wrapped().Layout), + ) + }) + }) + }) +} + +// The markers GitHub's runner leaves in a log. +const ( + logError = "##[error]" + logWarning = "##[warning]" + logGroup = "##[group]" + logCommand = "[command]" +) + +// logLine is a line as it is shown: the runner's marker as the color it +// stands for. +func logLine(th *ui.Theme, line string) (string, color.NRGBA) { + line = strings.ReplaceAll(line, "\t", " ") + for _, m := range []struct { + marker string + fg color.NRGBA + }{{logError, th.Destructive}, {logWarning, th.ToneWait}, {logGroup, th.MutedForeground}, {logCommand, th.MutedForeground}} { + if text, ok := strings.CutPrefix(line, m.marker); ok { + return text, m.fg + } + } + return line, th.Foreground +} + +// logText is the whole log as text, the copy's. +func logText(steps []api.JobStep) string { + var b strings.Builder + for _, st := range steps { + for _, line := range st.Lines { + b.WriteString(line) + b.WriteByte('\n') + } + } + return b.String() +} + +// logResult is how the job ended, how long it took and when. +func logResult(c backend.CheckItem, now time.Time) string { + args := i18n.Args{"duration": checkDuration(c.StartedAt, c.CompletedAt, now), "ago": ""} + if at, err := time.Parse(time.RFC3339, c.CompletedAt); err == nil { + args["ago"] = agoLabel(at.Unix(), now) + } + if c.State == "failed" { + return i18n.T("pulls.pullsChecks.failedIn", args) + } + return i18n.T("pulls.pullsChecks.passedIn", args) +} diff --git a/native/cmd/lich-native/pulls_log_test.go b/native/cmd/lich-native/pulls_log_test.go new file mode 100644 index 000000000..2fd29036b --- /dev/null +++ b/native/cmd/lich-native/pulls_log_test.go @@ -0,0 +1,149 @@ +package main + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + + "gioui.org/io/key" + + "github.com/lichdotdev/lich/api" + "github.com/lichdotdev/lich/native/backend" + "github.com/lichdotdev/lich/native/i18n" +) + +func logFixture() []api.JobStep { + lines := make([]string, 40) + for i := range lines { + lines[i] = "ok" + } + lines[30] = logError + "Process completed with exit code 1." + return []api.JobStep{ + {Name: "Set up job", State: "passed", Lines: []string{"runner", "image"}}, + {Name: "Test", State: "failed", Lines: lines}, + {Name: "Clean up", State: "passed", Lines: []string{"bye"}}, + } +} + +func TestLogOpensTheFailedStepOnItsError(t *testing.T) { + steps := logFixture() + var l logView + l.arrive(steps) + if l.open[0] || !l.open[1] || l.open[2] { + t.Fatalf("open = %v, want the failed step alone", l.open) + } + if at := l.locate(steps, l.rows.Position.First); at != (logAt{1, 30 - logErrorContext}) { + t.Errorf("opened on %+v, want its error in view", at) + } + if got, want := l.items(steps), len(steps)+40; got != want { + t.Errorf("%d rows, want %d", got, want) + } + for i := range l.items(steps) { + if back := l.item(steps, l.locate(steps, i)); back != i { + t.Fatalf("row %d is %+v, which is row %d", i, l.locate(steps, i), back) + } + } + l.open[1] = false + l.arrive(steps) + if l.open[1] { + t.Error("the log unfolded the step again") + } +} + +func TestALogReadAgainWithMoreStepsIsOpenedAfresh(t *testing.T) { + steps := logFixture() + var l logView + l.arrive(steps[:1]) + l.query.SetText("runner") + l.search(steps[:1]) + l.arrive(steps) + l.search(steps) + if len(l.open) != len(steps) || !l.open[1] || len(l.matches) != 1 { + t.Errorf("open %v, matches %v, want every step known and the search kept", l.open, l.matches) + } +} + +func TestLogSearchGoesRoundItsMatchesOpeningTheirSteps(t *testing.T) { + steps := logFixture() + var l logView + l.arrive(steps) + l.query.SetText("YE") + l.search(steps) + if len(l.matches) != 1 || !l.open[2] { + t.Fatalf("matches %v, open %v, want the one in Clean up in view", l.matches, l.open) + } + l.query.SetText("ok") + l.search(steps) + if len(l.matches) != 39 { + t.Fatalf("%d matches, want 39", len(l.matches)) + } + l.jump(steps, -1) + if l.at != 38 { + t.Errorf("before the first is %d, want the last", l.at) + } + l.jump(steps, 1) + if l.at != 0 { + t.Errorf("after the last is %d, want the first", l.at) + } +} + +func TestLogLineTurnsTheRunnersMarkersIntoTheirColor(t *testing.T) { + th := testTheme() + for line, want := range map[string]string{"##[error]broke": "broke", "##[group]Run go test": "Run go test", "a\tb": "a b"} { + if got, _ := logLine(th, line); got != want { + t.Errorf("%q shows %q, want %q", line, got, want) + } + } + if _, fg := logLine(th, "##[error]broke"); fg != th.Destructive { + t.Error("an error is not red") + } +} + +// A finished job opens its log beside the checks, one lich cannot read the log +// of opens its page, and Escape closes the log before the pull request. +func TestPullsCheckOpensItsLogAndEscapeClosesItFirst(t *testing.T) { + u, r := pullsFrames(t) + const url = "https://github.com/o/r/actions/runs/1/job/2" + d := backend.PRDetail{Number: 7, URL: "https://github.com/o/r/pull/7", State: "OPEN", HeadRefName: "fix", BaseRefName: "main", + Checks: backend.ChecksRollup{Total: 2, Passed: 1, Failed: 1}, + CheckRuns: []backend.CheckItem{ + {Name: "windows", State: "failed", URL: url, HasLog: true}, + {Name: "coverage", State: "passed", URL: "https://ci.example.com/1"}, + }} + stub := &rpcStub{answer: func(method string, _ []json.RawMessage) (any, int) { + switch method { + case "project.ListPullRequests": + return []backend.PRSummary{{Number: 7, Title: "Fix the thing", State: "OPEN"}}, http.StatusOK + case "project.PullRequestDetail": + return d, http.StatusOK + case "project.PullRequestConversation": + return talkFixture(), http.StatusOK + case "project.JobLog": + return backend.JobLog{Steps: logFixture()}, http.StatusOK + } + return nil, http.StatusOK + }} + u.pulls.store = newPullsStore(t.Context(), stub.client(t), newForgeStore(stub.client(t), r.invalidate), r.invalidate) + r.waitFor(t, "Fix the thing") + r.clickLabel(t, "Fix the thing") + openPullsTab(t, r, tabChecks.label(), "windows") + r.clickLabel(t, "windows") + r.waitFor(t, "Process completed with exit code 1.") + if !r.shows(i18n.T("pulls.pullsChecks.all")) || !r.shows("coverage") { + t.Fatalf("the checks left with the log open:\n%s", r.drawn()) + } + r.router.Queue(key.Event{Name: key.NameEscape, State: key.Press}) + r.settle(t) + if u.pulls.view.log.url != "" || u.pulls.selected != 7 { + t.Fatalf("Escape left the log %q and #%d", u.pulls.view.log.url, u.pulls.selected) + } + var act pullsAction + u.pulls.view.openCheck(d.CheckRuns[1], &act) + if act.external != "https://ci.example.com/1" || u.pulls.view.log.url != "" { + t.Errorf("a check with no log opened %q and the log of %q", act.external, u.pulls.view.log.url) + } + if !strings.HasSuffix(logText(logFixture()), "bye\n") { + t.Error("the copy is not the whole log") + } +} diff --git a/native/cmd/lich-native/pulls_logic.go b/native/cmd/lich-native/pulls_logic.go index 9e0062f99..f250d6be5 100644 --- a/native/cmd/lich-native/pulls_logic.go +++ b/native/cmd/lich-native/pulls_logic.go @@ -1,12 +1,13 @@ package main import ( - "github.com/lichdotdev/lich/api" + "cmp" "slices" "strconv" "strings" "time" + "github.com/lichdotdev/lich/api" "github.com/lichdotdev/lich/native/backend" "github.com/lichdotdev/lich/native/i18n" ) @@ -15,35 +16,106 @@ import ( type pullsState string const ( - pullsOpen pullsState = "open" - pullsApproved pullsState = "approved" - pullsClosed pullsState = "closed" - pullsMerged pullsState = "merged" + pullsOpen pullsState = "open" + pullsClosed pullsState = "closed" + pullsMerged pullsState = "merged" ) -var pullsStates = []pullsState{pullsOpen, pullsApproved, pullsClosed, pullsMerged} +var pullsStates = []pullsState{pullsOpen, pullsClosed, pullsMerged} + +// pullNeed is what an open pull request waits on, the one thing its row says; +// needNothing is one that can merge. +type pullNeed int + +const ( + needNothing pullNeed = iota + needFix + needChanges + needChecks + needReviewer + needReview + needReady +) + +// needOf is pr's need, what blocks it soonest first. A draft needs to be +// marked ready whatever its checks say. +func needOf(pr backend.PRSummary) pullNeed { + checks := verdictOf(pr.Checks) + switch { + case pr.IsDraft: + return needReady + case checks == verdictFailed: + return needFix + case waitsOnReviewer(pr): + return needReviewer + case pr.ReviewDecision == "CHANGES_REQUESTED": + return needChanges + case checks == verdictPending: + return needChecks + case pr.ReviewDecision == "REVIEW_REQUIRED": + return needReview + } + return needNothing +} -// pullsFilter is a quick filter over the rows gh answered. -type pullsFilter int +// pullsGroup is a section of the open index, in the order it lists them. +type pullsGroup int const ( - filterAll pullsFilter = iota - filterReady - filterDrafts - filterFailing - pullsFilterCount + groupReady pullsGroup = iota + groupWork + groupReview + groupDrafts ) -func (f pullsFilter) label() string { - switch f { - case filterReady: - return i18n.T("pulls.pullsList.filter.ready") - case filterDrafts: - return i18n.T("pulls.pullsList.filter.drafts") - case filterFailing: - return i18n.T("pulls.pullsList.filter.failing") +func (n pullNeed) group() pullsGroup { + switch n { + case needNothing: + return groupReady + case needFix, needChanges: + return groupWork + case needReady: + return groupDrafts + } + return groupReview +} + +func (g pullsGroup) label() string { + switch g { + case groupReady: + return i18n.T("pulls.pullsList.group.ready") + case groupWork: + return i18n.T("pulls.pullsList.group.work") + case groupReview: + return i18n.T("pulls.pullsList.group.review") + } + return i18n.T("pulls.pullsList.group.drafts") +} + +// indexItem is one line of the index: a pull request of its rows, or the +// heading of the count that follow it. +type indexItem struct { + row int + group pullsGroup + count int // 0 for a pull request +} + +// indexItems is rows with a heading over each group; a state that is over has +// none. +func indexItems(rows []backend.PRSummary, state pullsState) []indexItem { + var items []indexItem + heading := -1 + for i, pr := range rows { + if g := needOf(pr).group(); state == pullsOpen && (heading < 0 || items[heading].group != g) { + heading = len(items) + items = append(items, indexItem{group: g}) + } + if heading >= 0 { + items[heading].count++ + } + items = append(items, indexItem{row: i}) } - return i18n.T("pulls.pullsList.filter.all") + return items } type checkVerdict int @@ -67,18 +139,6 @@ func verdictOf(c backend.ChecksRollup) checkVerdict { return verdictPassed } -func (f pullsFilter) matches(pr backend.PRSummary) bool { - switch f { - case filterReady: - return !pr.IsDraft - case filterDrafts: - return pr.IsDraft - case filterFailing: - return verdictOf(pr.Checks) == verdictFailed - } - return true -} - // matchesText matches text against the number with or without its "#", the // title, the author and the branch. func matchesText(pr backend.PRSummary, text string) bool { @@ -95,41 +155,42 @@ func matchesText(pr backend.PRSummary, text string) bool { return false } -// filterPulls is the rows the filter and the text keep, newest update first. -func filterPulls(list []backend.PRSummary, f pullsFilter, text string) []backend.PRSummary { +// filterPulls is the rows the text keeps in the index's order: by group while +// the pull requests are open, the newest update first. +func filterPulls(list []backend.PRSummary, state pullsState, text string) []backend.PRSummary { var rows []backend.PRSummary for _, pr := range list { - if f.matches(pr) && matchesText(pr, text) { + if matchesText(pr, text) { rows = append(rows, pr) } } - slices.SortStableFunc(rows, func(a, b backend.PRSummary) int { return strings.Compare(b.UpdatedAt, a.UpdatedAt) }) - return rows -} - -// filterCounts is how many rows each quick filter would keep under text. -func filterCounts(list []backend.PRSummary, text string) [pullsFilterCount]int { - var counts [pullsFilterCount]int - for _, pr := range list { - if !matchesText(pr, text) { - continue - } - for f := range counts { - if pullsFilter(f).matches(pr) { - counts[f]++ + slices.SortStableFunc(rows, func(a, b backend.PRSummary) int { + if state == pullsOpen { + if c := cmp.Compare(needOf(a).group(), needOf(b).group()); c != 0 { + return c } } - } - return counts + return strings.Compare(b.UpdatedAt, a.UpdatedAt) + }) + return rows } -// updatedAgo is the row's age; "" for a timestamp gh did not give. -func updatedAgo(iso string, now time.Time) string { +// shortAge is how long ago iso was in one unit, for a narrow column; "" for a +// timestamp gh did not give. +func shortAge(iso string, now time.Time) string { at, err := time.Parse(time.RFC3339, iso) if err != nil { return "" } - return agoLabel(at.Unix(), now) + hours := int(max(now.Sub(at), 0) / time.Hour) + days := hours / agoHoursPerDay + switch { + case hours < agoHoursPerDay: + return formatAge(max(now.Sub(at), time.Minute)) + case days < agoDaysPerWeek: + return i18n.T("session.age.day", i18n.Args{"count": days}) + } + return i18n.T("session.age.week", i18n.Args{"count": days / agoDaysPerWeek}) } var everyMergeMethod = []string{"squash", "merge", "rebase"} @@ -336,19 +397,3 @@ func durationUnit(unit string, value int) string { } return i18n.T("pulls.pullsLogic.durationHours", args) } - -// commitMeta is the commit's second line: who and when. -func commitMeta(c backend.PRCommit, now time.Time) string { - who := c.Login - if who == "" { - who = c.Name - } - at, err := time.Parse(time.RFC3339, c.Date) - if err != nil { - return who - } - if who == "" { - return agoLabel(at.Unix(), now) - } - return who + " · " + agoLabel(at.Unix(), now) -} diff --git a/native/cmd/lich-native/pulls_logic_test.go b/native/cmd/lich-native/pulls_logic_test.go index dd0c43a04..a073115d9 100644 --- a/native/cmd/lich-native/pulls_logic_test.go +++ b/native/cmd/lich-native/pulls_logic_test.go @@ -26,38 +26,29 @@ func numbers(rows []backend.PRSummary) []int { return out } -func TestFilterPullsKeepsWhatTheFilterAndTextAgreeOnNewestFirst(t *testing.T) { +func TestFilterPullsKeepsWhatTheTextMatchesNewestFirst(t *testing.T) { list := []backend.PRSummary{ summary(1, "old", false, 0, "2026-01-01T00:00:00Z"), summary(2, "draft", true, 0, "2026-03-01T00:00:00Z"), summary(3, "red", false, 2, "2026-02-01T00:00:00Z"), } cases := []struct { - filter pullsFilter - text string - want []int + text string + want []int }{ - {filterAll, "", []int{2, 3, 1}}, - {filterReady, "", []int{3, 1}}, - {filterDrafts, "", []int{2}}, - {filterFailing, "", []int{3}}, - {filterAll, "#3", []int{3}}, - {filterAll, "1", []int{1}}, - {filterAll, "feat/dr", []int{2}}, - {filterAll, "OCTO", []int{2, 3, 1}}, - {filterReady, "draft", nil}, + {"", []int{2, 3, 1}}, + {"#3", []int{3}}, + {"1", []int{1}}, + {"feat/dr", []int{2}}, + {"OCTO", []int{2, 3, 1}}, + {"nothing", nil}, } for _, c := range cases { - if got := numbers(filterPulls(list, c.filter, c.text)); !slices.Equal(got, c.want) { - t.Errorf("filterPulls(%v, %q) = %v, want %v", c.filter, c.text, got, c.want) + // A state that is over has no groups, so the date alone orders it. + if got := numbers(filterPulls(list, pullsMerged, c.text)); !slices.Equal(got, c.want) { + t.Errorf("filterPulls(%q) = %v, want %v", c.text, got, c.want) } } - if got := filterCounts(list, ""); got != [4]int{3, 2, 1, 1} { - t.Errorf("filterCounts = %v, want [3 2 1 1]", got) - } - if got := filterCounts(list, "red"); got != [4]int{1, 1, 0, 1} { - t.Errorf("filterCounts(red) = %v, want [1 1 0 1]", got) - } } func detail(state, mergeable, status, review string) backend.PRDetail { diff --git a/native/cmd/lich-native/pulls_overview.go b/native/cmd/lich-native/pulls_overview.go new file mode 100644 index 000000000..c6face02d --- /dev/null +++ b/native/cmd/lich-native/pulls_overview.go @@ -0,0 +1,270 @@ +package main + +import ( + "image" + "image/color" + "slices" + "strings" + + "gioui.org/layout" + "gioui.org/unit" + + "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" +) + +// The Overview's columns: the description held to a reading width, the facts +// at the right edge; an island narrower than overviewSplitWidth puts the +// facts over the description. +var ( + overviewProseWidth = unit.Dp(748) + overviewFactsWidth = unit.Dp(260) + overviewSplitWidth = unit.Dp(760) + // overviewTop is the room between the head and the panel's content. + overviewTop = ui.Space(3.5) + // editorTop and editorEdge set the description's box out by the room it + // keeps around its text, which stays where the prose was. + editorTop = ui.Space(1.5) + editorEdge = pullsRowEdge + // previewInset is the preview toggle's room in the box's corner. + previewInset = ui.Space(1.5) +) + +// overview is the description beside the pull request's facts. +func (v *pullView) overview(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, act *pullsAction) D { + facts := func(gtx C) D { return v.facts(gtx, th, p, d) } + if gtx.Constraints.Max.X < gtx.Dp(overviewSplitWidth) { + // Under the facts, the editor is as tall as the panel. + height := gtx.Constraints.Max.Y + return v.panelList(gtx, th, []layout.Widget{ + func(gtx C) D { + return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(2), Bottom: ui.Space(2)}.Layout(gtx, facts) + }, + func(gtx C) D { return v.description(gtx, th, p, d, act, height) }, + }) + } + return layout.Flex{}.Layout(gtx, + layout.Flexed(1, ui.Spanning(func(gtx C) D { + if v.edit.editing(d) && !v.edit.previewing { + return v.description(gtx, th, p, d, act, gtx.Constraints.Max.Y) + } + return v.panelList(gtx, th, []layout.Widget{func(gtx C) D { return v.description(gtx, th, p, d, act, 0) }}) + })), + ui.Gap(4), + layout.Rigid(func(gtx C) D { + return layout.Inset{Top: overviewTop, Right: pullsRowEdge}.Layout(gtx, func(gtx C) D { + gtx.Constraints.Min.X, gtx.Constraints.Max.X = gtx.Dp(overviewFactsWidth), gtx.Dp(overviewFactsWidth) + return facts(gtx) + }) + }), + ) +} + +// description is the pull request's Markdown, or while it is edited the box +// holding it, height tall, with the toggle that previews it in the corner. +func (v *pullView) description(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, act *pullsAction, height int) D { + s := &v.edit + if !s.editing(d) { + return proseColumn(gtx, func(gtx C) D { return v.prose(gtx, th, d.URL, d.Body, act) }) + } + gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(overviewProseWidth+2*pullsPadX-editorEdge)) + return layout.Stack{Alignment: layout.NE}.Layout(gtx, + layout.Stacked(func(gtx C) D { + gtx.Constraints.Min.X = gtx.Constraints.Max.X + if s.previewing { + return proseColumn(gtx, func(gtx C) D { return v.prose(gtx, th, d.URL, s.body.Text(), act) }) + } + return layout.Inset{Left: editorEdge, Top: editorTop, Bottom: pullsPadX}.Layout(gtx, func(gtx C) D { + return v.descriptionEditor(gtx, th, d, act, max(height-gtx.Dp(editorTop+pullsPadX), 0)) + }) + }), + layout.Stacked(func(gtx C) D { + return layout.Inset{Top: editorTop + previewInset, Right: previewInset}.Layout(gtx, func(gtx C) D { return v.previewToggle(gtx, th, p) }) + }), + ) +} + +func (v *pullView) prose(gtx C, th *ui.Theme, url, body string, act *pullsAction) D { + body = strings.TrimSpace(body) + if body == "" { + return th.Text(ui.TextSM, i18n.T("pulls.pullsOverview.noDescription")).Muted().Layout(gtx) + } + return v.md.Layout(gtx, th, "body:"+url, body, act.open) +} + +// proseColumn is the description's column: the reading width, inset as the +// lists' rows. +func proseColumn(gtx C, w layout.Widget) D { + gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(overviewProseWidth+2*pullsPadX)) + return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(2.5), Bottom: ui.Space(5)}.Layout(gtx, w) +} + +// factHeight is a fact's line, closer than a list's: the facts are one block. +var factHeight = unit.Dp(26) + +// factLine is one fact: a glyph, what it says, and a muted note. click nil is +// a fact that leads nowhere. +func factLine(gtx C, th *ui.Theme, click *ui.Clickable, ic *icons.Icon, fg color.NRGBA, text, note string) D { + content := func(gtx C, th *ui.Theme) D { + gtx.Constraints.Min.X = gtx.Constraints.Max.X + label := th.Text(ui.TextXS, text) + children := []layout.FlexChild{ + layout.Rigid(inNodeColumn(func(gtx C) D { return pullGlyph(gtx, th, ic, ui.Space(3.5), fg) })), + layout.Rigid(layout.Spacer{Width: pullsLineGap}.Layout), + } + if note == "" { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, append(children, layout.Flexed(1, ui.Spanning(label.Layout)))...) + } + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, append(children, + layout.Rigid(label.Layout), + layout.Rigid(layout.Spacer{Width: pullsLineGap}.Layout), + layout.Flexed(1, ui.Spanning(th.Text(ui.TextXS, note).Muted().Layout)), + )...) + } + if click != nil { + return th.NavRow(gtx, click, false, factHeight, 0, content) + } + gtx.Constraints.Min = image.Pt(gtx.Constraints.Max.X, gtx.Dp(factHeight)) + return layout.W.Layout(gtx, func(gtx C) D { return content(gtx, th) }) +} + +// facts is what the pull request is: its branches, whether it merges, its +// checks and reviewers, then the sessions and the checkout its branch has +// here. What it does not have is left out. +func (v *pullView) facts(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail) D { + if v.checksFact.Clicked(gtx) { + v.showTab(d, tabChecks) + } + lines := []layout.Widget{func(gtx C) D { return v.branchesFact(gtx, th, p, d) }} + if ic, text, fg, ok := mergeableStat(th, d); ok { + lines = append(lines, func(gtx C) D { + if conflictsWithBase(d) && v.forge != api.ForgeGitLab { + return v.conflictsFact(gtx, th, p, d) + } + return factLine(gtx, th, nil, ic, fg, text, "") + }) + } + if ic, text, fg, ok := checksStat(th, d.Checks); ok { + lines = append(lines, func(gtx C) D { return factLine(gtx, th, &v.checksFact, ic, fg, text, "") }) + } + lines = append(lines, v.reviewerLines(gtx, th, p, d)...) + if wt, ok := p.checkedOut(d.HeadRefName); ok { + lines = append(lines, layout.Spacer{Height: ui.Space(3)}.Layout) + for _, id := range p.sessionsIn(p.project.ID, wt.Path) { + lines = append(lines, func(gtx C) D { + return factLine(gtx, th, nil, icPullSession, th.MutedForeground, p.sessionLabel(id), "") + }) + } + lines = append(lines, func(gtx C) D { return factLine(gtx, th, nil, icCheckout, th.MutedForeground, checkoutName(wt), "") }) + } + children := make([]layout.FlexChild, len(lines)) + for i, w := range lines { + children[i] = layout.Rigid(w) + } + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, children...) +} + +// branchesFact is the head and base under the state's glyph; who opened the +// pull request is in its tooltip. +func (v *pullView) branchesFact(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail) D { + ic, fg, word := stateStat(th, d) + note := "" + if d.IsDraft && d.State == "OPEN" { + note = word + } + by := i18n.T("pulls.pullsOverview.openedBy", i18n.Args{"author": d.Author}) + return v.withTip(gtx, th, p, "branches", by, func(gtx C) D { + return factLine(gtx, th, nil, ic, fg, d.HeadRefName+" → "+d.BaseRefName, note) + }) +} + +// reviewerLines is a line per reviewer, what each said beside the name, which +// opens the conversation. A review the base asks for and nobody was named for +// is a line of its own. +func (v *pullView) reviewerLines(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail) []layout.Widget { + if len(d.Reviewers) == 0 { + if d.ReviewDecision != "REVIEW_REQUIRED" || d.State != "OPEN" { + return nil + } + return []layout.Widget{func(gtx C) D { + return factLine(gtx, th, nil, icPullDashed, th.MutedForeground, i18n.T("pulls.pullsStats.reviewRequired"), "") + }} + } + open, total := 0, 0 + if asked := slices.IndexFunc(d.Reviewers, asksForChanges); asked >= 0 && !slices.ContainsFunc(d.Reviewers[asked+1:], asksForChanges) { + // The threads do not say whose verdict they hold, so only one that + // stands alone is told by them. + open, total = threadTally(p.store.conversation(p.project.Path, d.Number).val) + } + var lines []layout.Widget + for _, r := range d.Reviewers { + click := clickableOf(v.reviewerFacts, r.Login) + if click.Clicked(gtx) { + v.showTab(d, tabConversation) + } + ic, fg, note := reviewerState(th, r, open, total) + if v.forge == api.ForgeGitLab { + click = nil + } + lines = append(lines, func(gtx C) D { return factLine(gtx, th, click, ic, fg, r.Login, note) }) + } + return lines +} + +func asksForChanges(r backend.PRReviewer) bool { return r.State == "CHANGES_REQUESTED" } + +// reviewerState is a reviewer's verdict: its glyph and what it says. Asked +// changes are told by their threads, open of total, when there are any: +// GitHub keeps the verdict until the reviewer moves. +func reviewerState(th *ui.Theme, r backend.PRReviewer, open, total int) (*icons.Icon, color.NRGBA, string) { + verdict, _ := reviewVerdict(r.State) + switch { + case r.State == "APPROVED": + return icPullCheck, th.TonePass, verdict + case asksForChanges(r) && total > 0 && open == 0: + return icPullCheck2, th.ToneWait, i18n.T("pulls.pullsOverview.threadsResolved") + case asksForChanges(r) && total > 0: + return icPullX, th.Destructive, i18n.T("pulls.pullsOverview.threadsOpen", i18n.Args{"open": open, "total": total}) + case asksForChanges(r): + return icPullX, th.Destructive, verdict + case r.State == "": + verdict = i18n.T("pulls.verdict.requested") + } + if r.IsTeam { + return icPullTeam, th.MutedForeground, verdict + } + return icPullDashed, th.MutedForeground, verdict +} + +// stateStat is the pull request's state as a glyph and the word for it. +func stateStat(th *ui.Theme, d backend.PRDetail) (*icons.Icon, color.NRGBA, string) { + switch { + case d.State == "MERGED": + return icPullMerged, th.MutedForeground, i18n.T("pulls.pullsStats.merged") + case d.State == "CLOSED": + return icPullX, th.MutedForeground, i18n.T("pulls.pullsStats.closed") + case d.IsDraft: + // muted as in the list: amber is a verdict waiting on its reviewer + return icPullDashed, th.MutedForeground, i18n.T("pulls.pullsStats.draft") + } + return icPullRequests, th.TonePass, i18n.T("pulls.pullsStats.open") +} + +// reviewVerdict is what a review state says its author did, ok false for a +// state GitHub has but this window has no words for. +func reviewVerdict(state string) (text string, ok bool) { + switch state { + case "APPROVED": + return i18n.T("pulls.verdict.approved"), true + case "CHANGES_REQUESTED": + return i18n.T("pulls.verdict.changesRequested"), true + case "COMMENTED": + return i18n.T("pulls.verdict.commented"), true + case "DISMISSED": + return i18n.T("pulls.verdict.dismissed"), true + } + return "", false +} diff --git a/native/cmd/lich-native/pulls_panels.go b/native/cmd/lich-native/pulls_panels.go index 5e804249f..851641fe9 100644 --- a/native/cmd/lich-native/pulls_panels.go +++ b/native/cmd/lich-native/pulls_panels.go @@ -1,10 +1,11 @@ package main import ( + "io" "strings" - "time" "gioui.org/font" + "gioui.org/io/clipboard" "gioui.org/layout" "gioui.org/unit" "gioui.org/widget/material" @@ -15,10 +16,10 @@ import ( "github.com/lichdotdev/lich/native/ui" ) -// actions is the header's buttons, left to right: the hand-off a failing or -// conflicting pull request offers, Send open threads, the session, the pending review while one -// is written, Merge, and ⋯ with Approve, Refresh and Open on GitHub. While the -// title and description are edited they are Cancel and Save. +// actions is the header's buttons, left to right: what the pull request's +// state asks for, outlined (the hand-off a failing or conflicting one offers, +// Send open threads, Submit review while one is written), the session, Merge +// and ⋯. While the title and description are edited they are Cancel and Save. func (v *pullView) actions(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, act *pullsAction) D { if v.edit.editing(d) { return v.editActions(gtx, th) @@ -39,20 +40,20 @@ func (v *pullView) actions(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDeta if threads := v.sendOpenThreads(gtx, th, p, d, busy, act); threads != nil { items = append(items, ui.WrapItem(threads)) } - items = append(items, ui.WrapItem(func(gtx C) D { return v.sessionButton(gtx, th, p, d, busy, blocked) })) if len(v.pendingOf(d.URL).snapshot()) > 0 { items = append(items, ui.WrapItem(func(gtx C) D { return v.reviewButton(gtx, th, p, d, reviewBlocked) })) } items = append(items, - ui.WrapItem(func(gtx C) D { return v.moreButton(gtx, th, p, d, busy, reviewBlocked, act) }), + ui.WrapItem(func(gtx C) D { return v.sessionButton(gtx, th, p, d, busy, blocked) }), ui.WrapItem(func(gtx C) D { return v.mergeButton(gtx, th, p, d, busy, act) }), + ui.WrapItem(func(gtx C) D { return v.moreButton(gtx, th, p, d, busy, reviewBlocked, act) }), ) return ui.Wrap{GapX: ui.Space(2), GapY: ui.Space(2), Justify: ui.JustifyEnd}.Layout(gtx, items...) } // moreButton is ⋯: Approve while no review is being written on somebody -// else's pull request (never on a GitLab merge request), Refresh and Open on -// GitHub. +// else's pull request (never on a GitLab merge request), the link and the +// description to copy, Refresh and Open on GitHub. func (v *pullView) moreButton(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, busy, reviewBlocked string, act *pullsAction) D { var entries []ui.MenuEntry if len(v.pendingOf(d.URL).snapshot()) == 0 && !v.ownPR(p, d) && v.forge != api.ForgeGitLab { @@ -68,16 +69,24 @@ func (v *pullView) moreButton(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRD OnClick: func() { act.approve = true }}) } url := d.URL + var copied string entries = append(entries, + ui.MenuEntry{Kind: ui.MenuSeparator}, + ui.MenuEntry{Label: i18n.T("pulls.pullsOverview.copyLink"), Icon: icPRLinked, OnClick: func() { copied = url }}, + ui.MenuEntry{Label: i18n.T("pulls.pullsOverview.copyMarkdown"), Icon: icMenuCopy, Disabled: strings.TrimSpace(d.Body) == "", OnClick: func() { copied = d.Body }}, ui.MenuEntry{Kind: ui.MenuSeparator}, ui.MenuEntry{Label: i18n.T("pulls.pullRequestView.refresh"), Icon: icPullRefresh, OnClick: func() { act.refresh = true }}, ui.MenuEntry{Label: i18n.T(forgeKey(v.forge, "pulls.pullsEmptyState.openOnGitHub", "pulls.pullsEmptyState.openOnGitLab")), Icon: icPullOut, OnClick: func() { act.external = url }}, ) b := th.Button(&v.moreClick, "") b.Icon, b.Variant, b.Size = icPullMore, ui.VariantGhost, ui.SizeIconSM - return v.withTip(gtx, th, p, "more", i18n.T("pulls.pullsNav.more"), func(gtx C) D { + dims := v.withTip(gtx, th, p, "more", i18n.T("pulls.pullsNav.more"), func(gtx C) D { return th.DropdownMenu(p.root, &v.moreMenu, entries).Layout(gtx, b.Layout) }) + if copied != "" { + gtx.Execute(clipboard.WriteCmd{Type: "application/text", Data: io.NopCloser(strings.NewReader(copied))}) + } + return dims } // handoffButton is Resolve conflicts or Fix checks, handing the pull request @@ -113,7 +122,7 @@ func (v *pullView) sessionButton(gtx C, th *ui.Theme, p *pullsScreen, d backend. label = i18n.T("pulls.pullRequestView.opening") } b := th.Button(&v.session, label) - b.Icon, b.Variant, b.Size, b.Disabled = icPullSession, ui.VariantSecondary, ui.SizeSM, blocked != "" || busy != "" + b.Icon, b.Variant, b.Size, b.Disabled = icPullSession, ui.VariantGhost, ui.SizeSM, blocked != "" || busy != "" return p.tour.Anchor(gtx, tourPullsSession, func(gtx C) D { return v.withTip(gtx, th, p, "session", blocked, b.Layout) }) } @@ -139,7 +148,16 @@ func (v *pullView) withTip(gtx C, th *ui.Theme, p *pullsScreen, key, text string // mergeButton is the Merge menu: the methods the base's rules allow, every // one a bypass or none, enabled past a block only where a bypass is offered. +// On a pull request that is over it only says how it ended. func (v *pullView) mergeButton(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, busy string, act *pullsAction) D { + if d.State != "OPEN" { + over := th.Button(&v.mergeClick, i18n.T("pulls.pullsStats.merged")) + over.Icon, over.Variant, over.Size, over.Disabled = icPullMerged, ui.VariantGhost, ui.SizeSM, true + if d.State == "CLOSED" { + over.Icon, over.Text = icPullX, i18n.T("pulls.pullsStats.closed") + } + return over.Layout(gtx) + } rules := p.store.branchRules(p.project.Path, d.BaseRefName) bypass := canAdminOverride(d, rules) blocked := mergeBlockedReason(d, v.forge) != "" && !bypass @@ -156,9 +174,6 @@ func (v *pullView) mergeButton(gtx C, th *ui.Theme, p *pullsScreen, d backend.PR if busy == "merge" { label = i18n.T("pulls.pullRequestView.merging") } - if d.Checks.Failed > 0 && busy != "merge" { - label = i18n.T("pulls.pullsPanels.mergeFailing", i18n.Args{"count": d.Checks.Failed}) - } b := th.Button(&v.mergeClick, label) b.Icon, b.Size, b.Disabled = icPullMerged, ui.SizeSM, blocked || busy != "" if b.Disabled { @@ -175,27 +190,23 @@ const ( conflictsPanelHeight = unit.Dp(260) ) -// conflictsStat is the "Conflicts with" stat, face: once the files are known -// it opens a panel naming them, and until then its tooltip says why not. -func (v *pullView) conflictsStat(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, face layout.Widget) D { +// conflictsFact is the "Conflicts with" fact: once the files are known it +// counts them and opens a panel naming them, and until then its tooltip says +// why not. +func (v *pullView) conflictsFact(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail) D { + text := i18n.T("pulls.pullsStats.conflictsWith", i18n.Args{"base": d.BaseRefName}) read := p.store.conflictFiles(p.project.Path, &d) if hint := conflictsHint(read); hint != "" { - return v.withTip(gtx, th, p, "conflicts", hint, face) + return v.withTip(gtx, th, p, "conflicts", hint, func(gtx C) D { + return factLine(gtx, th, nil, icPullX, th.Destructive, text, "") + }) } files := read.val pop := th.DropdownPanel(p.root, &v.conflictsPanel, conflictsPanelWidth, func(gtx C, th *ui.Theme) D { return v.conflictsList(gtx, th, files) }) count := i18n.T("pulls.pullsStats.conflictFiles", i18n.Args{"count": len(files)}) - return pop.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(face), - ui.Gap(1.5), - layout.Rigid(th.Text(ui.TextXS, count).Muted().Layout), - ui.Gap(1), - layout.Rigid(func(gtx C) D { return icChevronDown.Layout(gtx, ui.Space(3.5), th.MutedForeground) }), - ) - }) + return pop.Layout(gtx, func(gtx C) D { return factLine(gtx, th, nil, icPullX, th.Destructive, text, count) }) } // conflictsHint is why the conflicting files cannot be listed yet, empty @@ -212,18 +223,10 @@ func conflictsHint(read pullsRead[[]string]) string { return "" } -// conflictsList is the panel's content: the count, then a row per file. +// conflictsList is the panel's content: a row per file. func (v *pullView) conflictsList(gtx C, th *ui.Theme, files []string) D { gtx.Constraints.Max.Y = min(gtx.Constraints.Max.Y, gtx.Dp(conflictsPanelHeight)) - heading := i18n.T("pulls.pullsConflicts.count", i18n.Args{"count": len(files)}) - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return layout.Inset{Left: ui.Space(2), Right: ui.Space(2), Top: ui.Space(1.5), Bottom: ui.Space(1)}.Layout(gtx, th.SectionHeading(heading).Layout) - }), - layout.Rigid(func(gtx C) D { - return th.ScrollArea(&v.conflictsRows).Layout(gtx, len(files), func(gtx C, i int) D { return conflictRow(gtx, th, files[i]) }) - }), - ) + return th.ScrollArea(&v.conflictsRows).Layout(gtx, len(files), func(gtx C, i int) D { return conflictRow(gtx, th, files[i]) }) } // conflictRow is one conflicting file: its name, then its directory dimmed, @@ -253,7 +256,7 @@ func (v *pullView) panelLayout(gtx C, th *ui.Theme, p *pullsScreen, d backend.PR case tabCommits: rows = v.commitRows(gtx, th, d) case tabChecks: - rows = v.checkRows(gtx, th, d, act) + return v.checksTab(gtx, th, p, d, act) default: return v.overview(gtx, th, p, d, act) } @@ -266,6 +269,7 @@ func (v *pullView) panelScroll(d backend.PRDetail) { at := panelAt{url: d.URL, tab: v.openTab(d)} if at != v.panelAt { v.panel.Position, v.panelAt = layout.Position{}, at + v.log.close() } } @@ -278,298 +282,6 @@ func (v *pullView) panelList(gtx C, th *ui.Theme, rows []layout.Widget) D { }) } -// The Overview's columns: the description held to a reading width, the facts -// beside it; an island narrower than overviewSplitWidth puts the facts over -// the description. -var ( - overviewProseWidth = unit.Dp(720) - overviewFactsWidth = unit.Dp(320) - overviewSplitWidth = unit.Dp(760) - // overviewHeadingBottom is the room under the fixed Description heading, - // over its separator. - overviewHeadingBottom = ui.Space(2.5) -) - -// overview is the description beside the pull request's facts. -func (v *pullView) overview(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, act *pullsAction) D { - // Stacked under the facts, the editor is as tall as the panel. - rows := v.overviewRows(th, d, act, gtx.Constraints.Max.Y) - heading := func(gtx C) D { - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(4)}.Layout(gtx, func(gtx C) D { - return v.descriptionHeading(gtx, th, p, d) - }) - } - if gtx.Constraints.Max.X < gtx.Dp(overviewSplitWidth) { - facts := func(gtx C) D { - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(4)}.Layout(gtx, func(gtx C) D { return v.facts(gtx, th, p, d) }) - } - return v.panelList(gtx, th, append([]layout.Widget{facts, heading}, rows...)) - } - // The heading stays put over the description scrolling under it, the - // separator marking where the scroll starts. - description := func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return layout.Inset{Top: ui.Space(1), Bottom: overviewHeadingBottom}.Layout(gtx, heading) - }), - layout.Flexed(1, func(gtx C) D { - if v.edit.editing(d) && !v.edit.previewing { - return layout.Inset{Top: ui.Space(1), Bottom: pullsPadX}.Layout(gtx, func(gtx C) D { - return proseColumn(gtx, func(gtx C) D { return v.descriptionEditor(gtx, th, d, act, gtx.Constraints.Max.Y) }) - }) - } - return v.panelList(gtx, th, rows) - }), - ) - } - return layout.Flex{}.Layout(gtx, - layout.Flexed(1, description), - layout.Rigid(func(gtx C) D { return th.VerticalRule(gtx) }), - layout.Rigid(func(gtx C) D { - w := gtx.Dp(overviewFactsWidth) - gtx.Constraints.Min.X, gtx.Constraints.Max.X = w, w - return layout.Inset{Left: ui.Space(5), Right: ui.Space(5), Top: ui.Space(5)}.Layout(gtx, func(gtx C) D { return v.facts(gtx, th, p, d) }) - }), - ) -} - -// facts is what the status line says on the other tabs, told in full: who -// reviews it, the checks, whether it merges, and the checkout and sessions -// its branch sits in. -func (v *pullView) facts(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail) D { - vs := v.verdicts(gtx, th, p, d) - var children []layout.FlexChild - section := func(title string, body ...layout.Widget) { - if len(children) > 0 { - children = append(children, ui.VGap(5)) - } - children = append(children, layout.Rigid(th.SectionHeading(title).Layout)) - for _, w := range body { - if w != nil { - children = append(children, ui.VGap(2), layout.Rigid(w)) - } - } - } - section(i18n.T("pulls.pullsOverview.reviewers"), vs.review, func(gtx C) D { return reviewerChips(gtx, th, d.Reviewers) }) - if vs.checks != nil { - section(i18n.T("pulls.pullRequestView.tab.checks"), vs.checks) - } - if vs.merge != nil { - section(i18n.T("pulls.pullRequestView.merge"), vs.merge) - } - section(i18n.T("pulls.pullsNav.checkout"), v.checkoutFact(th, p, d)...) - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, children...) -} - -// checkoutFact is the checkout the branch sits in and the sessions in it, or -// that it sits in none. -func (v *pullView) checkoutFact(th *ui.Theme, p *pullsScreen, d backend.PRDetail) []layout.Widget { - wt, ok := p.checkedOut(d.HeadRefName) - if !ok { - return []layout.Widget{th.Text(ui.TextSM, i18n.T("pulls.pullsNav.notCheckedOut")).Muted().Layout} - } - out := []layout.Widget{func(gtx C) D { return th.MetaGlyph(icCheckout, checkoutName(wt), th.Foreground).Layout(gtx) }} - for _, id := range p.sessionsIn(p.project.ID, wt.Path) { - out = append(out, func(gtx C) D { return th.MetaGlyph(icPullSession, p.sessionLabel(id), th.MutedForeground).Layout(gtx) }) - } - return out -} - -// overviewRows is the description, held to a reading width, or its draft -// while it is edited: the editor editorHeight tall, or the draft rendered. Its -// heading spans the column. -func (v *pullView) overviewRows(th *ui.Theme, d backend.PRDetail, act *pullsAction, editorHeight int) []layout.Widget { - return []layout.Widget{func(gtx C) D { - return proseColumn(gtx, func(gtx C) D { - body := d.Body - if s := &v.edit; s.editing(d) { - if !s.previewing { - return v.descriptionEditor(gtx, th, d, act, editorHeight) - } - body = s.body.Text() - } - if strings.TrimSpace(body) == "" { - return th.Text(ui.TextSM, i18n.T("pulls.pullsOverview.noDescription")).Muted().Layout(gtx) - } - return v.md.Layout(gtx, th, "body:"+d.URL, strings.TrimSpace(body), act.open) - }) - }} -} - -// proseColumn is the description's column: the reading width, inset as the -// Overview's rows. -func proseColumn(gtx C, w layout.Widget) D { - gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(overviewProseWidth+2*pullsPadX)) - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(2)}.Layout(gtx, w) -} - -// reviewVerdict is what a review state says its author did, ok false for a -// state GitHub has but this window has no words for. -func reviewVerdict(state string) (text string, ok bool) { - switch state { - case "APPROVED": - return i18n.T("pulls.verdict.approved"), true - case "CHANGES_REQUESTED": - return i18n.T("pulls.verdict.changesRequested"), true - case "COMMENTED": - return i18n.T("pulls.verdict.commented"), true - case "DISMISSED": - return i18n.T("pulls.verdict.dismissed"), true - } - return "", false -} - -// reviewerChips is the reviewers row: each login and what they said. -func reviewerChips(gtx C, th *ui.Theme, reviewers []backend.PRReviewer) D { - if len(reviewers) == 0 { - return th.Text(ui.TextSM, i18n.T("pulls.pullsOverview.nobodyYet")).Muted().Layout(gtx) - } - items := make([]ui.WrapChild, len(reviewers)) - for i, r := range reviewers { - fg := th.MutedForeground - ic := icPullDashed - switch r.State { - case "APPROVED": - fg, ic = th.TonePass, icPullCheck - case "CHANGES_REQUESTED": - fg, ic = th.Destructive, icPullX - } - if r.IsTeam { - ic = icPullTeam - } - verdict, _ := reviewVerdict(r.State) - if r.State == "" { - verdict = i18n.T("pulls.verdict.requested") - } - items[i] = ui.WrapItem(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.5), fg) }), - ui.Gap(1.5), - layout.Rigid(th.Text(ui.TextSM, r.Login).Layout), - ui.Gap(1), - layout.Rigid(th.Text(ui.TextXS, verdict).Muted().Layout), - ) - }) - } - return ui.Wrap{GapX: ui.Space(4), GapY: ui.Space(1.5)}.Layout(gtx, items...) -} - -// commitRows is PullsCommits: each commit, its body behind a click, and on -// hover View changes. -func (v *pullView) commitRows(gtx C, th *ui.Theme, d backend.PRDetail) []layout.Widget { - if len(d.Commits) == 0 { - return []layout.Widget{func(gtx C) D { return th.PanelNotice(i18n.T("pulls.pullsCommits.none"), pullsPadX).Layout(gtx) }} - } - now := gtx.Now - rows := make([]layout.Widget, len(d.Commits)) - for i, c := range d.Commits { - open := boolOf(v.commitOpen, c.OID) - click := clickableOf(v.commitClicks, c.OID) - body := strings.TrimSpace(c.Body) - rows[i] = func(gtx C) D { - if click.Clicked(gtx) && body != "" { - open.Value = !open.Value - } - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - view := func(gtx C) D { return v.viewChanges(gtx, th, d, i) } - return commitRow(gtx, th, c, click, body != "", open.Value, now, view) - }), - layout.Rigid(func(gtx C) D { - if !open.Value { - return D{} - } - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Bottom: ui.Space(3)}.Layout(gtx, func(gtx C) D { - return th.Text(ui.TextXS, body).Muted().Wrapped().Layout(gtx) - }) - }), - ) - } - } - return rows -} - -// commitRow is a commit's headline, who and when, view while the row is -// hovered, the chevron when it has a body to open, and its short oid. -func commitRow(gtx C, th *ui.Theme, c backend.PRCommit, click *ui.Clickable, hasBody, open bool, now time.Time, view layout.Widget) D { - return th.PanelRow(gtx, click, hasBody, pullsRowEdge, pullsRowPadX, func(gtx C, th *ui.Theme) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(th.Text(ui.TextSM, c.Headline).Weight(font.Medium).Layout), - layout.Rigid(th.Text(ui.TextXS, commitMeta(c, now)).Muted().Layout), - ) - }), - layout.Rigid(func(gtx C) D { - if !click.Hovered() { - return D{} - } - return layout.Inset{Right: ui.Space(2)}.Layout(gtx, view) - }), - layout.Rigid(func(gtx C) D { - if !hasBody { - return D{} - } - ic := icPullRight - if open { - ic = icPullDown - } - return layout.Inset{Right: ui.Space(2)}.Layout(gtx, func(gtx C) D { return ic.Layout(gtx, ui.Space(3.5), th.MutedForeground) }) - }), - layout.Rigid(th.Text(ui.TextXS, shortOID(c.OID)).Mono().Muted().Layout), - ) - }) -} - -// checkRows is PullsChecks: each check, its run opened in the browser. -func (v *pullView) checkRows(gtx C, th *ui.Theme, d backend.PRDetail, act *pullsAction) []layout.Widget { - if len(d.CheckRuns) == 0 { - return []layout.Widget{func(gtx C) D { return th.PanelNotice(i18n.T("pulls.pullsChecks.none"), pullsPadX).Layout(gtx) }} - } - now := gtx.Now - rows := make([]layout.Widget, len(d.CheckRuns)) - for i, c := range d.CheckRuns { - click := clickableOf(v.checkClicks, c.Name+"\n"+c.URL) - rows[i] = func(gtx C) D { - if click.Clicked(gtx) && c.URL != "" { - act.external = c.URL - } - ic, fg := icPullCheck, th.TonePass - switch c.State { - case "failed": - ic, fg = icPullX, th.Destructive - case "pending": - ic, fg = icPullRunning, th.ToneWait - } - return th.PanelRow(gtx, click, c.URL != "", pullsRowEdge, pullsRowPadX, func(gtx C, th *ui.Theme) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { return pullGlyph(gtx, th, ic, ui.Space(4), fg) }), - ui.Gap(3), - layout.Flexed(1, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(th.Text(ui.TextSM, c.Name).Layout), - layout.Rigid(func(gtx C) D { - if c.Description == "" { - return D{} - } - return th.Text(ui.TextXS, c.Description).Muted().Layout(gtx) - }), - ) - }), - layout.Rigid(func(gtx C) D { - if !c.Required { - return D{} - } - return layout.Inset{Right: ui.Space(3)}.Layout(gtx, th.TinyChip(i18n.T("pulls.pullsChecks.required"), th.MutedForeground).Layout) - }), - layout.Rigid(th.Text(ui.TextXS, checkDuration(c.StartedAt, c.CompletedAt, now)).Muted().Layout), - ) - }) - } - } - return rows -} - func boolOf(m map[string]*ui.Bool, id string) *ui.Bool { b, ok := m[id] if !ok { diff --git a/native/cmd/lich-native/pulls_skeleton.go b/native/cmd/lich-native/pulls_skeleton.go index 2fe9f573f..b064e59f6 100644 --- a/native/cmd/lich-native/pulls_skeleton.go +++ b/native/cmd/lich-native/pulls_skeleton.go @@ -9,151 +9,67 @@ import ( "github.com/lichdotdev/lich/native/ui/markdown" ) -// The line heights the list's and rows' bars sit in, so each bar takes the -// room of the text it stands for: text-sm and text-xs. -var ( - skeletonSMLine = ui.Space(5) - skeletonXSLine = ui.Space(4) -) - -// detailSkeleton mirrors body while the pull request loads, skeletonHeading -// standing in for its title row: the tab strip, its labels known before the -// pull request is, and the open tab's content, each bar where its text will -// land. -func (v *pullView) detailSkeleton(th *ui.Theme) layout.Widget { - return func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return layout.Inset{Left: pullsToolbarPad, Right: pullsToolbarPad}.Layout(gtx, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - ui.VGap(4), - layout.Rigid(func(gtx C) D { return v.skeletonTabs(gtx, th) }), - ) - }) - }), - layout.Flexed(1, func(gtx C) D { - return v.skeletonTab(gtx, th) - }), - ) - } -} - -// skeletonHeading is titleRow: heading's title over the stats line, beside -// the actions Open in Session, Merge and ⋯ as blocks of their size. +// skeletonHeading is titleRow: the title beside the actions Open in Session, +// Merge and ⋯ as blocks of their size. func skeletonHeading(gtx C, th *ui.Theme) D { var session, merge, more ui.Clickable - actions := func(gtx C) D { - sessionB := th.Button(&session, i18n.T("pulls.pulls.openInSession")) - sessionB.Icon, sessionB.Size = icPullSession, ui.SizeSM - mergeB := th.Button(&merge, i18n.T("pulls.pullRequestView.merge")) - mergeB.Icon, mergeB.Size = icPullMerged, ui.SizeSM - moreB := th.Button(&more, "") - moreB.Icon, moreB.Size = icPullMore, ui.SizeIconSM - return ui.Wrap{GapX: ui.Space(2), Justify: ui.JustifyEnd}.Layout(gtx, - ui.WrapItem(th.SkeletonShape(sessionB.Layout).Layout), - ui.WrapItem(th.SkeletonShape(mergeB.Layout).Layout), - ui.WrapItem(th.SkeletonShape(moreB.Layout).Layout), - ) - } - heading := func(gtx C) D { - return layout.Inset{Right: ui.Space(4), Top: pullsHeadingTop}.Layout(gtx, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - // The spacer is the title's pencil, which sets the line when taller. - return layout.Flex{}.Layout(gtx, - layout.Rigid(th.SkeletonText(pullsTitleSize, ui.Space(120)).Layout), - ui.Gap(1), - layout.Rigid(layout.Spacer{Width: ui.Space(6), Height: ui.Space(6)}.Layout), - ) - }), - ui.VGap(3), - layout.Rigid(func(gtx C) D { - return layout.Flex{}.Layout(gtx, - layout.Rigid(th.SkeletonText(ui.TextXS, ui.Space(14)).Layout), - ui.Gap(4), - layout.Rigid(th.SkeletonText(ui.TextXS, ui.Space(48)).Layout), - ui.Gap(4), - layout.Rigid(th.SkeletonText(ui.TextXS, ui.Space(24)).Layout), - ) - }), - ) - }) - } - return layout.Flex{}.Layout(gtx, layout.Flexed(1, ui.Spanning(heading)), layout.Rigid(actions)) + sessionB := th.Button(&session, i18n.T("pulls.pulls.openInSession")) + sessionB.Icon, sessionB.Size = icPullSession, ui.SizeSM + mergeB := th.Button(&merge, i18n.T("pulls.pullRequestView.merge")) + mergeB.Icon, mergeB.Size = icPullMerged, ui.SizeSM + moreB := th.Button(&more, "") + moreB.Icon, moreB.Size = icPullMore, ui.SizeIconSM + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Flexed(1, ui.Spanning(th.SkeletonText(ui.TextSM, ui.Space(64)).Layout)), + ui.Gap(4), + layout.Rigid(th.SkeletonShape(sessionB.Layout).Layout), + ui.Gap(2), + layout.Rigid(th.SkeletonShape(mergeB.Layout).Layout), + ui.Gap(2), + layout.Rigid(th.SkeletonShape(moreB.Layout).Layout), + ) } // skeletonTabOrder is every tab a pull request can show, as tabsOf lists them. var skeletonTabOrder = []pullsTab{tabOverview, tabConversation, tabCommits, tabFiles, tabChecks} -// skeletonTabs is tabStrip with every tab's label, a bar where a count -// lands, the open tab marked, and a bar where the diff's size lands. +// skeletonTabs is tabStrip with every tab's label, known before the pull +// request is, and no counts. func (v *pullView) skeletonTabs(gtx C, th *ui.Theme) D { var triggers []ui.TabsTrigger for _, t := range skeletonTabOrder { - trigger := ui.TabsTrigger{Text: t.label()} - if t != tabOverview { - trigger.Trailing = th.SkeletonText(ui.TextSM, ui.Space(2.5)).Layout - } - triggers = append(triggers, trigger) + triggers = append(triggers, ui.TabsTrigger{Text: t.label()}) } tabs := th.Tabs(&v.tabs, triggers...) - tabs.Variant = ui.TabsVariantLine - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { - d := tabs.Layout(gtx) - d.Size.X = gtx.Constraints.Max.X - return d - }), - layout.Rigid(func(gtx C) D { - return layout.Inset{Left: ui.Space(4)}.Layout(gtx, th.SkeletonText(ui.TextXS, ui.Space(16)).Layout) - }), - ) + tabs.Variant = ui.TabsVariantGhost + return tabs.Layout(gtx) } -// skeletonOverview is overview: the description's fixed heading over its -// prose filling the column, beside the facts, stacked the same way on an -// island too narrow for both. +// skeletonOverview is overview: the description's prose filling its column +// beside the facts, stacked the same way on an island too narrow for both. func skeletonOverview(gtx C, th *ui.Theme) D { - var more ui.Clickable - heading := func(gtx C) D { - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(4)}.Layout(gtx, func(gtx C) D { - moreB := th.Button(&more, "") - moreB.Icon, moreB.Size = icPullMore, ui.SizeIconXS - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, ui.Spanning(th.SkeletonText(ui.TextXS, ui.Space(24)).Layout)), - layout.Rigid(th.SkeletonShape(moreB.Layout).Layout), - ) - }) - } prose := func(gtx C) D { size := gtx.Constraints.Max - gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(overviewProseWidth+2*pullsPadX)) - layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(3)}.Layout(gtx, func(gtx C) D { return skeletonProse(gtx, th) }) + proseColumn(gtx, func(gtx C) D { return skeletonProse(gtx, th) }) return D{Size: size} } + facts := func(gtx C) D { return skeletonFacts(gtx, th) } if gtx.Constraints.Max.X < gtx.Dp(overviewSplitWidth) { return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(5)}.Layout(gtx, func(gtx C) D { return skeletonFacts(gtx, th) }) + return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(3)}.Layout(gtx, facts) }), - layout.Rigid(heading), layout.Flexed(1, prose), ) } return layout.Flex{}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return layout.Inset{Top: ui.Space(1), Bottom: overviewHeadingBottom}.Layout(gtx, heading) - }), - layout.Flexed(1, prose), - ) - }), - layout.Rigid(func(gtx C) D { return th.VerticalRule(gtx) }), + layout.Flexed(1, func(gtx C) D { return layout.Inset{Top: ui.Space(1)}.Layout(gtx, prose) }), + ui.Gap(4), layout.Rigid(func(gtx C) D { - w := gtx.Dp(overviewFactsWidth) - gtx.Constraints.Min.X, gtx.Constraints.Max.X = w, w - return layout.Inset{Left: ui.Space(5), Right: ui.Space(5), Top: ui.Space(5)}.Layout(gtx, func(gtx C) D { return skeletonFacts(gtx, th) }) + return layout.Inset{Top: overviewTop, Right: pullsRowEdge}.Layout(gtx, func(gtx C) D { + gtx.Constraints.Min.X, gtx.Constraints.Max.X = gtx.Dp(overviewFactsWidth), gtx.Dp(overviewFactsWidth) + return facts(gtx) + }) }), ) } @@ -183,18 +99,11 @@ func skeletonProse(gtx C, th *ui.Theme) D { return layout.Flex{Axis: layout.Vertical}.Layout(gtx, children...) } -// skeletonFacts is facts' sections, a heading over its value each. +// skeletonFacts is facts' first lines. func skeletonFacts(gtx C, th *ui.Theme) D { var children []layout.FlexChild - for i, w := range []unit.Dp{ui.Space(32), ui.Space(40), ui.Space(28)} { - if i > 0 { - children = append(children, ui.VGap(5)) - } - children = append(children, - layout.Rigid(th.SkeletonBar(ui.Space(18), skeletonXSLine, ui.Space(3)).Layout), - ui.VGap(2), - layout.Rigid(th.SkeletonBar(w, skeletonSMLine, ui.Space(3.5)).Layout), - ) + for _, w := range []unit.Dp{ui.Space(35), ui.Space(27), ui.Space(40)} { + children = append(children, layout.Rigid(th.SkeletonBar(w, factHeight, ui.Space(3)).Layout)) } return layout.Flex{Axis: layout.Vertical}.Layout(gtx, children...) } @@ -209,11 +118,11 @@ func (v *pullView) skeletonTab(gtx C, th *ui.Theme) D { case tabConversation: return skeletonConversation(gtx, th) case tabCommits: - return skeletonCommits(gtx, th) + return skeletonList(gtx, th) case tabFiles: return v.skeletonFiles(gtx, th) case tabChecks: - return skeletonChecks(gtx, th) + return skeletonList(gtx, th) } return skeletonOverview(gtx, th) } diff --git a/native/cmd/lich-native/pulls_skeleton_tabs.go b/native/cmd/lich-native/pulls_skeleton_tabs.go index 2691b0a60..5afec26f1 100644 --- a/native/cmd/lich-native/pulls_skeleton_tabs.go +++ b/native/cmd/lich-native/pulls_skeleton_tabs.go @@ -11,62 +11,17 @@ import ( "github.com/lichdotdev/lich/native/ui/markdown" ) -// skeletonWidths are ragged fractions a list's bars take, so it reads as -// rows of different text. -var skeletonWidths = []float32{0.62, 0.48, 0.7, 0.55, 0.4, 0.66, 0.5} - -func skeletonWidth(i int) float32 { return skeletonWidths[i%len(skeletonWidths)] } - -// The tab skeletons' rows: bounded for an unbounded height, the panel's -// form inset as panelList is, each row padded as panelRow is. +// The tab skeletons' rows: bounded for an unbounded height, the panel's form +// inset as panelList is. var ( skeletonRows = ui.SkeletonFill{MaxRows: listSkeletonMaxRows} skeletonPanelRows = ui.SkeletonFill{MaxRows: listSkeletonMaxRows, PadY: ui.Space(1)} - skeletonRowBox = ui.SkeletonRow{PadX: pullsRowEdge + pullsRowPadX, PadY: ui.Space(2)} ) -// skeletonTwoLines is a text-sm line over a text-xs one, w of the room. -func skeletonTwoLines(th *ui.Theme, w float32) layout.Widget { - return func(gtx C) D { - full := gtx.Metric.PxToDp(gtx.Constraints.Max.X) - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(th.SkeletonText(ui.TextSM, full*unit.Dp(w)).Layout), - layout.Rigid(th.SkeletonText(ui.TextXS, full*unit.Dp(w)*0.6).Layout), - ) - } -} - -// skeletonCommits is commitRows filling the panel. -func skeletonCommits(gtx C, th *ui.Theme) D { - return skeletonPanelRows.Layout(gtx, func(gtx C, i int) D { return skeletonCommitRow(gtx, th, i) }) -} - -// skeletonCommitRow is commitRow: a headline over who and when, the short -// oid at the right. -func skeletonCommitRow(gtx C, th *ui.Theme, i int) D { - return skeletonRowBox.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, ui.Spanning(skeletonTwoLines(th, skeletonWidth(i)))), - layout.Rigid(th.SkeletonText(ui.TextXS, ui.Space(12.5)).Layout), - ) - }) -} - -// skeletonChecks is checkRows filling the panel. -func skeletonChecks(gtx C, th *ui.Theme) D { - return skeletonPanelRows.Layout(gtx, func(gtx C, i int) D { return skeletonCheckRow(gtx, th, i) }) -} - -// skeletonCheckRow is a check's row: the state glyph, its name over its -// description, the duration at the right. -func skeletonCheckRow(gtx C, th *ui.Theme, i int) D { - return skeletonRowBox.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(th.Skeleton(ui.Space(4), ui.Space(4)).Layout), - ui.Gap(3), - layout.Flexed(1, ui.Spanning(skeletonTwoLines(th, skeletonWidth(i)))), - layout.Rigid(th.SkeletonText(ui.TextXS, ui.Space(8)).Layout), - ) +// skeletonList is the Commits or Checks tab: lines filling the panel. +func skeletonList(gtx C, th *ui.Theme) D { + return skeletonPanelRows.Layout(gtx, func(gtx C, i int) D { + return skeletonLine(gtx, th, skeletonTitles[i%len(skeletonTitles)]) }) } @@ -74,7 +29,7 @@ func skeletonCheckRow(gtx C, th *ui.Theme, i int) D { // byline and a few lines of Markdown. func skeletonConversation(gtx C, th *ui.Theme) D { return skeletonPanelRows.Layout(gtx, func(gtx C, i int) D { - return layout.Inset{Left: pullsPadX, Right: pullsPadX, Top: ui.Space(3), Bottom: ui.Space(1)}.Layout(gtx, func(gtx C) D { + return talkColumn(gtx, func(gtx C) D { return layout.Flex{}.Layout(gtx, layout.Rigid(th.Skeleton(authorAvatarSize, authorAvatarSize).Layout), layout.Rigid(layout.Spacer{Width: authorAvatarGap}.Layout), @@ -82,7 +37,7 @@ func skeletonConversation(gtx C, th *ui.Theme) D { full := gtx.Metric.PxToDp(gtx.Constraints.Max.X) children := []layout.FlexChild{ layout.Rigid(th.SkeletonText(ui.TextSM, ui.Space(40)).Layout), - ui.VGap(1), + ui.VGap(0.5), } for j := range 1 + i%3 { children = append(children, layout.Rigid(skeletonMarkdownLine(th, full*unit.Dp(skeletonProseLines[j])))) @@ -107,7 +62,7 @@ func skeletonMarkdownLine(th *ui.Theme, w unit.Dp) layout.Widget { func (v *pullView) skeletonFiles(gtx C, th *ui.Theme) D { return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { - return layout.Inset{Left: ui.Space(2), Right: ui.Space(2), Top: ui.Space(1.5), Bottom: ui.Space(1.5)}.Layout(gtx, func(gtx C) D { + return layout.Inset{Left: ui.Space(3), Right: ui.Space(3), Bottom: ui.Space(1.5)}.Layout(gtx, func(gtx C) D { return layout.Flex{Alignment: layout.Middle}.Layout(gtx, layout.Rigid(th.Skeleton(ui.Space(6), ui.Space(6)).Layout), ui.Gap(2), @@ -130,12 +85,6 @@ func (v *pullView) skeletonFiles(gtx C, th *ui.Theme) D { gtx.Constraints = layout.Exact(image.Pt(w, gtx.Constraints.Max.Y)) return skeletonTree(gtx, th) }), - layout.Rigid(func(gtx C) D { - if v.tree.hidden { - return D{} - } - return th.VerticalRule(gtx) - }), layout.Flexed(1, func(gtx C) D { return skeletonCards(gtx, th) }), ) }), @@ -163,8 +112,8 @@ func skeletonTree(gtx C, th *ui.Theme) D { // skeletonDiffLines is how many lines of diff each skeleton card shows. const skeletonDiffLines = 6 -// skeletonCards is cardItem after cardItem: a separator between cards, each -// a header on Sidebar over its lines of diff. +// skeletonCards is cardItem after cardItem, each a header over its lines of +// diff. func skeletonCards(gtx C, th *ui.Theme) D { return skeletonRows.Layout(gtx, func(gtx C, i int) D { inset := layout.Inset{Left: ui.Space(2), Right: ui.Space(2), Top: ui.Space(2.5)} @@ -189,21 +138,15 @@ func skeletonCards(gtx C, th *ui.Theme) D { }) } -// skeletonCardHeader is fileCard.header: the file's name and its +/- in a -// Sidebar strip as tall as the header's icon buttons make it. +// skeletonCardHeader is fileCard.header: the file's name and its +/- in a line +// as tall as the header's icon buttons make it. func skeletonCardHeader(gtx C, th *ui.Theme, i int) D { - on := th.On(th.Sidebar) gtx.Constraints.Min.X = gtx.Constraints.Max.X - return layout.Background{}.Layout(gtx, - func(gtx C) D { return ui.Fill(gtx, th.Sidebar, 0) }, - func(gtx C) D { - return layout.Inset{Left: ui.Space(2), Right: ui.Space(2), Top: ui.Space(1), Bottom: ui.Space(1)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(layout.Spacer{Height: ui.Space(6)}.Layout), - layout.Flexed(1, ui.Spanning(on.SkeletonText(ui.TextXS, ui.Space(40+8*float32(i%3))).Layout)), - layout.Rigid(on.SkeletonText(ui.TextXS, ui.Space(10)).Layout), - ) - }) - }, - ) + return layout.Inset{Left: ui.Space(2), Right: ui.Space(2), Top: ui.Space(1), Bottom: ui.Space(1)}.Layout(gtx, func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(layout.Spacer{Height: ui.Space(6)}.Layout), + layout.Flexed(1, ui.Spanning(th.SkeletonText(ui.TextXS, ui.Space(40+8*float32(i%3))).Layout)), + layout.Rigid(th.SkeletonText(ui.TextXS, ui.Space(10)).Layout), + ) + }) } diff --git a/native/cmd/lich-native/pulls_skeleton_tabs_test.go b/native/cmd/lich-native/pulls_skeleton_tabs_test.go index 78c131e00..871d8caf6 100644 --- a/native/cmd/lich-native/pulls_skeleton_tabs_test.go +++ b/native/cmd/lich-native/pulls_skeleton_tabs_test.go @@ -19,14 +19,14 @@ func TestTabSkeletonRowsAreLoadedRowsHeight(t *testing.T) { th := rowMetaTheme(t) gtx := layout.Context{Ops: new(op.Ops), Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Constraints{Max: image.Pt(1200, 800)}} commit := backend.PRCommit{OID: "0123456789abcdef", Headline: "fix: a thing", Name: "ana", Date: rowMetaNow.Format("2006-01-02T15:04:05Z")} - if loaded, got := commitRow(gtx, th, commit, new(ui.Clickable), false, false, rowMetaNow, nil).Size.Y, skeletonCommitRow(gtx, th, 0).Size.Y; got != loaded { + if loaded, got := commitRow(gtx, th, commit, new(ui.Clickable), false, false, rowMetaNow, nil).Size.Y, skeletonLine(gtx, th, 0.5).Size.Y; got != loaded { t.Errorf("commit skeleton row is %dpx tall, a loaded one %dpx", got, loaded) } d := backend.PRDetail{CheckRuns: []api.CheckItem{{Name: "test", Description: "Go tests", State: "passed"}}} var v pullView v.checkClicks = map[string]*ui.Clickable{} - var act pullsAction - if loaded, got := v.checkRows(gtx, th, d, &act)[0](gtx).Size.Y, skeletonCheckRow(gtx, th, 0).Size.Y; got != loaded { + // The first row is its group's heading. + if loaded, got := v.checkRows(gtx, th, d, false)[1](gtx).Size.Y, skeletonLine(gtx, th, 0.5).Size.Y; got != loaded { t.Errorf("check skeleton row is %dpx tall, a loaded one %dpx", got, loaded) } } diff --git a/native/cmd/lich-native/pulls_store.go b/native/cmd/lich-native/pulls_store.go index 0a35e3b4f..79263000a 100644 --- a/native/cmd/lich-native/pulls_store.go +++ b/native/cmd/lich-native/pulls_store.go @@ -3,7 +3,6 @@ package main import ( "context" "fmt" - "slices" "sync" "time" @@ -53,6 +52,7 @@ type pullsStore struct { // avatars is by address, and never stale: GitHub's address changes with // the picture. avatars map[string]*pullsRead[*ui.AvatarImage] + logs map[string]*pullsRead[backend.JobLog] // by the job's address } func newPullsStore(ctx context.Context, c *backend.Client, forges *forgeStore, invalidate func()) *pullsStore { @@ -68,6 +68,7 @@ func newPullsStore(ctx context.Context, c *backend.Client, forges *forgeStore, i talks: map[string]*pullsRead[*backend.PRConversation]{}, accounts: map[string]*pullsRead[backend.GitHubAccountState]{}, avatars: map[string]*pullsRead[*ui.AvatarImage]{}, + logs: map[string]*pullsRead[backend.JobLog]{}, } } @@ -123,29 +124,20 @@ func (s *pullsStore) stale() { staleAll(s.diffs) staleAll(s.talks) staleAll(s.accounts) + // A finished job's log never changes: only one that failed is read again. + for _, log := range s.logs { + log.stale = log.stale || log.err != "" + } s.mu.Unlock() s.invalidate() } func (s *pullsStore) list(path string, state pullsState) pullsRead[[]backend.PRSummary] { - if state == pullsApproved { - return approvedOnly(s.list(path, pullsOpen)) - } return read(s, s.lists, path+"\x00"+string(state), func() ([]backend.PRSummary, error) { return s.client.For(path).ListPullRequests(s.ctx, path, string(state)) }) } -// approvedOnly narrows the open read, since gh's --state has no word for it. -// shortcut: sees only the 50 most recently updated open pull requests, ask gh -// with --search review:approved if a repository outgrows that. -func approvedOnly(open pullsRead[[]backend.PRSummary]) pullsRead[[]backend.PRSummary] { - open.val = slices.DeleteFunc(slices.Clone(open.val), func(pr backend.PRSummary) bool { - return pr.ReviewDecision != "APPROVED" - }) - return open -} - // detail reads pull request number, again every pendingRecheck while it is // still settling (stillSettling). func (s *pullsStore) detail(path string, number int) pullsRead[*backend.PRDetail] { @@ -203,6 +195,12 @@ func (s *pullsStore) commitRange(path, first, last string) pullsRead[backend.Com }) } +func (s *pullsStore) jobLog(path, url string) pullsRead[backend.JobLog] { + return read(s, s.logs, url, func() (backend.JobLog, error) { + return s.client.For(path).JobLog(s.ctx, path, url) + }) +} + func (s *pullsStore) conversation(path string, number int) pullsRead[*backend.PRConversation] { if s.forges.gitLab(path) { return pullsRead[*backend.PRConversation]{loaded: true} diff --git a/native/cmd/lich-native/pulls_store_test.go b/native/cmd/lich-native/pulls_store_test.go index 3a65c845a..c01f0c3aa 100644 --- a/native/cmd/lich-native/pulls_store_test.go +++ b/native/cmd/lich-native/pulls_store_test.go @@ -4,10 +4,10 @@ import ( "context" "encoding/json" "net/http" - "slices" "testing" "time" + "github.com/lichdotdev/lich/api" "github.com/lichdotdev/lich/native/backend" "github.com/lichdotdev/lich/native/ui" ) @@ -30,21 +30,29 @@ func TestPullsStoreReadsOnceUntilAChangeIsAnnounced(t *testing.T) { waitFor(t, "the read the change owes", func() bool { return stub.calls("project.ListPullRequests") == 2 }) } -func TestPullsStoreApprovedNarrowsTheOpenRead(t *testing.T) { +// A finished job's log never changes, so only one that failed to read is asked +// for again. +func TestPullsStoreReadsAJobsLogOnceUnlessItFailed(t *testing.T) { + broken := true stub := &rpcStub{answer: func(string, []json.RawMessage) (any, int) { - return []backend.PRSummary{{Number: 7, ReviewDecision: "APPROVED"}, {Number: 8, ReviewDecision: "REVIEW_REQUIRED"}, {Number: 9}}, http.StatusOK + if broken { + return failing("HTTP 502") + } + return backend.JobLog{Steps: []api.JobStep{{Name: "Test", Lines: []string{"ok"}}}}, http.StatusOK }} s := newPullsStore(context.Background(), stub.client(t), newForgeStore(stub.client(t), func() {}), func() {}) - s.list("/repo", pullsApproved) - waitFor(t, "the first read", func() bool { return s.list("/repo", pullsApproved).loaded }) - if got := numbers(s.list("/repo", pullsApproved).val); !slices.Equal(got, []int{7}) { - t.Errorf("approved = %v, want [7]", got) - } - if got := numbers(s.list("/repo", pullsOpen).val); !slices.Equal(got, []int{7, 8, 9}) { - t.Errorf("open after approved = %v, want [7 8 9]", got) + log := func() pullsRead[backend.JobLog] { + return s.jobLog("/repo", "https://github.com/o/r/actions/runs/1/job/2") } - if got := stub.calls("project.ListPullRequests"); got != 1 { - t.Errorf("calls = %d, want the one open read", got) + log() + waitFor(t, "the refusal", func() bool { return log().err != "" }) + broken = false + s.stale() + waitFor(t, "the log", func() bool { return len(log().val.Steps) == 1 }) + s.stale() + log() + if got := stub.calls("project.JobLog"); got != 2 { + t.Errorf("calls = %d, want the refused one and the one that read it", got) } } diff --git a/native/cmd/lich-native/pulls_submit.go b/native/cmd/lich-native/pulls_submit.go index aa05a3431..6cc07b3d7 100644 --- a/native/cmd/lich-native/pulls_submit.go +++ b/native/cmd/lich-native/pulls_submit.go @@ -79,7 +79,7 @@ func (v *pullView) reviewButton(gtx C, th *ui.Theme, p *pullsScreen, d backend.P ui.MenuEntry{Label: discard, OnClick: func() { v.pendingOf(url).clear() }}, ) b := th.Button(&s.click, i18n.T("pulls.pullsSubmit.review", i18n.Args{"count": pending})) - b.Icon, b.Variant, b.Size, b.Disabled = icPullTalk, ui.VariantGhost, ui.SizeSM, blocked != "" + b.Icon, b.Variant, b.Size, b.Disabled = icPullTalk, ui.VariantOutline, ui.SizeSM, blocked != "" if b.Disabled { return v.withTip(gtx, th, p, "approve", blocked, b.Layout) } diff --git a/native/cmd/lich-native/pulls_thread.go b/native/cmd/lich-native/pulls_thread.go new file mode 100644 index 000000000..568713d25 --- /dev/null +++ b/native/cmd/lich-native/pulls_thread.go @@ -0,0 +1,313 @@ +package main + +import ( + "fmt" + "image" + "log" + "path" + "strings" + "time" + + "gioui.org/font" + "gioui.org/layout" + "gioui.org/unit" + + "github.com/lichdotdev/lich/native/backend" + "github.com/lichdotdev/lich/native/i18n" + "github.com/lichdotdev/lich/native/ui" + "github.com/lichdotdev/lich/native/ui/codeview" +) + +// threadRow is a thread in the conversation, indent in from its column: the +// line that folds it, then its code and what was said, both where the line's +// text starts. +func (v *pullView) threadRow(th *ui.Theme, p *pullsScreen, d backend.PRDetail, t backend.PRReviewThread, act *pullsAction, now time.Time, indent unit.Dp) layout.Widget { + return func(gtx C) D { + gtx.Constraints.Max.X = min(gtx.Constraints.Max.X, gtx.Dp(overviewProseWidth+2*pullsPadX)) + open := v.threadOpen(gtx, t) + return layout.Inset{Left: indent}.Layout(gtx, func(gtx C) D { + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Rigid(func(gtx C) D { + return pullsLine(gtx, th, v.talk.foldClicks[t.ID], false, func(gtx C, th *ui.Theme) D { + return threadLine(gtx, th, t, open, threadFact(p, t, open), true) + }) + }), + layout.Rigid(func(gtx C) D { + if !open { + return D{} + } + return layout.Inset{Left: pullsTextX, Right: pullsPadX, Top: ui.Space(1), Bottom: ui.Space(3)}.Layout(gtx, func(gtx C) D { + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Rigid(func(gtx C) D { return v.threadCode(gtx, th, p, t) }), + layout.Rigid(func(gtx C) D { return v.threadTalk(gtx, th, p, d, t, act, now) }), + ) + }) + }), + ) + }) + } +} + +// threadOpen takes the fold's click and answers whether the thread is open, a +// resolved one starting folded. The conversation and the diff share it. +func (v *pullView) threadOpen(gtx C, t backend.PRReviewThread) bool { + s := &v.talk + fold := boolOf(s.folds, t.ID) + if _, seen := s.foldClicks[t.ID]; !seen { + fold.Value = !t.IsResolved + } + if clickableOf(s.foldClicks, t.ID).Clicked(gtx) { + fold.Value = !fold.Value + } + return fold.Value +} + +// threadFact is the one thing a thread's line says at its end: what it waits +// for, else that its code has moved, else while folded how much was said. +func threadFact(p *pullsScreen, t backend.PRReviewThread, open bool) string { + sent := p.threadSentLabel(t.ID) + switch { + case sent != "" && !t.IsResolved: + return sent + case t.IsOutdated: + return i18n.T("pulls.pullsConversation.outdated") + case !open && len(t.Comments) > 1: + return i18n.T("pulls.pullsConversation.comments", i18n.Args{"count": len(t.Comments)}) + } + return "" +} + +// threadLine is where a thread is: its file, named where the diff around it +// does not already, and its lines; then the folder, or folded what the thread +// opens with. +func threadLine(gtx C, th *ui.Theme, t backend.PRReviewThread, open bool, fact string, file bool) D { + start := t.StartLine + if start == t.Line { + start = 0 + } + children := []layout.FlexChild{ + layout.Rigid(inNodeColumn(func(gtx C) D { return foldIcon(open).Layout(gtx, ui.Space(3.5), th.MutedForeground) })), + layout.Rigid(layout.Spacer{Width: pullsLineGap}.Layout), + } + if file { + children = append(children, + layout.Rigid(th.FileIcon(t.Path, ui.Space(3.5)).Layout), + ui.Gap(1.5), + layout.Rigid(th.Text(ui.TextSM, path.Base(t.Path)).Weight(font.Medium).Layout), + ui.Gap(1.5), + ) + } + rest := layout.Widget(layout.Spacer{}.Layout) + switch dir := path.Dir(t.Path); { + case !open && len(t.Comments) > 0: + rest = th.Text(ui.TextSM, strings.Join(strings.Fields(t.Comments[0].Body), " ")).Muted().Layout + case open && file && dir != ".": + rest = th.Text(ui.TextXS, dir).Mono().Muted().Layout + } + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, append(children, + layout.Rigid(th.Text(ui.TextXS, lineAnchor(start, t.Line)).Mono().Layout), + ui.Gap(2), + layout.Flexed(1, ui.Spanning(rest)), + ui.Gap(2), + layout.Rigid(th.Text(ui.TextXS, fact).Muted().Layout), + )...) +} + +// threadTalk is what was said in the thread, then Reply, Send to session and +// Resolve, gone while one of its comments is edited. +func (v *pullView) threadTalk(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, t backend.PRReviewThread, act *pullsAction, now time.Time) D { + var rows []layout.FlexChild + editing := false + for _, c := range t.Comments { + target := threadTarget(t, c) + editing = v.talk.isEditing(gtx, target) || editing + if len(rows) > 0 { + rows = append(rows, ui.VGap(3)) + } + rows = append(rows, layout.Rigid(func(gtx C) D { return v.threadComment(gtx, th, p, target, c, act, now) })) + } + if !editing { + rows = append(rows, ui.VGap(2), layout.Rigid(func(gtx C) D { + return layout.Inset{Left: authorAvatarSize + authorAvatarGap}.Layout(gtx, func(gtx C) D { return v.threadActions(gtx, th, p, d, t, act) }) + })) + } + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, rows...) +} + +// lineAnchor names the line a comment sits on, or the lines it spans from a +// positive start. +func lineAnchor(start, line int) string { + if start > 0 { + return i18n.T("pulls.pullsConversation.lines", i18n.Args{"start": start, "end": line}) + } + return i18n.T("pulls.pullsConversation.line", i18n.Args{"line": line}) +} + +// hunkLines is the tail of GitHub's hunk a thread shows: the lines it is +// about. +const hunkLines = 4 + +// threadPatch is the tail of hunk as a patch of file, its lines numbered as +// the hunk numbers them; "" for a hunk with no header. +func threadPatch(file, hunk string) string { + lines := strings.Split(strings.TrimRight(hunk, "\n"), "\n") + head, err := parseHunkHead(lines[0]) + if err != nil || len(lines) == 1 { + return "" + } + lines = lines[1:] + cut := max(0, len(lines)-hunkLines) + from, to := head.oldStart, head.newStart + sides := func(lines []string) (old, new int) { + for _, line := range lines { + switch { + case strings.HasPrefix(line, "+"): + new++ + case strings.HasPrefix(line, "-"): + old++ + case !strings.HasPrefix(line, "\\"): + old, new = old+1, new+1 + } + } + return old, new + } + old, new := sides(lines[:cut]) + from, to = from+old, to+new + old, new = sides(lines[cut:]) + // A side with no lines is numbered by the line before them. + if old == 0 { + from-- + } + if new == 0 { + to-- + } + return fmt.Sprintf("--- a/%s\n+++ b/%s\n@@ -%d,%d +%d,%d @@\n%s\n", file, file, from, old, to, new, strings.Join(lines[cut:], "\n")) +} + +// threadCode is the lines the thread is about, as the Files tab draws them, on +// an island of their own. +func (v *pullView) threadCode(gtx C, th *ui.Theme, p *pullsScreen, t backend.PRReviewThread) D { + if len(t.Comments) == 0 || t.Comments[0].DiffHunk == "" || v.files == nil { + return D{} + } + s := &v.talk + code, ok := s.hunks[t.ID] + if !ok { + code = new(chatEditDiff) + s.hunks[t.ID] = code + } + code.build(threadPatch(t.Path, t.Comments[0].DiffHunk), v.files.family, v.files.size) + if len(code.files) != 1 { + return D{} + } + cell, err := s.cells.height(gtx, v.files.family, v.files.size) + if err != nil { + log.Printf("thread code: %v", err) + return D{} + } + pad, height := gtx.Dp(ui.Space(1)), code.files[0].rows*cell + gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, height+2*pad)) + dims := pullsIsland(gtx, th, th.Sidebar, func(gtx C, th *ui.Theme) D { + return layout.Inset{Top: ui.Space(1), Left: 1, Right: 1}.Layout(gtx, func(gtx C) D { + gtx.Constraints.Min = image.Point{} + return code.files[0].layout(gtx, th, codeview.OnSurface(th, p.files.code), height) + }) + }) + dims.Size.Y += gtx.Dp(ui.Space(3.5)) + return dims +} + +// threadActions is Reply at the start and, at the end, Send to session and +// Resolve; or the box while a reply is written. +func (v *pullView) threadActions(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, t backend.PRReviewThread, act *pullsAction) D { + s := &v.talk + reply, resolve := clickableOf(s.replyClicks, t.ID), clickableOf(s.resolveClick, t.ID) + if reply.Clicked(gtx) { + s.replying[t.ID] = true + gtx.Execute(keyFocus(s.editorOf(t.ID))) + } + if resolve.Clicked(gtx) { + act.resolve = &threadResolve{id: t.ID, resolved: !t.IsResolved} + // Settled, it folds away; taken up again, it stays in view. + boolOf(s.folds, t.ID).Value = t.IsResolved + } + if clickableOf(s.cancelClicks, t.ID).Clicked(gtx) { + s.replying[t.ID] = false + } + if s.replying[t.ID] { + return v.replyBox(gtx, th, t, act) + } + resolveB := th.Button(resolve, i18n.T("pulls.reviewThread.resolve")) + resolveB.Icon = icPullCheck + if t.IsResolved { + resolveB.Icon, resolveB.Text = icExtensionRestart, i18n.T("pulls.reviewThread.reopen") + } + resolveB.Variant, resolveB.Size, resolveB.Disabled = ui.VariantGhost, ui.SizeXS, v.busyNow() == "resolve:"+t.ID + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(func(gtx C) D { + return reply.Layout(gtx, func(gtx C) D { + label := th.Text(ui.TextSM, i18n.T("pulls.reviewThread.reply")).Muted() + if reply.Hovered() { + label = label.In(th.Foreground) + } + return label.Layout(gtx) + }) + }), + layout.Flexed(1, func(gtx C) D { return D{Size: image.Pt(gtx.Constraints.Min.X, 0)} }), + layout.Rigid(func(gtx C) D { return v.toSessionButton(gtx, th, p, d, t, act) }), + ui.Gap(1), + layout.Rigid(resolveB.Layout)) +} + +// toSessionButton is Send to session, Open in Session while the branch's +// checkout has no session; nothing on a thread that cannot go. +func (v *pullView) toSessionButton(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, t backend.PRReviewThread, act *pullsAction) D { + if !canSendThreads(d) || !p.threadSendable(t) { + return D{} + } + click := clickableOf(v.talk.toSession, t.ID) + busy := v.busyNow() == "threads" + if click.Clicked(gtx) && !busy { + act.threads = []backend.PRReviewThread{t} + } + label, tip := i18n.T("pulls.pulls.openInSession"), "" + if id, _ := p.reviewSession(d); id != "" { + label, tip = i18n.T("pulls.threadSend.send"), i18n.T("pulls.threadSend.sendTip", i18n.Args{"name": p.sessionLabel(id)}) + } + b := th.Button(click, label) + b.Icon, b.Variant, b.Size, b.Disabled = icPullSession, ui.VariantGhost, ui.SizeXS, busy + return v.withTip(gtx, th, p, "toSession:"+t.ID, tip, b.Layout) +} + +// sendOpenThreads is Send open threads, beside the hand-off in the header: +// every open thread not yet sent, in one prompt; nil when there is none. +func (v *pullView) sendOpenThreads(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, busy string, act *pullsAction) layout.Widget { + threads := p.sendableThreads(p.store.conversation(p.project.Path, d.Number).val) + if !canSendThreads(d) || len(threads) == 0 { + return nil + } + if v.talk.allToSession.Clicked(gtx) && busy == "" { + act.threads = threads + } + return func(gtx C) D { + b := th.Button(&v.talk.allToSession, i18n.T("pulls.threadSend.sendAll", i18n.Args{"count": len(threads)})) + b.Icon, b.Variant, b.Size, b.Disabled = icPullTalk, ui.VariantOutline, ui.SizeSM, busy != "" + return b.Layout(gtx) + } +} + +func (v *pullView) replyBox(gtx C, th *ui.Theme, t backend.PRReviewThread, act *pullsAction) D { + s := &v.talk + ed := s.editorOf(t.ID) + send := clickableOf(s.sendClicks, t.ID) + body := strings.TrimSpace(ed.Text()) + if (send.Clicked(gtx) || ctrlEnter(gtx, ed)) && body != "" && len(t.Comments) > 0 { + act.reply = &threadReply{commentID: t.Comments[len(t.Comments)-1].ID, body: body, thread: t.ID} + } + box := writeBox{editor: ed, placeholder: i18n.T("pulls.reviewThread.replyPlaceholder"), action: i18n.T("pulls.reviewThread.reply"), + send: send, cancel: clickableOf(s.cancelClicks, t.ID), busy: v.busyNow() == "reply:"+t.ID} + if box.busy { + box.action = i18n.T("pulls.commentBox.sending") + } + return box.layout(gtx, th) +} diff --git a/native/cmd/lich-native/pulls_thread_test.go b/native/cmd/lich-native/pulls_thread_test.go new file mode 100644 index 000000000..3e7012192 --- /dev/null +++ b/native/cmd/lich-native/pulls_thread_test.go @@ -0,0 +1,57 @@ +package main + +import ( + "testing" + + "github.com/lichdotdev/lich/native/backend" +) + +// A thread shows the last lines of GitHub's hunk, numbered as the hunk is. +func TestThreadPatchNumbersTheTailOfItsHunk(t *testing.T) { + cases := []struct{ name, hunk, want string }{ + {"whole when short", "@@ -1,2 +1,2 @@ func x\n ctx\n-old\n+new", "--- a/a.go\n+++ b/a.go\n@@ -1,2 +1,2 @@\n ctx\n-old\n+new\n"}, + {"its tail when long", "@@ -10,4 +20,6 @@\n a\n-b\n+c\n d\n+e\n+f\n g", "--- a/a.go\n+++ b/a.go\n@@ -12,2 +22,4 @@\n d\n+e\n+f\n g\n"}, + {"a side with no lines", "@@ -0,0 +1,2 @@\n+a\n+b", "--- a/a.go\n+++ b/a.go\n@@ -0,0 +1,2 @@\n+a\n+b\n"}, + {"no header", "+a\n+b", ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := threadPatch("a.go", c.hunk) + if got != c.want { + t.Fatalf("patch = %q, want %q", got, c.want) + } + if got == "" { + return + } + if files, err := parsePatchFiles(gitPatch(got)); err != nil || len(files) != 1 { + t.Errorf("the diff view reads %d files of it: %v", len(files), err) + } + }) + } +} + +// GitHub keeps CHANGES_REQUESTED until the reviewer moves, so the threads say +// whose move it is. +func TestReviewerStateFollowsTheThreads(t *testing.T) { + th := testTheme() + asked := backend.PRReviewer{Login: "lia", State: "CHANGES_REQUESTED"} + cases := []struct { + name string + r backend.PRReviewer + open, total int + note string + }{ + {"open threads", asked, 2, 3, "2 of 3 threads open"}, + {"every thread resolved", asked, 0, 3, "all threads resolved"}, + {"no threads", asked, 0, 0, "requested changes"}, + {"not answered yet", backend.PRReviewer{Login: "rui"}, 2, 3, "review requested"}, + {"approved", backend.PRReviewer{Login: "rui", State: "APPROVED"}, 2, 3, "approved"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if _, _, note := reviewerState(th, c.r, c.open, c.total); note != c.note { + t.Errorf("note = %q, want %q", note, c.note) + } + }) + } +} diff --git a/native/cmd/lich-native/pulls_view.go b/native/cmd/lich-native/pulls_view.go index 88ce2a108..1dde409c6 100644 --- a/native/cmd/lich-native/pulls_view.go +++ b/native/cmd/lich-native/pulls_view.go @@ -6,6 +6,7 @@ import ( "image/color" "sync" + "gioui.org/font" "gioui.org/layout" "gioui.org/op" "gioui.org/unit" @@ -25,17 +26,12 @@ import ( var ( pullsRowEdge = ui.Space(2) pullsRowPadX = rowInset - pullsRowPadY = ui.Space(2.5) pullsPadX = pullsRowEdge + pullsRowPadX - pullsTitleSize = unit.Sp(18) pullsToolbarPad = ui.Space(2) - // pullsHeadingTop centers the title's first line on the h-8 buttons - // beside it. - pullsHeadingTop = ui.Space(0.5) ) // pullsTitleMinWidth is the least the title keeps beside the actions; less -// and the actions move to their own line above it. +// and the actions move to their own line under it. var pullsTitleMinWidth = unit.Dp(320) // pullsAction is what the screen asks of the window this frame. @@ -66,31 +62,31 @@ type panelAt struct { tab pullsTab } -// pullView is PullRequestView: the toolbar, the title, the status line, the -// tabs and the open tab's panel. +// pullView is one pull request: its title and actions on one line, the tabs +// on the next, then the open tab's panel. type pullView struct { - session, handoff, moreClick ui.Clickable - moreMenu ui.MenuState - mergeClick ui.Clickable - mergeMenu ui.MenuState - back, indexLink, prev, next, switchClick ui.Clickable - switchMenu ui.MenuState - tips map[string]*ui.Tooltip - tabs ui.TabsState - panel widget.List - panelAt panelAt - checksStat ui.Clickable - reviewStat ui.Clickable - commitOpen map[string]*ui.Bool - commitClicks map[string]*ui.Clickable - checkClicks map[string]*ui.Clickable - conflictsPanel ui.DropdownPanelState - conflictsRows widget.List + session, handoff, moreClick ui.Clickable + moreMenu ui.MenuState + mergeClick ui.Clickable + mergeMenu ui.MenuState + back, prev, next ui.Clickable + tips map[string]*ui.Tooltip + tabs ui.TabsState + panel widget.List + panelAt panelAt + checksFact, branchFact ui.Clickable + reviewerFacts map[string]*ui.Clickable + commitOpen map[string]*ui.Bool + commitClicks map[string]*ui.Clickable + checkClicks map[string]*ui.Clickable + conflictsPanel ui.DropdownPanelState + conflictsRows widget.List // files is the Files tab, the dock's Review cards in pull request mode; // viewed is each PR's ticks, by URL, read from the store once a window. files *reviewPanel viewed map[string]*viewedTicks pick commitPick + log logView // busy is the action in flight ("session", "approve", "merge"), which its // button says it is doing; set off the frame. busyMu sync.Mutex @@ -153,6 +149,7 @@ func (v *pullView) init() { v.commitClicks = map[string]*ui.Clickable{} v.checkClicks = map[string]*ui.Clickable{} v.viewed = map[string]*viewedTicks{} + v.reviewerFacts = map[string]*ui.Clickable{} v.pending = map[string]*pendingReview{} v.talk.init() v.md = markdown.Cache{} @@ -174,12 +171,12 @@ func (v *pullView) layout(gtx C, th *ui.Theme, p *pullsScreen, act *pullsAction) read := p.store.detail(p.project.Path, p.selected) switch { case read.val == nil && read.err != "": - return v.withToolbar(gtx, th, p, nil, func(gtx C) D { return th.Notice(read.err).Layout(gtx) }) + return v.withToolbar(gtx, th, p, nil, nil, func(gtx C) D { return pullsNote(gtx, th, read.err) }) case read.val == nil && !read.loaded, read.val == nil && read.loading: - return v.withToolbar(gtx, th, p, func(gtx C) D { return skeletonHeading(gtx, th) }, v.detailSkeleton(th)) + return v.loadingLayout(gtx, th, p) case read.val == nil: - return v.withToolbar(gtx, th, p, nil, func(gtx C) D { - return th.Notice(i18n.T(forgeKey(v.forge, "pulls.pullsEmptyState.none", "pulls.pullsEmptyState.noneGitLab"))).Layout(gtx) + return v.withToolbar(gtx, th, p, nil, nil, func(gtx C) D { + return pullsNote(gtx, th, i18n.T(forgeKey(v.forge, "pulls.pullsEmptyState.none", "pulls.pullsEmptyState.noneGitLab"))) }) } d := v.edit.shown(*read.val, read, p.store.lastStale()) @@ -195,45 +192,86 @@ func (v *pullView) layout(gtx C, th *ui.Theme, p *pullsScreen, act *pullsAction) v.shotEdit = "" } heading := func(gtx C) D { return v.titleRow(gtx, th, p, d, act) } - return v.withToolbar(gtx, th, p, heading, func(gtx C) D { return v.body(gtx, th, p, d, act) }) -} - -// withToolbar lays the strip over w: the crumb, then heading, the pull -// request's title row or its skeleton, when there is one. -func (v *pullView) withToolbar(gtx C, th *ui.Theme, p *pullsScreen, heading, w layout.Widget) D { + tabs := func(gtx C) D { return v.tabStrip(gtx, th, p, d) } + return v.withToolbar(gtx, th, p, heading, tabs, func(gtx C) D { return v.panelLayout(gtx, th, p, d, act) }) +} + +// loadingLayout is the pull request while it is read. +func (v *pullView) loadingLayout(gtx C, th *ui.Theme, p *pullsScreen) D { + return v.withToolbar(gtx, th, p, func(gtx C) D { return skeletonHeading(gtx, th) }, + func(gtx C) D { return v.skeletonTabs(gtx, th) }, func(gtx C) D { return v.skeletonTab(gtx, th) }) +} + +// withToolbar lays the pull request's head over w: back beside heading, the +// title row or its skeleton, then the tabs beside the place in the index. +// Both are nil when there is nothing to show of the pull request. +func (v *pullView) withToolbar(gtx C, th *ui.Theme, p *pullsScreen, heading, tabs, w layout.Widget) D { + lines := []layout.FlexChild{layout.Rigid(func(gtx C) D { + return layout.Flex{}.Layout(gtx, + layout.Rigid(func(gtx C) D { return v.backButton(gtx, th, p) }), + ui.Gap(0.5), + layout.Flexed(1, func(gtx C) D { + if heading == nil { + return D{} + } + return heading(gtx) + }), + ) + })} + if tabs != nil { + lines = append(lines, ui.VGap(2), layout.Rigid(func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Flexed(1, func(gtx C) D { + full := gtx.Constraints.Max.X + // The tabs share out any width they must fill. + gtx.Constraints.Min.X = 0 + d := tabs(gtx) + d.Size.X = full + return d + }), + layout.Rigid(func(gtx C) D { return v.stepper(gtx, th, p) }), + ) + })) + } return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { return layout.UniformInset(pullsToolbarPad).Layout(gtx, func(gtx C) D { gtx.Constraints.Min.X = gtx.Constraints.Max.X - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { return v.crumb(gtx, th, p) }), - layout.Rigid(func(gtx C) D { - if heading == nil { - return D{} - } - return heading(gtx) - }), - ) + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, lines...) }) }), layout.Flexed(1, w), ) } +func (v *pullView) backButton(gtx C, th *ui.Theme, p *pullsScreen) D { + b := th.Button(&v.back, "") + b.Icon, b.Variant, b.Size = icPullBack, ui.VariantGhost, ui.SizeIconSM + return v.withTip(gtx, th, p, "back", i18n.T(forgeKey(v.forge, "pulls.pullsNav.back", "pulls.pullsNav.backGitLab")), b.Layout) +} + +// titleRow is the title beside the actions, or over them where both do not +// fit. func (v *pullView) titleRow(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, act *pullsAction) D { v.editClicks(gtx, d, act) + heading := func(gtx C) D { + gtx.Constraints.Min = image.Pt(gtx.Constraints.Max.X, gtx.Dp(ui.Space(8))) + return layout.W.Layout(gtx, func(gtx C) D { return v.heading(gtx, th, p, d, act) }) + } actions, size := v.recordActions(gtx, th, p, d, act) if size.Y > gtx.Dp(ui.Space(8)) || gtx.Constraints.Max.X-size.X < gtx.Dp(pullsTitleMinWidth) { return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Rigid(heading), + ui.VGap(1), layout.Rigid(func(gtx C) D { gtx.Constraints.Min.X = gtx.Constraints.Max.X return v.actions(gtx, th, p, d, act) }), - layout.Rigid(func(gtx C) D { return v.heading(gtx, th, p, d, act) }), ) } return layout.Flex{}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { return v.heading(gtx, th, p, d, act) }), + layout.Flexed(1, heading), + ui.Gap(4), layout.Rigid(func(gtx C) D { actions.Add(gtx.Ops) return D{Size: size} @@ -241,10 +279,10 @@ func (v *pullView) titleRow(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDet ) } -// navClicks carries out the crumb's clicks before the frame draws the pull -// request, so the frame that took one already draws where it leads. +// navClicks carries out the head's navigation before the frame draws the pull +// request, so the frame that took a click already draws where it leads. func (v *pullView) navClicks(gtx C, p *pullsScreen, rows []backend.PRSummary) { - if v.back.Clicked(gtx) || v.indexLink.Clicked(gtx) { + if v.back.Clicked(gtx) { p.backToIndex() } if v.prev.Clicked(gtx) { @@ -255,77 +293,14 @@ func (v *pullView) navClicks(gtx C, p *pullsScreen, rows []backend.PRSummary) { } } -// crumb is the line over the title: back to the index, the index's name and -// the pull request's number, which opens the switcher; at the right its place -// in the index between previous and next. -func (v *pullView) crumb(gtx C, th *ui.Theme, p *pullsScreen) D { +// stepper is "N of M" between previous and next, along the index as it is +// filtered; nothing for a pull request the index does not show. +func (v *pullView) stepper(gtx C, th *ui.Theme, p *pullsScreen) D { rows := p.visible(p.store.list(p.project.Path, p.state).val) - at := position(rows, p.selected) - return layout.Inset{Bottom: ui.Space(1)}.Layout(gtx, func(gtx C) D { - gtx.Constraints.Min.X = gtx.Constraints.Max.X - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(func(gtx C) D { - b := th.Button(&v.back, "") - b.Icon, b.Variant, b.Size = icPullBack, ui.VariantGhost, ui.SizeIconSM - return v.withTip(gtx, th, p, "back", i18n.T(forgeKey(v.forge, "pulls.pullsNav.back", "pulls.pullsNav.backGitLab")), b.Layout) - }), - ui.Gap(2.5), - layout.Rigid(func(gtx C) D { - return th.HoverLink(gtx, &v.indexLink, i18n.T(forgeKey(v.forge, "tabs.projectTabs.pullRequests", "tabs.projectTabs.mergeRequests"))) - }), - ui.Gap(1.5), - layout.Rigid(func(gtx C) D { return icPullRight.Layout(gtx, ui.Space(3), th.MutedForeground) }), - ui.Gap(1.5), - layout.Rigid(func(gtx C) D { return v.switcher(gtx, th, p, rows) }), - layout.Flexed(1, func(gtx C) D { return D{Size: image.Pt(gtx.Constraints.Max.X, 0)} }), - layout.Rigid(func(gtx C) D { - if at < 0 { - return D{} - } - return v.stepper(gtx, th, p, at, len(rows)) - }), - ) - }) -} - -// switcher is the pull request's number, a menu of the index's rows to go to -// another one. -func (v *pullView) switcher(gtx C, th *ui.Theme, p *pullsScreen, rows []backend.PRSummary) D { - entries := make([]ui.MenuEntry, len(rows)) - for i, r := range rows { - entries[i] = ui.MenuEntry{Kind: ui.MenuRadioItem, Label: changeRef(v.forge, r.Number) + " " + r.Title, Checked: r.Number == p.selected, - OnClick: func() { p.openPR(r.Number) }} + at, total := position(rows, p.selected), len(rows) + if at < 0 { + return D{} } - face := func(gtx C) D { - return v.switchClick.Layout(gtx, func(gtx C) D { - bg := th.Muted - if v.switchClick.Hovered() { - bg = th.Accent - } - return layout.Background{}.Layout(gtx, - func(gtx C) D { return ui.Fill(gtx, bg, ui.RadiusMD) }, - func(gtx C) D { - on := th.On(bg) - return layout.Inset{Left: ui.Space(2), Right: ui.Space(1.5), Top: ui.Space(0.5), Bottom: ui.Space(0.5)}.Layout(gtx, func(gtx C) D { - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Rigid(on.Text(ui.TextXS, changeRef(v.forge, p.selected)).Mono().Layout), - ui.Gap(1), - layout.Rigid(func(gtx C) D { return icPullDown.Layout(gtx, ui.Space(3), on.MutedForeground) }), - ) - }) - }) - }) - } - if len(entries) == 0 { - return face(gtx) - } - return v.withTip(gtx, th, p, "switch", i18n.T(forgeKey(v.forge, "pulls.pullsNav.switch", "pulls.pullsNav.switchGitLab")), func(gtx C) D { - return th.DropdownMenu(p.root, &v.switchMenu, entries).Layout(gtx, face) - }) -} - -// stepper is "N of M" between previous and next, along the index's filter. -func (v *pullView) stepper(gtx C, th *ui.Theme, p *pullsScreen, at, total int) D { arrow := func(click *ui.Clickable, ic *icons.Icon, key, tip string, disabled bool) layout.Widget { return func(gtx C) D { b := th.Button(click, "") @@ -351,35 +326,43 @@ func (v *pullView) recordActions(gtx C, th *ui.Theme, p *pullsScreen, d backend. return macro.Stop(), size } -// heading is the title over its stats, its left edge on the toolbar strip's. +// heading is the title on one line, the pencil that edits it (none on a +// GitLab merge request), the number and the diff's size; the field while the +// title is edited. func (v *pullView) heading(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, act *pullsAction) D { - return layout.Inset{Right: ui.Space(4), Top: pullsHeadingTop}.Layout(gtx, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { return v.pullTitle(gtx, th, p, d, act) }), - ui.VGap(3), - layout.Rigid(func(gtx C) D { return v.stats(gtx, th, p, d) }), + if v.edit.editing(d) { + return v.titleField(gtx, th, d, act) + } + title := th.Text(ui.TextSM, d.Title).Weight(font.Medium) + want, pencil := naturalWidth(gtx, title.Layout), 0 + if v.forge != api.ForgeGitLab { + pencil = gtx.Dp(ui.Space(7)) + } + face := func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(func(gtx C) D { + gtx.Constraints.Max.X = max(gtx.Constraints.Max.X-pencil, 0) + whole := "" + if want > gtx.Constraints.Max.X { + whole = d.Title + } + return v.withTip(gtx, th, p, "title", whole, title.Layout) + }), + layout.Rigid(func(gtx C) D { + if pencil == 0 { + return D{} + } + return layout.Inset{Left: ui.Space(1)}.Layout(gtx, func(gtx C) D { + return th.IconAction(p.root, &v.edit.open, icPullEdit, i18n.T("pulls.pullRequestView.edit"), false).Layout(gtx) + }) + }), ) - }) -} - -func (v *pullView) body(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail, act *pullsAction) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return layout.Inset{Left: pullsToolbarPad, Right: pullsToolbarPad}.Layout(gtx, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - ui.VGap(4), - layout.Rigid(func(gtx C) D { return v.tabStrip(gtx, th, p, d) }), - ) - }) - }), - layout.Flexed(1, func(gtx C) D { return v.panelLayout(gtx, th, p, d, act) }), - ) -} - -// pullStat is PullsStats' Stat: a size-3.5 glyph and its words in one tone. -func pullStat(gtx C, th *ui.Theme, ic *icons.Icon, text string, fg color.NRGBA) D { - glyph := func(gtx C) D { return pullGlyph(gtx, th, ic, ui.Space(3.5), fg) } - return th.Stat(gtx, glyph, text, fg) + } + facts := []layout.Widget{th.Text(ui.TextXS, changeRef(v.forge, d.Number)).Mono().Muted().Layout} + if d.Additions != 0 || d.Deletions != 0 { + facts = append(facts, th.DiffStat(d.Additions, d.Deletions).Layout) + } + return lineText(gtx, want+pencil, face, facts...) } // pullState is a state the glyph says alone: ic in fg, word its name for @@ -396,85 +379,12 @@ func pullGlyph(gtx C, th *ui.Theme, ic *icons.Icon, size unit.Dp, fg color.NRGBA return ic.Layout(gtx, size, fg) } -// stats is the status line: state, branches and who opened it, then the -// checks, mergeability and review, which Overview's facts carry instead. -func (v *pullView) stats(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail) D { - items := []ui.WrapChild{ - ui.WrapItem(func(gtx C) D { return stateStat(gtx, th, d) }), - ui.WrapItem(func(gtx C) D { - return th.MetaGlyph(icPullBranch, d.HeadRefName+" → "+d.BaseRefName, th.MutedForeground).Layout(gtx) - }), - ui.WrapItem(th.Text(ui.TextXS, i18n.T("pulls.pullsOverview.openedBy", i18n.Args{"author": d.Author})).Muted().Layout), - } - if v.openTab(d) != tabOverview { - vs := v.verdicts(gtx, th, p, d) - for _, w := range []layout.Widget{vs.checks, vs.merge, vs.review} { - if w != nil { - items = append(items, ui.WrapItem(w)) - } - } - } - return ui.Wrap{GapX: ui.Space(4), GapY: ui.Space(1.5)}.Layout(gtx, items...) -} - -// prVerdicts is what the pull request's checks, mergeability and review say, -// each nil when it says nothing. -type prVerdicts struct { - checks, merge, review layout.Widget -} - -// verdicts is the pull request's prVerdicts: the checks and the review open -// their tab, a conflict lists its files. -func (v *pullView) verdicts(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDetail) prVerdicts { - if v.checksStat.Clicked(gtx) { - v.showTab(d, tabChecks) - } - if v.reviewStat.Clicked(gtx) { - v.showTab(d, tabConversation) - } - var out prVerdicts - if ic, text, fg, ok := checksStat(th, d.Checks); ok { - out.checks = func(gtx C) D { - return v.checksStat.Layout(gtx, func(gtx C) D { return pullStat(gtx, th, ic, text, fg) }) - } - } - if ic, text, fg, ok := mergeableStat(th, d); ok { - out.merge = func(gtx C) D { - face := func(gtx C) D { return pullStat(gtx, th, ic, text, fg) } - if conflictsWithBase(d) && v.forge != api.ForgeGitLab { - return v.conflictsStat(gtx, th, p, d, face) - } - return face(gtx) - } - } - open, total := threadTally(p.store.conversation(p.project.Path, d.Number).val) - if ic, text, fg, ok := reviewStat(th, d.ReviewDecision, open, total); ok { - out.review = func(gtx C) D { - return v.reviewStat.Layout(gtx, func(gtx C) D { return pullStat(gtx, th, ic, text, fg) }) - } - } - return out -} - -func stateStat(gtx C, th *ui.Theme, d backend.PRDetail) D { - switch { - case d.State == "MERGED": - return pullState(gtx, th, icPullMerged, i18n.T("pulls.pullsStats.merged"), th.MutedForeground) - case d.State == "CLOSED": - return pullState(gtx, th, icPullX, i18n.T("pulls.pullsStats.closed"), th.MutedForeground) - case d.IsDraft: - // muted as in the list: amber is a verdict waiting on its reviewer - return pullState(gtx, th, icPullDashed, i18n.T("pulls.pullsStats.draft"), th.MutedForeground) - } - return pullState(gtx, th, icPullRequests, i18n.T("pulls.pullsStats.open"), th.TonePass) -} - func checksStat(th *ui.Theme, c backend.ChecksRollup) (*icons.Icon, string, color.NRGBA, bool) { switch verdictOf(c) { case verdictFailed: return icPullX, i18n.T("pulls.pullsStats.checksFailing", i18n.Args{"failed": c.Failed, "total": c.Total}), th.Destructive, true case verdictPending: - return icPullRunning, i18n.T("pulls.pullsStats.checksRunning", i18n.Args{"pending": c.Pending, "total": c.Total}), th.ToneWait, true + return icPullRunning, i18n.T("pulls.pullsStats.checksRunning", i18n.Args{"done": c.Total - c.Pending, "total": c.Total}), th.ToneWait, true case verdictPassed: return icPullCheck, i18n.T("pulls.pullsStats.checksPassed", i18n.Args{"count": c.Passed}), th.TonePass, true } @@ -494,26 +404,6 @@ func mergeableStat(th *ui.Theme, d backend.PRDetail) (*icons.Icon, string, color return icPullDashed, i18n.T("pulls.pullsStats.checkingMergeability"), th.MutedForeground, true } -// reviewStat is ReviewStat: the verdict, and on changes requested how the -// threads stand, GitHub keeping the verdict until the reviewer moves. -func reviewStat(th *ui.Theme, decision string, open, total int) (*icons.Icon, string, color.NRGBA, bool) { - switch { - case decision == "CHANGES_REQUESTED" && total > 0 && open > 0: - return icPullX, i18n.T("pulls.pullsStats.threadsUnresolved", i18n.Args{"open": open, "total": total}), th.Destructive, true - case decision == "CHANGES_REQUESTED" && total > 0: - return icPullCheck2, i18n.T("pulls.pullsStats.threadsResolved"), th.ToneWait, true - } - switch decision { - case "APPROVED": - return icPullCheck, i18n.T("pulls.pullsStats.approved"), th.TonePass, true - case "CHANGES_REQUESTED": - return icPullX, i18n.T("pulls.pullsStats.changesRequested"), th.Destructive, true - case "REVIEW_REQUIRED": - return icPullDashed, i18n.T("pulls.pullsStats.reviewRequired"), th.MutedForeground, true - } - return nil, "", color.NRGBA{}, false -} - // tabsOf is the tabs a pull request shows, in order: Checks only when it has // any, Conversation not on a GitLab merge request, whose threads lich does not // read yet. @@ -568,7 +458,7 @@ func (v *pullView) tabStrip(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDet for _, t := range tabsOf(d, v.forge) { trigger := ui.TabsTrigger{Text: t.label()} if n := counts[t]; n > 0 { - trigger.Trailing = th.Text(ui.TextSM, fmt.Sprint(n)).Muted().Layout + trigger.Trailing = th.Text(ui.TextXS, fmt.Sprint(n)).Muted().Layout } triggers = append(triggers, trigger) } @@ -576,18 +466,6 @@ func (v *pullView) tabStrip(gtx C, th *ui.Theme, p *pullsScreen, d backend.PRDet v.tabs.Selected = 0 } tabs := th.Tabs(&v.tabs, triggers...) - tabs.Variant = ui.TabsVariantLine - return layout.Flex{Alignment: layout.Middle}.Layout(gtx, - layout.Flexed(1, func(gtx C) D { - d := tabs.Layout(gtx) - d.Size.X = gtx.Constraints.Max.X - return d - }), - layout.Rigid(func(gtx C) D { - if d.Additions == 0 && d.Deletions == 0 { - return D{} - } - return layout.Inset{Left: ui.Space(4)}.Layout(gtx, func(gtx C) D { return th.DiffStat(d.Additions, d.Deletions).Layout(gtx) }) - }), - ) + tabs.Variant = ui.TabsVariantGhost + return tabs.Layout(gtx) } diff --git a/native/cmd/lich-native/pulls_write.go b/native/cmd/lich-native/pulls_write.go new file mode 100644 index 000000000..4a5506be0 --- /dev/null +++ b/native/cmd/lich-native/pulls_write.go @@ -0,0 +1,67 @@ +package main + +import ( + "cmp" + "strings" + + "gioui.org/layout" + "gioui.org/unit" + "gioui.org/widget" + + "github.com/lichdotdev/lich/native/i18n" + "github.com/lichdotdev/lich/native/ui" +) + +var ( + writeBoxPadX = ui.Space(3.5) + writeBoxPadY = ui.Space(3) + // writeBoxMax is how tall the text grows before it scrolls. + writeBoxMax = unit.Dp(320) +) + +// writeBox is where anything is written on a pull request: the text on a +// filled box with no field in it, growing as it is written, then Cancel and +// the action with Ctrl+Enter inside. The caller carries the clicks out. +type writeBox struct { + editor *widget.Editor + placeholder string + note string // muted, beside the buttons + action string + send, cancel *ui.Clickable + busy bool + keys string // the action's key, Ctrl+Enter when "" + // resting is the box before it is written in: one line and no buttons. + resting bool +} + +func (b writeBox) layout(gtx C, th *ui.Theme) D { + gtx.Constraints.Min.X = gtx.Constraints.Max.X + on := th.On(th.Sidebar) + ta := on.Textarea(b.editor, b.placeholder) + ta.Bare, ta.Disabled = true, b.busy + ta.PadX, ta.PadY, ta.MaxHeight = writeBoxPadX, writeBoxPadY, writeBoxMax + children := []layout.FlexChild{layout.Rigid(ta.Layout)} + if !b.resting { + children = append(children, layout.Rigid(func(gtx C) D { return b.buttons(gtx, on) })) + } + return layout.Background{}.Layout(gtx, + func(gtx C) D { return ui.Fill(gtx, on.Surface, ui.RadiusLG) }, + func(gtx C) D { return layout.Flex{Axis: layout.Vertical}.Layout(gtx, children...) }, + ) +} + +func (b writeBox) buttons(gtx C, th *ui.Theme) D { + cancel := th.Button(b.cancel, i18n.T("common.action.cancel")) + cancel.Variant, cancel.Size = ui.VariantGhost, ui.SizeXS + send := th.Button(b.send, b.action) + send.Size, send.Keys = ui.SizeXS, cmp.Or(b.keys, ctrlEnterCap()) + send.Disabled = b.busy || strings.TrimSpace(b.editor.Text()) == "" + return layout.Inset{Left: writeBoxPadX, Right: writeBoxPadX, Bottom: writeBoxPadY}.Layout(gtx, func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Flexed(1, ui.Spanning(th.Text(ui.TextXS, b.note).Muted().Layout)), + layout.Rigid(cancel.Layout), + ui.Gap(1), + layout.Rigid(send.Layout), + ) + }) +} diff --git a/native/cmd/lich-native/stale_pulls_test.go b/native/cmd/lich-native/stale_pulls_test.go index bbec5bdd4..7d27b3d68 100644 --- a/native/cmd/lich-native/stale_pulls_test.go +++ b/native/cmd/lich-native/stale_pulls_test.go @@ -5,10 +5,10 @@ import ( "github.com/lichdotdev/lich/api" "image" "net/http" - "strings" "sync" "testing" + "gioui.org/f32" "gioui.org/io/key" "github.com/lichdotdev/lich/native/backend" @@ -85,7 +85,7 @@ func pullsDetailShown(t *testing.T) (*window, *frameRig) { u, r := pullsFrames(t) r.waitFor(t, "Fix the thing") r.clickLabel(t, "Fix the thing") - r.waitFor(t, i18n.T("pulls.pullsOverview.openedBy", i18n.Args{"author": ""})) + r.waitFor(t, "fix → main") return u, r } @@ -107,15 +107,6 @@ func TestPullsMergeCancelClosesInTheFrameAfterTheClick(t *testing.T) { } } -func TestPullsFilterTabsFilterInTheFrameThatTookTheClick(t *testing.T) { - u, r := pullsFrames(t) - r.waitFor(t, "Fix the thing") - r.clickLabel(t, pullsFilter(2).label()) - if u.pulls.filter.Selected != 2 { - t.Fatal("the click missed Drafts") - } -} - // openPullsTab opens the detail's tab named label and waits for want. func openPullsTab(t *testing.T, r *frameRig, label, want string) { t.Helper() @@ -271,14 +262,6 @@ func TestPullsEditEnterGoesToTheDescriptionAndEscapeStays(t *testing.T) { } } -func TestPullsDescriptionMenuSitsAtTheColumnsEdge(t *testing.T) { - _, r := pullsDetailShown(t) - more := r.controlOf(t, strings.ToUpper(i18n.T("pulls.pullsOverview.description"))) - if prose := float32(overviewProseWidth + 2*pullsPadX); more.X <= prose { - t.Errorf("⋯ at x=%v sits inside the %vdp prose width, not at the column's edge", more.X, prose) - } -} - // The skeleton's title row and tab strip take the loaded ones' height, so // the tabs do not move down when the pull request arrives. func TestPullsDetailSkeletonKeepsTheTabsWhereTheyLand(t *testing.T) { @@ -298,7 +281,7 @@ func TestPullsDetailSkeletonKeepsTheTabsWhereTheyLand(t *testing.T) { } skeleton := r.at(t, overview) release() - r.waitFor(t, i18n.T("pulls.pullsOverview.openedBy", i18n.Args{"author": ""})) + r.waitFor(t, "fix → main") // Only the height: the tabs' widths follow counts the skeleton cannot know. if loaded := r.at(t, overview); loaded.Y != skeleton.Y { t.Errorf("the Overview tab sits at y=%v in the skeleton and y=%v loaded", skeleton.Y, loaded.Y) @@ -322,14 +305,14 @@ func TestPullsViewedTickCountsInTheFrameThatTookTheClick(t *testing.T) { } } -// The index opens on the screen, a row opens its pull request, and the -// crumb's back button returns to the index with the cursor on that row. +// The index opens on the screen, a row opens its pull request, and the head's +// back button returns to the index with the cursor on that row. func TestPullsBackReturnsToTheIndexOnTheRowItLeft(t *testing.T) { u, r := pullsDetailShown(t) if u.pulls.selected != 7 { t.Fatalf("the click on the row opened #%d", u.pulls.selected) } - r.clickLabel(t, i18n.T("tabs.projectTabs.pullRequests")) + r.click(t, f32.Pt(24, 24)) // an icon alone, at the island's corner if u.pulls.selected != 0 || u.pulls.cursor != 7 { t.Fatalf("back left #%d open, cursor on #%d", u.pulls.selected, u.pulls.cursor) } @@ -353,7 +336,7 @@ func TestPullsKeysWalkTheIndexAndEscapeGoesBack(t *testing.T) { t.Fatalf("j left the cursor on #%d, keyed %v", u.pulls.cursor, u.pulls.keyed) } r.router.Queue(key.Event{Name: key.NameReturn, State: key.Press}) - r.waitFor(t, i18n.T("pulls.pullsOverview.openedBy", i18n.Args{"author": ""})) + r.waitFor(t, "fix → main") if u.pulls.selected != 8 { t.Fatalf("Enter opened #%d", u.pulls.selected) } diff --git a/native/cmd/ui-gallery/sections_coverage.go b/native/cmd/ui-gallery/sections_coverage.go index c9839c698..ace12e499 100644 --- a/native/cmd/ui-gallery/sections_coverage.go +++ b/native/cmd/ui-gallery/sections_coverage.go @@ -27,7 +27,7 @@ type coverageState struct { fields [6]widget.Editor clear ui.Clickable - areas [4]widget.Editor + areas [5]widget.Editor groups [5]widget.Editor groupBtn ui.Clickable @@ -237,13 +237,15 @@ func (g *gallery) fieldVariantsSection(gtx C, th *ui.Theme) D { invalid.Invalid = true narrowArea := th.Textarea(&c.areas[3], "Width 240") narrowArea.Width = 240 + bareArea := th.Textarea(&c.areas[4], "Bare: no box and one line tall") + bareArea.Bare = true return ui.Stack(4, ui.Columns(4, labeled(th, "Input, Mono", mono.Layout), labeled(th, "Borderless", borderless.Layout)), ui.Columns(4, labeled(th, "Bare", bare.Layout), labeled(th, "Clear (X while it has text)", clearable.Layout)), ui.Columns(4, labeled(th, "Width", narrow.Layout), labeled(th, "LeadingSize", leading.Layout)), labeled(th, "Textarea, Resize nil", resizeNone.Layout), ui.Columns(4, labeled(th, "Textarea, Disabled", disabled.Layout), labeled(th, "Textarea, Invalid", invalid.Layout)), - labeled(th, "Textarea, Width", narrowArea.Layout), + ui.Columns(4, labeled(th, "Textarea, Width", narrowArea.Layout), labeled(th, "Textarea, Bare", bareArea.Layout)), )(gtx) } diff --git a/native/i18n/locales/en/pulls.json b/native/i18n/locales/en/pulls.json index d58852291..dd0a9667c 100644 --- a/native/i18n/locales/en/pulls.json +++ b/native/i18n/locales/en/pulls.json @@ -56,7 +56,18 @@ }, "pullsChecks": { "none": "No checks reported.", - "required": "Required" + "required": "Required", + "group": { + "failed": "Failed", + "running": "Running", + "passed": "Passed" + }, + "all": "All checks", + "search": "Search the log", + "copyLog": "Copy the log", + "logFailed": "Couldn't read the log: {error}", + "failedIn": "Failed in {duration}, {ago}", + "passedIn": "Passed in {duration}, {ago}" }, "pullsCommits": { "none": "No commits.", @@ -65,11 +76,7 @@ "pullsConflicts": { "loading": "Working out which files conflict…", "failed": "Couldn't work out which files conflict: {error}", - "stale": "No file conflicts here now. GitHub may not have caught up.", - "count": { - "one": "{count} conflicting file", - "other": "{count} conflicting files" - } + "stale": "No file conflicts here now. GitHub may not have caught up." }, "pullsEmptyState": { "openFailed": "Couldn't open a pull request: {error}", @@ -105,41 +112,41 @@ }, "pullsConversation": { "commentFailed": "Comment failed: {error}", - "loading": "Reading the conversation…", "resolved": { "one": "{count} resolved thread", "other": "{count} resolved threads" }, "commentOn": "Comment on the pull request", "comment": "Comment", - "commentPlaceholder": "Something about the pull request as a whole", "readFailed": "Couldn't read the conversation: {error}", - "nothingYet": "Nothing said yet.", "line": "line {line}", "lines": "lines {start}-{end}", - "outdated": "outdated", - "pendingHead": "Pending review", - "pendingNote": "Sent when you submit the review.", + "outdated": "Outdated", + "pendingNote": "Sent when you submit the review", "discard": "Discard", "edit": "Edit", - "save": "Save" + "save": "Save", + "comments": { + "one": "{count} comment", + "other": "{count} comments" + }, + "you": "You" }, "pullsOverview": { "openedBy": "Opened by {author}", - "description": "Description", "noDescription": "No description.", - "reviewers": "Reviewers", - "nobodyYet": "Nobody yet", "copyLink": "Copy link", "copyMarkdown": "Copy Markdown", "save": "Save", "saving": "Saving…", "descriptionPlaceholder": "Describe the change. Markdown works.", - "editFailed": "Couldn't update the description: {error}" + "editFailed": "Couldn't update the description: {error}", + "threadsOpen": "{open} of {total} threads open", + "threadsResolved": "all threads resolved" }, "pullsStats": { "checksFailing": "{failed} of {total} checks failing", - "checksRunning": "{pending} of {total} checks running", + "checksRunning": "{done} of {total} checks", "checksPassed": { "one": "{count} check passed", "other": "{count} checks passed" @@ -151,43 +158,41 @@ "approved": "Approved", "changesRequested": "Changes requested", "reviewRequired": "Review required", - "threadsUnresolved": "Changes requested · {open} of {total} threads unresolved", - "threadsResolved": "Changes requested · all threads resolved", "conflictsWith": "Conflicts with {base}", "conflictFiles": { - "one": "· {count} file", - "other": "· {count} files" + "one": "{count} file", + "other": "{count} files" }, "mergeable": "Mergeable", "checkingMergeability": "Checking mergeability…" }, "pullsList": { - "filter": { - "all": "All", - "ready": "Ready", - "drafts": "Drafts", - "failing": "Failing" + "group": { + "ready": "Ready to merge", + "work": "Needs work", + "review": "In review", + "drafts": "Drafts" }, "none": { "open": "No open pull requests.", "closed": "No closed pull requests.", - "merged": "No merged pull requests.", - "approved": "No approved pull requests." + "merged": "No merged pull requests." }, "noneGitLab": { "open": "No open merge requests.", "closed": "No closed merge requests.", - "merged": "No merged merge requests.", - "approved": "No approved merge requests." + "merged": "No merged merge requests." }, "noMatch": "Nothing matches that filter.", - "draft": "Draft", - "fork": "fork", - "searchHint": "Filter by number, title, author or branch", + "fork": "From a fork", + "searchHint": "Filter pull requests", + "searchHintGitLab": "Filter merge requests", "checksFailed": { "one": "{count} failed", "other": "{count} failed" - } + }, + "threadsResolved": "Threads resolved", + "checkedOutIn": "Checked out in {name}" }, "pullsFiles": { "loadFailed": "Couldn't load the diff: {error}", @@ -204,7 +209,7 @@ "one": "{count} commit", "other": "{count} commits" }, - "rangeNote": "Viewing {range} · comments and Viewed are off", + "rangeNote": "Comments and Viewed are off", "rangeKey": "range" }, "reviewThread": { @@ -232,8 +237,8 @@ "send": "Send to session", "sendTip": "Sends this thread to {name}", "sendAll": { - "one": "Send {count} open thread to session", - "other": "Send {count} open threads to session" + "one": "Send {count} open thread", + "other": "Send {count} open threads" }, "waiting": "Fixed · waiting for a push", "handed": "Sent to session", @@ -317,9 +322,6 @@ "durationMinutes": "{value}m", "durationHours": "{value}h" }, - "pullsPanels": { - "mergeFailing": "Merge · {count} failing" - }, "pullsSubmit": { "review": "Submit review {count}", "withComments": { @@ -337,12 +339,8 @@ "next": "Next pull request", "nextGitLab": "Next merge request", "position": "{index} of {total}", - "switch": "Go to another pull request", - "switchGitLab": "Go to another merge request", "more": "More actions", "create": "New pull request", - "createGitLab": "New merge request", - "checkout": "Checkout", - "notCheckedOut": "Not checked out" + "createGitLab": "New merge request" } } diff --git a/native/i18n/locales/en/session.json b/native/i18n/locales/en/session.json index 94d414851..126fe8c1e 100644 --- a/native/i18n/locales/en/session.json +++ b/native/i18n/locales/en/session.json @@ -42,6 +42,8 @@ "millisecond": "{count}ms", "minute": "{count}m", "hour": "{count}h", + "day": "{count}d", + "week": "{count}w", "ago": { "minute": "{count}m ago", "hour": "{count}h ago", diff --git a/native/i18n/locales/en/tourPulls.json b/native/i18n/locales/en/tourPulls.json index 4a65e2945..1e9cb688f 100644 --- a/native/i18n/locales/en/tourPulls.json +++ b/native/i18n/locales/en/tourPulls.json @@ -8,7 +8,7 @@ }, "filter": { "title": "Find the one you need", - "body": "All, Ready, Drafts and Failing narrow the list, and the field above filters by number, title, author or branch. The menu next to it switches between open, closed and merged." + "body": "Open pull requests are grouped by what each one needs. Type here to filter them by number, title, author or branch; the menu beside it switches to closed and merged." }, "pick": { "title": "Open a pull request", diff --git a/native/i18n/locales/es/pulls.json b/native/i18n/locales/es/pulls.json index 829731dd2..ad8f5daf5 100644 --- a/native/i18n/locales/es/pulls.json +++ b/native/i18n/locales/es/pulls.json @@ -56,7 +56,18 @@ }, "pullsChecks": { "none": "No se informó ninguna comprobación.", - "required": "Obligatorio" + "required": "Obligatorio", + "group": { + "failed": "Fallidas", + "running": "En curso", + "passed": "Superadas" + }, + "all": "Todas las comprobaciones", + "search": "Buscar en el log", + "copyLog": "Copiar el log", + "logFailed": "No se pudo leer el log: {error}", + "failedIn": "Falló en {duration}, {ago}", + "passedIn": "Superada en {duration}, {ago}" }, "pullsCommits": { "none": "No hay commits.", @@ -65,11 +76,7 @@ "pullsConflicts": { "loading": "Averiguando qué archivos están en conflicto…", "failed": "No se pudo averiguar qué archivos están en conflicto: {error}", - "stale": "Ahora mismo no hay archivos en conflicto. Puede que GitHub aún no se haya actualizado.", - "count": { - "one": "{count} archivo en conflicto", - "other": "{count} archivos en conflicto" - } + "stale": "Ahora mismo no hay archivos en conflicto. Puede que GitHub aún no se haya actualizado." }, "pullsEmptyState": { "openFailed": "No se pudo abrir un pull request: {error}", @@ -105,41 +112,41 @@ }, "pullsConversation": { "commentFailed": "No se pudo comentar: {error}", - "loading": "Leyendo la conversación…", "resolved": { "one": "{count} hilo resuelto", "other": "{count} hilos resueltos" }, "commentOn": "Comentar en el pull request", "comment": "Comentar", - "commentPlaceholder": "Algo sobre el pull request en su conjunto", "readFailed": "No se pudo leer la conversación: {error}", - "nothingYet": "Aún no hay comentarios.", "line": "línea {line}", "lines": "líneas {start}-{end}", - "outdated": "desactualizado", - "pendingHead": "Revisión pendiente", - "pendingNote": "Se publicará al enviar la revisión.", + "outdated": "Desactualizado", + "pendingNote": "Se publicará al enviar la revisión", "discard": "Descartar", "edit": "Editar", - "save": "Guardar" + "save": "Guardar", + "comments": { + "one": "{count} comentario", + "other": "{count} comentarios" + }, + "you": "Tú" }, "pullsOverview": { "openedBy": "Abierto por {author}", - "description": "Descripción", "noDescription": "Sin descripción.", - "reviewers": "Revisores", - "nobodyYet": "Nadie todavía", "copyLink": "Copiar enlace", "copyMarkdown": "Copiar Markdown", "save": "Guardar", "saving": "Guardando…", "descriptionPlaceholder": "Describe el cambio. Admite Markdown.", - "editFailed": "No se pudo actualizar la descripción: {error}" + "editFailed": "No se pudo actualizar la descripción: {error}", + "threadsOpen": "{open} de {total} hilos abiertos", + "threadsResolved": "todos los hilos resueltos" }, "pullsStats": { "checksFailing": "{failed} de {total} comprobaciones fallan", - "checksRunning": "{pending} de {total} comprobaciones en curso", + "checksRunning": "{done} de {total} comprobaciones", "checksPassed": { "one": "{count} comprobación superada", "other": "{count} comprobaciones superadas" @@ -151,43 +158,41 @@ "approved": "Aprobado", "changesRequested": "Cambios solicitados", "reviewRequired": "Revisión requerida", - "threadsUnresolved": "Cambios solicitados · {open} de {total} hilos sin resolver", - "threadsResolved": "Cambios solicitados · todos los hilos resueltos", "conflictsWith": "Conflictos con {base}", "conflictFiles": { - "one": "· {count} archivo", - "other": "· {count} archivos" + "one": "{count} archivo", + "other": "{count} archivos" }, "mergeable": "Se puede fusionar", "checkingMergeability": "Comprobando si se puede fusionar…" }, "pullsList": { - "filter": { - "all": "Todos", - "ready": "Listos", - "drafts": "Borradores", - "failing": "Con fallos" + "group": { + "ready": "Listos para fusionar", + "work": "Necesitan cambios", + "review": "En revisión", + "drafts": "Borradores" }, "none": { "open": "No hay pull requests abiertos.", "closed": "No hay pull requests cerrados.", - "merged": "No hay pull requests fusionados.", - "approved": "No hay pull requests aprobados." + "merged": "No hay pull requests fusionados." }, "noneGitLab": { "open": "No hay merge requests abiertos.", "closed": "No hay merge requests cerrados.", - "merged": "No hay merge requests fusionados.", - "approved": "No hay merge requests aprobados." + "merged": "No hay merge requests fusionados." }, "noMatch": "Nada coincide con ese filtro.", - "draft": "Borrador", - "fork": "fork", - "searchHint": "Número, título, autor o rama", + "fork": "De un fork", + "searchHint": "Filtrar pull requests", + "searchHintGitLab": "Filtrar merge requests", "checksFailed": { "one": "{count} fallida", "other": "{count} fallidas" - } + }, + "threadsResolved": "Hilos resueltos", + "checkedOutIn": "Checkout en {name}" }, "pullsFiles": { "loadFailed": "No se pudo cargar el diff: {error}", @@ -204,7 +209,7 @@ "one": "{count} commit", "other": "{count} commits" }, - "rangeNote": "Viendo {range} · sin comentarios ni Visto", + "rangeNote": "Los comentarios y Visto están desactivados", "rangeKey": "rango" }, "reviewThread": { @@ -232,8 +237,8 @@ "send": "Enviar a la sesión", "sendTip": "Envía este hilo a {name}", "sendAll": { - "one": "Enviar {count} hilo abierto a la sesión", - "other": "Enviar {count} hilos abiertos a la sesión" + "one": "Enviar {count} hilo abierto", + "other": "Enviar {count} hilos abiertos" }, "waiting": "Corregido · esperando un push", "handed": "Enviado a la sesión", @@ -317,9 +322,6 @@ "durationMinutes": "{value} min", "durationHours": "{value} h" }, - "pullsPanels": { - "mergeFailing": "Fusionar · {count} fallan" - }, "pullsSubmit": { "review": "Enviar revisión {count}", "withComments": { @@ -337,12 +339,8 @@ "next": "Siguiente pull request", "nextGitLab": "Siguiente merge request", "position": "{index} de {total}", - "switch": "Ir a otro pull request", - "switchGitLab": "Ir a otro merge request", "more": "Más acciones", "create": "Nuevo pull request", - "createGitLab": "Nuevo merge request", - "checkout": "Checkout", - "notCheckedOut": "Sin checkout" + "createGitLab": "Nuevo merge request" } } diff --git a/native/i18n/locales/es/session.json b/native/i18n/locales/es/session.json index dde5e6aca..44dca6362 100644 --- a/native/i18n/locales/es/session.json +++ b/native/i18n/locales/es/session.json @@ -42,6 +42,8 @@ "millisecond": "{count}ms", "minute": "{count}min", "hour": "{count}h", + "day": "{count}d", + "week": "{count}sem.", "ago": { "minute": "hace {count} min", "hour": "hace {count} h", diff --git a/native/i18n/locales/es/tourPulls.json b/native/i18n/locales/es/tourPulls.json index ae1d55e4b..44e0d5d15 100644 --- a/native/i18n/locales/es/tourPulls.json +++ b/native/i18n/locales/es/tourPulls.json @@ -8,7 +8,7 @@ }, "filter": { "title": "Encuentra el que buscas", - "body": "Todos, Listos, Borradores y Con fallos acotan la lista, y el campo de arriba filtra por número, título, autor o rama. El menú de al lado cambia entre abiertos, cerrados y fusionados." + "body": "Los pull requests abiertos se agrupan según lo que necesita cada uno. Escribe aquí para filtrarlos por número, título, autor o rama; el menú de al lado muestra los cerrados y los fusionados." }, "pick": { "title": "Abre un pull request", diff --git a/native/i18n/locales/ja/pulls.json b/native/i18n/locales/ja/pulls.json index 9ec194c34..9b9647507 100644 --- a/native/i18n/locales/ja/pulls.json +++ b/native/i18n/locales/ja/pulls.json @@ -56,7 +56,18 @@ }, "pullsChecks": { "none": "報告されたチェックはありません。", - "required": "必須" + "required": "必須", + "group": { + "failed": "失敗", + "running": "実行中", + "passed": "成功" + }, + "all": "すべてのチェック", + "search": "ログを検索", + "copyLog": "ログをコピー", + "logFailed": "ログを読み込めませんでした: {error}", + "failedIn": "{duration}で失敗、{ago}", + "passedIn": "{duration}で成功、{ago}" }, "pullsCommits": { "none": "コミットはありません。", @@ -65,11 +76,7 @@ "pullsConflicts": { "loading": "コンフリクトしているファイルを調べています…", "failed": "コンフリクトしているファイルを特定できませんでした: {error}", - "stale": "現在コンフリクトしているファイルはありません。GitHub の情報がまだ更新されていない可能性があります。", - "count": { - "one": "コンフリクトしているファイル {count} 件", - "other": "コンフリクトしているファイル {count} 件" - } + "stale": "現在コンフリクトしているファイルはありません。GitHub の情報がまだ更新されていない可能性があります。" }, "pullsEmptyState": { "openFailed": "プルリクエストを作成できませんでした: {error}", @@ -105,41 +112,40 @@ }, "pullsConversation": { "commentFailed": "コメントに失敗しました: {error}", - "loading": "会話を読み込んでいます…", "resolved": { "one": "解決済みのスレッド {count} 件", "other": "解決済みのスレッド {count} 件" }, "commentOn": "プルリクエストにコメント", "comment": "コメント", - "commentPlaceholder": "プルリクエスト全体へのコメント", "readFailed": "会話を読み込めませんでした: {error}", - "nothingYet": "まだコメントはありません。", "line": "{line} 行目", "lines": "{start}-{end} 行目", "outdated": "古い", - "pendingHead": "保留中のレビュー", - "pendingNote": "レビューを送信すると送られます。", + "pendingNote": "レビューを送信すると送られます", "discard": "破棄", "edit": "編集", - "save": "保存" + "save": "保存", + "comments": { + "other": "コメント {count} 件" + }, + "you": "あなた" }, "pullsOverview": { "openedBy": "{author} が作成", - "description": "説明", "noDescription": "説明はありません。", - "reviewers": "レビュアー", - "nobodyYet": "まだいません", "copyLink": "リンクをコピー", "copyMarkdown": "Markdown をコピー", "save": "保存", "saving": "保存中…", "descriptionPlaceholder": "変更内容を説明してください。Markdown が使えます。", - "editFailed": "説明を更新できませんでした: {error}" + "editFailed": "説明を更新できませんでした: {error}", + "threadsOpen": "{total} 件中 {open} 件のスレッドが未解決", + "threadsResolved": "すべてのスレッドが解決済み" }, "pullsStats": { "checksFailing": "{total} 件中 {failed} 件のチェックが失敗", - "checksRunning": "{total} 件中 {pending} 件のチェックが実行中", + "checksRunning": "チェック {done}/{total} 件完了", "checksPassed": { "one": "{count} 件のチェックが成功", "other": "{count} 件のチェックが成功" @@ -151,42 +157,40 @@ "approved": "承認済み", "changesRequested": "変更をリクエスト済み", "reviewRequired": "レビューが必要", - "threadsUnresolved": "変更をリクエスト済み · {total} 件中 {open} 件のスレッドが未解決", - "threadsResolved": "変更をリクエスト済み · すべてのスレッドが解決済み", "conflictsWith": "{base} とコンフリクト", "conflictFiles": { - "one": "· {count} 件", - "other": "· {count} 件" + "one": "{count} 件", + "other": "{count} 件" }, "mergeable": "マージ可能", "checkingMergeability": "マージ可能か確認中…" }, "pullsList": { - "filter": { - "all": "すべて", - "ready": "準備完了", - "drafts": "ドラフト", - "failing": "失敗" + "group": { + "ready": "マージ可能", + "work": "対応が必要", + "review": "レビュー中", + "drafts": "ドラフト" }, "none": { "open": "オープンなプルリクエストはありません。", "closed": "クローズ済みのプルリクエストはありません。", - "merged": "マージ済みのプルリクエストはありません。", - "approved": "承認済みのプルリクエストはありません。" + "merged": "マージ済みのプルリクエストはありません。" }, "noneGitLab": { "open": "オープンなマージリクエストはありません。", "closed": "クローズ済みのマージリクエストはありません。", - "merged": "マージ済みのマージリクエストはありません。", - "approved": "承認済みのマージリクエストはありません。" + "merged": "マージ済みのマージリクエストはありません。" }, "noMatch": "このフィルターに一致するものはありません。", - "draft": "ドラフト", - "fork": "フォーク", - "searchHint": "番号、タイトル、作成者、ブランチで絞り込む", + "fork": "フォークから", + "searchHint": "プルリクエストを絞り込む", + "searchHintGitLab": "マージリクエストを絞り込む", "checksFailed": { "other": "{count} 件失敗" - } + }, + "threadsResolved": "スレッド解決済み", + "checkedOutIn": "{name} でチェックアウト中" }, "pullsFiles": { "loadFailed": "差分を読み込めませんでした: {error}", @@ -201,7 +205,7 @@ "commits": { "other": "{count} 件のコミット" }, - "rangeNote": "{range} を表示中 · コメントと確認済みは使えません", + "rangeNote": "コメントと確認済みは使えません", "rangeKey": "範囲" }, "reviewThread": { @@ -229,8 +233,7 @@ "send": "セッションに送る", "sendTip": "このスレッドを {name} に送ります", "sendAll": { - "one": "未解決のスレッド {count} 件をセッションに送る", - "other": "未解決のスレッド {count} 件をセッションに送る" + "other": "未解決のスレッド {count} 件を送る" }, "waiting": "修正済み · push 待ち", "handed": "セッションに送信済み", @@ -314,9 +317,6 @@ "durationMinutes": "{value}分", "durationHours": "{value}時間" }, - "pullsPanels": { - "mergeFailing": "マージ · {count} 件失敗" - }, "pullsSubmit": { "review": "レビューを送信 {count}", "withComments": { @@ -334,12 +334,8 @@ "next": "次のプルリクエスト", "nextGitLab": "次のマージリクエスト", "position": "{index} / {total}", - "switch": "別のプルリクエストへ移動", - "switchGitLab": "別のマージリクエストへ移動", "more": "その他の操作", "create": "新しいプルリクエスト", - "createGitLab": "新しいマージリクエスト", - "checkout": "チェックアウト", - "notCheckedOut": "未チェックアウト" + "createGitLab": "新しいマージリクエスト" } } diff --git a/native/i18n/locales/ja/session.json b/native/i18n/locales/ja/session.json index 03d13af71..aa159100e 100644 --- a/native/i18n/locales/ja/session.json +++ b/native/i18n/locales/ja/session.json @@ -42,6 +42,8 @@ "millisecond": "{count}ミリ秒", "minute": "{count}分", "hour": "{count}時間", + "day": "{count}日", + "week": "{count}週間", "ago": { "minute": "{count}分前", "hour": "{count}時間前", diff --git a/native/i18n/locales/ja/tourPulls.json b/native/i18n/locales/ja/tourPulls.json index 98a54fb20..17a1bc5dd 100644 --- a/native/i18n/locales/ja/tourPulls.json +++ b/native/i18n/locales/ja/tourPulls.json @@ -8,7 +8,7 @@ }, "filter": { "title": "目的のものを探す", - "body": "「すべて」「準備完了」「ドラフト」「失敗」で一覧を絞り込み、上の欄で番号、タイトル、作成者、ブランチから探せます。横のメニューでオープン、クローズ、マージ済みを切り替えます。" + "body": "オープンなプルリクエストは、それぞれに必要な対応ごとにまとまっています。ここに入力すると番号、タイトル、作成者、ブランチで絞り込めます。横のメニューでクローズ済みとマージ済みに切り替えます。" }, "pick": { "title": "プルリクエストを開く", diff --git a/native/i18n/locales/ko/pulls.json b/native/i18n/locales/ko/pulls.json index db92b142c..faa8f594f 100644 --- a/native/i18n/locales/ko/pulls.json +++ b/native/i18n/locales/ko/pulls.json @@ -56,7 +56,18 @@ }, "pullsChecks": { "none": "보고된 체크가 없습니다.", - "required": "필수" + "required": "필수", + "group": { + "failed": "실패", + "running": "실행 중", + "passed": "통과" + }, + "all": "모든 체크", + "search": "로그 검색", + "copyLog": "로그 복사", + "logFailed": "로그를 읽지 못했습니다: {error}", + "failedIn": "{duration} 만에 실패, {ago}", + "passedIn": "{duration} 만에 통과, {ago}" }, "pullsCommits": { "none": "커밋이 없습니다.", @@ -65,10 +76,7 @@ "pullsConflicts": { "loading": "충돌하는 파일을 확인하는 중…", "failed": "충돌하는 파일을 확인하지 못했습니다: {error}", - "stale": "지금은 충돌하는 파일이 없습니다. GitHub에 아직 반영되지 않았을 수 있습니다.", - "count": { - "other": "충돌하는 파일 {count}개" - } + "stale": "지금은 충돌하는 파일이 없습니다. GitHub에 아직 반영되지 않았을 수 있습니다." }, "pullsEmptyState": { "openFailed": "풀 리퀘스트를 열지 못했습니다: {error}", @@ -104,40 +112,39 @@ }, "pullsConversation": { "commentFailed": "코멘트 실패: {error}", - "loading": "대화를 읽는 중…", "resolved": { "other": "해결된 스레드 {count}개" }, "commentOn": "풀 리퀘스트에 코멘트", "comment": "코멘트", - "commentPlaceholder": "풀 리퀘스트 전체에 대한 의견", "readFailed": "대화를 읽지 못했습니다: {error}", - "nothingYet": "아직 대화가 없습니다.", "line": "{line}번 줄", "lines": "{start}-{end}번 줄", "outdated": "오래됨", - "pendingHead": "대기 중인 리뷰", - "pendingNote": "리뷰를 제출할 때 함께 보냅니다.", + "pendingNote": "리뷰를 제출할 때 함께 보냅니다", "discard": "버리기", "edit": "편집", - "save": "저장" + "save": "저장", + "comments": { + "other": "코멘트 {count}개" + }, + "you": "나" }, "pullsOverview": { "openedBy": "작성자: {author}", - "description": "설명", "noDescription": "설명이 없습니다.", - "reviewers": "리뷰어", - "nobodyYet": "아직 없음", "copyLink": "링크 복사", "copyMarkdown": "Markdown 복사", "save": "저장", "saving": "저장 중…", "descriptionPlaceholder": "변경 사항을 설명하세요. Markdown을 사용할 수 있습니다.", - "editFailed": "설명을 업데이트하지 못했습니다: {error}" + "editFailed": "설명을 업데이트하지 못했습니다: {error}", + "threadsOpen": "스레드 {total}개 중 {open}개 미해결", + "threadsResolved": "모든 스레드 해결됨" }, "pullsStats": { "checksFailing": "체크 {total}개 중 {failed}개 실패", - "checksRunning": "체크 {total}개 중 {pending}개 실행 중", + "checksRunning": "체크 {total}개 중 {done}개 완료", "checksPassed": { "other": "체크 {count}개 통과" }, @@ -148,41 +155,39 @@ "approved": "승인됨", "changesRequested": "변경 요청됨", "reviewRequired": "리뷰 필요", - "threadsUnresolved": "변경 요청됨 · 스레드 {total}개 중 {open}개 미해결", - "threadsResolved": "변경 요청됨 · 모든 스레드 해결됨", "conflictsWith": "{base} 브랜치와 충돌", "conflictFiles": { - "other": "· 파일 {count}개" + "other": "파일 {count}개" }, "mergeable": "병합 가능", "checkingMergeability": "병합 가능 여부 확인 중…" }, "pullsList": { - "filter": { - "all": "전체", - "ready": "준비됨", - "drafts": "초안", - "failing": "실패" + "group": { + "ready": "병합 준비됨", + "work": "수정 필요", + "review": "리뷰 중", + "drafts": "초안" }, "none": { "open": "열린 풀 리퀘스트가 없습니다.", "closed": "닫힌 풀 리퀘스트가 없습니다.", - "merged": "병합된 풀 리퀘스트가 없습니다.", - "approved": "승인된 풀 리퀘스트가 없습니다." + "merged": "병합된 풀 리퀘스트가 없습니다." }, "noneGitLab": { "open": "열린 병합 요청이 없습니다.", "closed": "닫힌 병합 요청이 없습니다.", - "merged": "병합된 병합 요청이 없습니다.", - "approved": "승인된 병합 요청이 없습니다." + "merged": "병합된 병합 요청이 없습니다." }, "noMatch": "그 필터와 일치하는 항목이 없습니다.", - "draft": "초안", - "fork": "포크", - "searchHint": "번호, 제목, 작성자, 브랜치로 필터", + "fork": "포크에서 옴", + "searchHint": "풀 리퀘스트 필터", + "searchHintGitLab": "병합 요청 필터", "checksFailed": { "other": "{count}개 실패" - } + }, + "threadsResolved": "스레드 해결됨", + "checkedOutIn": "{name}에 체크아웃됨" }, "pullsFiles": { "loadFailed": "diff를 불러오지 못했습니다: {error}", @@ -197,7 +202,7 @@ "commits": { "other": "커밋 {count}개" }, - "rangeNote": "{range} 보는 중 · 댓글과 확인함은 쓸 수 없음", + "rangeNote": "코멘트와 확인함은 쓸 수 없음", "rangeKey": "범위" }, "reviewThread": { @@ -225,8 +230,7 @@ "send": "세션으로 보내기", "sendTip": "이 스레드를 {name} 세션에 보냅니다", "sendAll": { - "one": "열린 스레드 {count}개를 세션으로 보내기", - "other": "열린 스레드 {count}개를 세션으로 보내기" + "other": "열린 스레드 {count}개 보내기" }, "waiting": "수정됨 · 푸시 대기 중", "handed": "세션에 보냄", @@ -306,9 +310,6 @@ "durationMinutes": "{value}분", "durationHours": "{value}시간" }, - "pullsPanels": { - "mergeFailing": "병합 · {count}개 실패" - }, "pullsSubmit": { "review": "리뷰 제출 {count}", "withComments": { @@ -325,12 +326,8 @@ "next": "다음 풀 리퀘스트", "nextGitLab": "다음 병합 요청", "position": "{index} / {total}", - "switch": "다른 풀 리퀘스트로 이동", - "switchGitLab": "다른 병합 요청으로 이동", "more": "추가 작업", "create": "새 풀 리퀘스트", - "createGitLab": "새 병합 요청", - "checkout": "체크아웃", - "notCheckedOut": "체크아웃 안 됨" + "createGitLab": "새 병합 요청" } } diff --git a/native/i18n/locales/ko/session.json b/native/i18n/locales/ko/session.json index d895b0476..8c9fba6b6 100644 --- a/native/i18n/locales/ko/session.json +++ b/native/i18n/locales/ko/session.json @@ -41,6 +41,8 @@ "millisecond": "{count}밀리초", "minute": "{count}분", "hour": "{count}시간", + "day": "{count}일", + "week": "{count}주", "ago": { "minute": "{count}분 전", "hour": "{count}시간 전", diff --git a/native/i18n/locales/ko/tourPulls.json b/native/i18n/locales/ko/tourPulls.json index 129d9d9ac..d2905d5ab 100644 --- a/native/i18n/locales/ko/tourPulls.json +++ b/native/i18n/locales/ko/tourPulls.json @@ -8,7 +8,7 @@ }, "filter": { "title": "원하는 것 찾기", - "body": "전체, 준비됨, 초안, 실패로 목록을 좁히고, 위 입력란에서 번호, 제목, 작성자, 브랜치로 찾을 수 있습니다. 옆 메뉴로 열림, 닫힘, 병합됨을 바꿉니다." + "body": "열린 풀 리퀘스트는 각각 필요한 일에 따라 묶여 있습니다. 여기에 입력해 번호, 제목, 작성자, 브랜치로 거르고, 옆 메뉴에서 닫힘과 병합됨으로 바꿉니다." }, "pick": { "title": "풀 리퀘스트 열기", diff --git a/native/i18n/locales/pt-br/pulls.json b/native/i18n/locales/pt-br/pulls.json index 55fb32ff0..3c0574dc9 100644 --- a/native/i18n/locales/pt-br/pulls.json +++ b/native/i18n/locales/pt-br/pulls.json @@ -56,7 +56,18 @@ }, "pullsChecks": { "none": "Nenhum check reportado.", - "required": "Obrigatório" + "required": "Obrigatório", + "group": { + "failed": "Falharam", + "running": "Em execução", + "passed": "Passaram" + }, + "all": "Todos os checks", + "search": "Buscar no log", + "copyLog": "Copiar o log", + "logFailed": "Não foi possível ler o log: {error}", + "failedIn": "Falhou em {duration}, {ago}", + "passedIn": "Passou em {duration}, {ago}" }, "pullsCommits": { "none": "Nenhum commit.", @@ -65,11 +76,7 @@ "pullsConflicts": { "loading": "Descobrindo quais arquivos conflitam…", "failed": "Não foi possível descobrir quais arquivos conflitam: {error}", - "stale": "Nenhum arquivo em conflito agora. O GitHub pode ainda não ter atualizado.", - "count": { - "one": "{count} arquivo em conflito", - "other": "{count} arquivos em conflito" - } + "stale": "Nenhum arquivo em conflito agora. O GitHub pode ainda não ter atualizado." }, "pullsEmptyState": { "openFailed": "Não foi possível abrir um pull request: {error}", @@ -105,41 +112,41 @@ }, "pullsConversation": { "commentFailed": "Falha ao comentar: {error}", - "loading": "Lendo a conversa…", "resolved": { "one": "{count} thread resolvida", "other": "{count} threads resolvidas" }, "commentOn": "Comentar no pull request", "comment": "Comentar", - "commentPlaceholder": "Algo sobre o pull request como um todo", "readFailed": "Não foi possível ler a conversa: {error}", - "nothingYet": "Ainda não há comentários.", "line": "linha {line}", "lines": "linhas {start}-{end}", - "outdated": "desatualizada", - "pendingHead": "Revisão pendente", - "pendingNote": "Vai junto quando você enviar a revisão.", + "outdated": "Desatualizada", + "pendingNote": "Vai junto quando você enviar a revisão", "discard": "Descartar", "edit": "Editar", - "save": "Salvar" + "save": "Salvar", + "comments": { + "one": "{count} comentário", + "other": "{count} comentários" + }, + "you": "Você" }, "pullsOverview": { "openedBy": "Aberto por {author}", - "description": "Descrição", "noDescription": "Sem descrição.", - "reviewers": "Revisores", - "nobodyYet": "Ninguém ainda", "copyLink": "Copiar link", "copyMarkdown": "Copiar Markdown", "save": "Salvar", "saving": "Salvando…", "descriptionPlaceholder": "Descreva a mudança. Aceita Markdown.", - "editFailed": "Não foi possível atualizar a descrição: {error}" + "editFailed": "Não foi possível atualizar a descrição: {error}", + "threadsOpen": "{open} de {total} threads abertas", + "threadsResolved": "todas as threads resolvidas" }, "pullsStats": { "checksFailing": "{failed} de {total} checks falhando", - "checksRunning": "{pending} de {total} checks em execução", + "checksRunning": "{done} de {total} checks", "checksPassed": { "one": "{count} check passou", "other": "{count} checks passaram" @@ -151,43 +158,41 @@ "approved": "Aprovado", "changesRequested": "Alterações solicitadas", "reviewRequired": "Revisão necessária", - "threadsUnresolved": "Alterações solicitadas · {open} de {total} threads sem resolver", - "threadsResolved": "Alterações solicitadas · todas as threads resolvidas", "conflictsWith": "Conflita com {base}", "conflictFiles": { - "one": "· {count} arquivo", - "other": "· {count} arquivos" + "one": "{count} arquivo", + "other": "{count} arquivos" }, "mergeable": "Pronto para merge", "checkingMergeability": "Verificando se pode ser mergeado…" }, "pullsList": { - "filter": { - "all": "Todos", - "ready": "Prontos", - "drafts": "Rascunhos", - "failing": "Falhando" + "group": { + "ready": "Prontos para merge", + "work": "Precisam de ajustes", + "review": "Em revisão", + "drafts": "Rascunhos" }, "none": { "open": "Nenhum pull request aberto.", "closed": "Nenhum pull request fechado.", - "merged": "Nenhum pull request mergeado.", - "approved": "Nenhum pull request aprovado." + "merged": "Nenhum pull request mergeado." }, "noneGitLab": { "open": "Nenhum merge request aberto.", "closed": "Nenhum merge request fechado.", - "merged": "Nenhum merge request mergeado.", - "approved": "Nenhum merge request aprovado." + "merged": "Nenhum merge request mergeado." }, "noMatch": "Nada corresponde a esse filtro.", - "draft": "Rascunho", - "fork": "fork", - "searchHint": "Número, título, autor ou branch", + "fork": "De um fork", + "searchHint": "Filtrar pull requests", + "searchHintGitLab": "Filtrar merge requests", "checksFailed": { "one": "{count} falhou", "other": "{count} falharam" - } + }, + "threadsResolved": "Threads resolvidas", + "checkedOutIn": "Checkout em {name}" }, "pullsFiles": { "loadFailed": "Não foi possível carregar o diff: {error}", @@ -204,7 +209,7 @@ "one": "{count} commit", "other": "{count} commits" }, - "rangeNote": "Vendo {range} · sem comentários nem Visto", + "rangeNote": "Comentários e Visto estão desligados", "rangeKey": "intervalo" }, "reviewThread": { @@ -232,8 +237,8 @@ "send": "Enviar para a sessão", "sendTip": "Envia esta thread para {name}", "sendAll": { - "one": "Enviar {count} thread aberta para a sessão", - "other": "Enviar {count} threads abertas para a sessão" + "one": "Enviar {count} thread aberta", + "other": "Enviar {count} threads abertas" }, "waiting": "Corrigida · aguardando um push", "handed": "Enviada à sessão", @@ -317,9 +322,6 @@ "durationMinutes": "{value}min", "durationHours": "{value}h" }, - "pullsPanels": { - "mergeFailing": "Merge · {count} falhando" - }, "pullsSubmit": { "review": "Enviar revisão {count}", "withComments": { @@ -337,12 +339,8 @@ "next": "Próximo pull request", "nextGitLab": "Próximo merge request", "position": "{index} de {total}", - "switch": "Ir para outro pull request", - "switchGitLab": "Ir para outro merge request", "more": "Mais ações", "create": "Novo pull request", - "createGitLab": "Novo merge request", - "checkout": "Checkout", - "notCheckedOut": "Sem checkout" + "createGitLab": "Novo merge request" } } diff --git a/native/i18n/locales/pt-br/session.json b/native/i18n/locales/pt-br/session.json index d9f769073..ac9f9cc0d 100644 --- a/native/i18n/locales/pt-br/session.json +++ b/native/i18n/locales/pt-br/session.json @@ -42,6 +42,8 @@ "millisecond": "{count} ms", "minute": "{count} min", "hour": "{count} h", + "day": "{count} d", + "week": "{count} sem.", "ago": { "minute": "há {count} min.", "hour": "há {count} h", diff --git a/native/i18n/locales/pt-br/tourPulls.json b/native/i18n/locales/pt-br/tourPulls.json index 0996be584..40ae38f60 100644 --- a/native/i18n/locales/pt-br/tourPulls.json +++ b/native/i18n/locales/pt-br/tourPulls.json @@ -8,7 +8,7 @@ }, "filter": { "title": "Ache o que você procura", - "body": "Todos, Prontos, Rascunhos e Falhando filtram a lista, e o campo acima busca por número, título, autor ou branch. O menu ao lado alterna entre abertos, fechados e mergeados." + "body": "Os pull requests abertos ficam agrupados pelo que cada um precisa. Digite aqui para filtrar por número, título, autor ou branch; o menu ao lado mostra os fechados e os mergeados." }, "pick": { "title": "Abra um pull request", diff --git a/native/i18n/locales/ru/pulls.json b/native/i18n/locales/ru/pulls.json index a0eed2bda..35814b70f 100644 --- a/native/i18n/locales/ru/pulls.json +++ b/native/i18n/locales/ru/pulls.json @@ -56,7 +56,18 @@ }, "pullsChecks": { "none": "Проверок нет.", - "required": "Обязательный" + "required": "Обязательный", + "group": { + "failed": "С ошибкой", + "running": "Выполняются", + "passed": "Пройдены" + }, + "all": "Все проверки", + "search": "Поиск в журнале", + "copyLog": "Скопировать журнал", + "logFailed": "Не удалось прочитать журнал: {error}", + "failedIn": "Ошибка через {duration}, {ago}", + "passedIn": "Пройдена за {duration}, {ago}" }, "pullsCommits": { "none": "Коммитов нет.", @@ -65,13 +76,7 @@ "pullsConflicts": { "loading": "Выясняем, в каких файлах конфликты…", "failed": "Не удалось выяснить, в каких файлах конфликты: {error}", - "stale": "Сейчас конфликтующих файлов нет. Возможно, GitHub ещё не обновил данные.", - "count": { - "one": "{count} конфликтующий файл", - "few": "{count} конфликтующих файла", - "many": "{count} конфликтующих файлов", - "other": "{count} конфликтующего файла" - } + "stale": "Сейчас конфликтующих файлов нет. Возможно, GitHub ещё не обновил данные." }, "pullsEmptyState": { "openFailed": "Не удалось открыть pull request: {error}", @@ -107,7 +112,6 @@ }, "pullsConversation": { "commentFailed": "Не удалось отправить комментарий: {error}", - "loading": "Чтение обсуждения…", "resolved": { "one": "{count} решённое обсуждение", "few": "{count} решённых обсуждения", @@ -116,34 +120,37 @@ }, "commentOn": "Комментарий к pull request", "comment": "Комментировать", - "commentPlaceholder": "Комментарий ко всему pull request", "readFailed": "Не удалось прочитать обсуждение: {error}", - "nothingYet": "Пока ничего не написано.", "line": "строка {line}", "lines": "строки {start}-{end}", - "outdated": "устарело", - "pendingHead": "Черновик ревью", - "pendingNote": "Отправится вместе с ревью.", + "outdated": "Устарело", + "pendingNote": "Отправится вместе с ревью", "discard": "Отбросить", "edit": "Изменить", - "save": "Сохранить" + "save": "Сохранить", + "comments": { + "one": "{count} комментарий", + "few": "{count} комментария", + "many": "{count} комментариев", + "other": "{count} комментария" + }, + "you": "Вы" }, "pullsOverview": { "openedBy": "Открыл(а) {author}", - "description": "Описание", "noDescription": "Описания нет.", - "reviewers": "Ревьюеры", - "nobodyYet": "Пока никого", "copyLink": "Копировать ссылку", "copyMarkdown": "Копировать Markdown", "save": "Сохранить", "saving": "Сохранение…", "descriptionPlaceholder": "Опишите изменение. Поддерживается Markdown.", - "editFailed": "Не удалось обновить описание: {error}" + "editFailed": "Не удалось обновить описание: {error}", + "threadsOpen": "открытых обсуждений: {open} из {total}", + "threadsResolved": "все обсуждения решены" }, "pullsStats": { "checksFailing": "Не пройдено проверок: {failed} из {total}", - "checksRunning": "Выполняется проверок: {pending} из {total}", + "checksRunning": "Проверок завершено: {done} из {total}", "checksPassed": { "one": "{count} проверка пройдена", "few": "{count} проверки пройдены", @@ -157,47 +164,45 @@ "approved": "Одобрен", "changesRequested": "Запрошены изменения", "reviewRequired": "Нужно ревью", - "threadsUnresolved": "Запрошены изменения · нерешённых обсуждений: {open} из {total}", - "threadsResolved": "Запрошены изменения · все обсуждения решены", "conflictsWith": "Конфликты с {base}", "conflictFiles": { - "one": "· {count} файл", - "few": "· {count} файла", - "many": "· {count} файлов", - "other": "· {count} файла" + "one": "{count} файл", + "few": "{count} файла", + "many": "{count} файлов", + "other": "{count} файла" }, "mergeable": "Можно слить", "checkingMergeability": "Проверка возможности слияния…" }, "pullsList": { - "filter": { - "all": "Все", - "ready": "Готовые", - "drafts": "Черновики", - "failing": "С ошибками" + "group": { + "ready": "Можно сливать", + "work": "Нужна доработка", + "review": "На ревью", + "drafts": "Черновики" }, "none": { "open": "Нет открытых pull request.", "closed": "Нет закрытых pull request.", - "merged": "Нет слитых pull request.", - "approved": "Нет одобренных pull request." + "merged": "Нет слитых pull request." }, "noneGitLab": { "open": "Нет открытых merge request.", "closed": "Нет закрытых merge request.", - "merged": "Нет слитых merge request.", - "approved": "Нет одобренных merge request." + "merged": "Нет слитых merge request." }, "noMatch": "Под этот фильтр ничего не подходит.", - "draft": "Черновик", - "fork": "форк", - "searchHint": "Фильтр по номеру, названию, автору или ветке", + "fork": "Из форка", + "searchHint": "Фильтр pull request", + "searchHintGitLab": "Фильтр merge request", "checksFailed": { "one": "{count} с ошибкой", "few": "{count} с ошибкой", "many": "{count} с ошибкой", "other": "{count} с ошибкой" - } + }, + "threadsResolved": "Обсуждения решены", + "checkedOutIn": "Открыт в {name}" }, "pullsFiles": { "loadFailed": "Не удалось загрузить изменения: {error}", @@ -218,7 +223,7 @@ "many": "{count} коммитов", "other": "{count} коммита" }, - "rangeNote": "Показано {range} · комментарии и «Просмотрено» отключены", + "rangeNote": "Комментарии и «Просмотрено» отключены", "rangeKey": "диапазон" }, "reviewThread": { @@ -246,10 +251,10 @@ "send": "Отправить в сессию", "sendTip": "Отправляет это обсуждение в «{name}»", "sendAll": { - "one": "Отправить {count} открытое обсуждение в сессию", - "few": "Отправить {count} открытых обсуждения в сессию", - "many": "Отправить {count} открытых обсуждений в сессию", - "other": "Отправить {count} открытого обсуждения в сессию" + "one": "Отправить {count} открытое обсуждение", + "few": "Отправить {count} открытых обсуждения", + "many": "Отправить {count} открытых обсуждений", + "other": "Отправить {count} открытого обсуждения" }, "waiting": "Исправлено · ждёт push", "handed": "Отправлено в сессию", @@ -343,9 +348,6 @@ "durationMinutes": "{value} мин", "durationHours": "{value} ч" }, - "pullsPanels": { - "mergeFailing": "Слияние · не пройдено: {count}" - }, "pullsSubmit": { "review": "Отправить ревью {count}", "withComments": { @@ -365,12 +367,8 @@ "next": "Следующий pull request", "nextGitLab": "Следующий merge request", "position": "{index} из {total}", - "switch": "Перейти к другому pull request", - "switchGitLab": "Перейти к другому merge request", "more": "Другие действия", "create": "Новый pull request", - "createGitLab": "Новый merge request", - "checkout": "Рабочая копия", - "notCheckedOut": "Нет рабочей копии" + "createGitLab": "Новый merge request" } } diff --git a/native/i18n/locales/ru/session.json b/native/i18n/locales/ru/session.json index 28657f5e7..94294998c 100644 --- a/native/i18n/locales/ru/session.json +++ b/native/i18n/locales/ru/session.json @@ -44,6 +44,8 @@ "millisecond": "{count} мс", "minute": "{count} мин", "hour": "{count} ч", + "day": "{count} дн.", + "week": "{count} нед.", "ago": { "minute": "{count} мин назад", "hour": "{count} ч назад", diff --git a/native/i18n/locales/ru/tourPulls.json b/native/i18n/locales/ru/tourPulls.json index 1d32a2eaf..58baa6eaa 100644 --- a/native/i18n/locales/ru/tourPulls.json +++ b/native/i18n/locales/ru/tourPulls.json @@ -8,7 +8,7 @@ }, "filter": { "title": "Найдите нужный", - "body": "«Все», «Готовые», «Черновики» и «С ошибками» сужают список, а поле выше фильтрует по номеру, названию, автору или ветке. Меню рядом переключает между открытыми, закрытыми и слитыми." + "body": "Открытые pull request сгруппированы по тому, что нужно каждому. Введите здесь номер, название, автора или ветку, чтобы отфильтровать список; меню рядом показывает закрытые и слитые." }, "pick": { "title": "Откройте pull request", diff --git a/native/i18n/locales/zh-cn/pulls.json b/native/i18n/locales/zh-cn/pulls.json index c895f780c..a75ad68f5 100644 --- a/native/i18n/locales/zh-cn/pulls.json +++ b/native/i18n/locales/zh-cn/pulls.json @@ -56,7 +56,18 @@ }, "pullsChecks": { "none": "没有检查结果。", - "required": "必需" + "required": "必需", + "group": { + "failed": "失败", + "running": "运行中", + "passed": "通过" + }, + "all": "所有检查", + "search": "搜索日志", + "copyLog": "复制日志", + "logFailed": "无法读取日志:{error}", + "failedIn": "{duration}后失败,{ago}", + "passedIn": "{duration}后通过,{ago}" }, "pullsCommits": { "none": "没有提交。", @@ -65,11 +76,7 @@ "pullsConflicts": { "loading": "正在判断哪些文件存在冲突…", "failed": "无法判断哪些文件存在冲突:{error}", - "stale": "目前没有文件冲突,GitHub 可能尚未同步。", - "count": { - "one": "{count} 个冲突文件", - "other": "{count} 个冲突文件" - } + "stale": "目前没有文件冲突,GitHub 可能尚未同步。" }, "pullsEmptyState": { "openFailed": "无法打开拉取请求:{error}", @@ -105,41 +112,40 @@ }, "pullsConversation": { "commentFailed": "评论失败:{error}", - "loading": "正在读取对话…", "resolved": { "one": "{count} 个已解决的讨论串", "other": "{count} 个已解决的讨论串" }, "commentOn": "评论此拉取请求", "comment": "评论", - "commentPlaceholder": "针对整个拉取请求发表评论", "readFailed": "无法读取对话:{error}", - "nothingYet": "还没有评论。", "line": "第 {line} 行", "lines": "第 {start}-{end} 行", "outdated": "已过时", - "pendingHead": "待提交的评审", - "pendingNote": "提交评审时发送。", + "pendingNote": "提交评审时发送", "discard": "丢弃", "edit": "编辑", - "save": "保存" + "save": "保存", + "comments": { + "other": "{count} 条评论" + }, + "you": "你" }, "pullsOverview": { "openedBy": "由 {author} 打开", - "description": "描述", "noDescription": "没有描述。", - "reviewers": "评审者", - "nobodyYet": "暂无", "copyLink": "复制链接", "copyMarkdown": "复制 Markdown", "save": "保存", "saving": "正在保存…", "descriptionPlaceholder": "描述这项更改,支持 Markdown。", - "editFailed": "无法更新描述:{error}" + "editFailed": "无法更新描述:{error}", + "threadsOpen": "{total} 个讨论串中有 {open} 个未解决", + "threadsResolved": "所有讨论串均已解决" }, "pullsStats": { "checksFailing": "{total} 项检查中有 {failed} 项失败", - "checksRunning": "{total} 项检查中有 {pending} 项正在运行", + "checksRunning": "{total} 项检查已完成 {done} 项", "checksPassed": { "one": "{count} 项检查通过", "other": "{count} 项检查通过" @@ -151,42 +157,40 @@ "approved": "已批准", "changesRequested": "已请求更改", "reviewRequired": "需要评审", - "threadsUnresolved": "已请求更改 · {total} 个讨论串中有 {open} 个未解决", - "threadsResolved": "已请求更改 · 所有讨论串均已解决", "conflictsWith": "与 {base} 存在冲突", "conflictFiles": { - "one": "· {count} 个文件", - "other": "· {count} 个文件" + "one": "{count} 个文件", + "other": "{count} 个文件" }, "mergeable": "可合并", "checkingMergeability": "正在检查是否可合并…" }, "pullsList": { - "filter": { - "all": "全部", - "ready": "就绪", - "drafts": "草稿", - "failing": "失败" + "group": { + "ready": "可以合并", + "work": "需要处理", + "review": "评审中", + "drafts": "草稿" }, "none": { "open": "没有打开的拉取请求。", "closed": "没有已关闭的拉取请求。", - "merged": "没有已合并的拉取请求。", - "approved": "没有已批准的拉取请求。" + "merged": "没有已合并的拉取请求。" }, "noneGitLab": { "open": "没有打开的合并请求。", "closed": "没有已关闭的合并请求。", - "merged": "没有已合并的合并请求。", - "approved": "没有已批准的合并请求。" + "merged": "没有已合并的合并请求。" }, "noMatch": "没有符合该筛选条件的内容。", - "draft": "草稿", - "fork": "分叉", - "searchHint": "按编号、标题、作者或分支筛选", + "fork": "来自分叉", + "searchHint": "筛选拉取请求", + "searchHintGitLab": "筛选合并请求", "checksFailed": { "other": "{count} 项失败" - } + }, + "threadsResolved": "讨论串已解决", + "checkedOutIn": "已检出到 {name}" }, "pullsFiles": { "loadFailed": "无法加载差异:{error}", @@ -201,7 +205,7 @@ "commits": { "other": "{count} 个提交" }, - "rangeNote": "正在查看 {range} · 评论和已查看不可用", + "rangeNote": "评论和已查看不可用", "rangeKey": "范围" }, "reviewThread": { @@ -229,8 +233,7 @@ "send": "发送到会话", "sendTip": "将此讨论串发送给 {name}", "sendAll": { - "one": "将 {count} 个未解决的讨论串发送到会话", - "other": "将 {count} 个未解决的讨论串发送到会话" + "other": "发送 {count} 个未解决的讨论串" }, "waiting": "已修复 · 等待 push", "handed": "已发送到会话", @@ -314,9 +317,6 @@ "durationMinutes": "{value}分钟", "durationHours": "{value}小时" }, - "pullsPanels": { - "mergeFailing": "合并 · {count} 项失败" - }, "pullsSubmit": { "review": "提交评审 {count}", "withComments": { @@ -334,12 +334,8 @@ "next": "下一个拉取请求", "nextGitLab": "下一个合并请求", "position": "{index} / {total}", - "switch": "前往其他拉取请求", - "switchGitLab": "前往其他合并请求", "more": "更多操作", "create": "新建拉取请求", - "createGitLab": "新建合并请求", - "checkout": "检出", - "notCheckedOut": "未检出" + "createGitLab": "新建合并请求" } } diff --git a/native/i18n/locales/zh-cn/session.json b/native/i18n/locales/zh-cn/session.json index fd191238b..a06eb350d 100644 --- a/native/i18n/locales/zh-cn/session.json +++ b/native/i18n/locales/zh-cn/session.json @@ -42,6 +42,8 @@ "millisecond": "{count}毫秒", "minute": "{count}分钟", "hour": "{count}小时", + "day": "{count}天", + "week": "{count}周", "ago": { "minute": "{count}分钟前", "hour": "{count}小时前", diff --git a/native/i18n/locales/zh-cn/tourPulls.json b/native/i18n/locales/zh-cn/tourPulls.json index 7a1b3db92..417c35300 100644 --- a/native/i18n/locales/zh-cn/tourPulls.json +++ b/native/i18n/locales/zh-cn/tourPulls.json @@ -8,7 +8,7 @@ }, "filter": { "title": "找到你要的那个", - "body": "“全部”“就绪”“草稿”和“失败”用来缩小列表,上方的输入框可按编号、标题、作者或分支筛选。旁边的菜单用于在打开、已关闭和已合并之间切换。" + "body": "打开的拉取请求按各自需要的处理分组。在此输入可按编号、标题、作者或分支筛选;旁边的菜单可切换到已关闭和已合并。" }, "pick": { "title": "打开一个拉取请求", diff --git a/native/ui/textarea.go b/native/ui/textarea.go index dad86d43c..52f8e0f08 100644 --- a/native/ui/textarea.go +++ b/native/ui/textarea.go @@ -58,6 +58,9 @@ type TextareaStyle struct { Mono bool Disabled bool Invalid bool + // Bare draws no box at all and gives up the floor of min-h-16: the text + // field of a box the caller draws, one line tall until it is written in. + Bare bool // Steady draws the frame the same focused and not, with no ring and the // resting border: the blinking caret is what says the keyboard is there. Steady bool @@ -87,6 +90,9 @@ func (s TextareaStyle) Layout(gtx C) D { field := inputText{theme: s.theme, editor: s.Editor, placeholder: s.Placeholder, size: TextSM, leading: s.Leading, font: font.Font{Typeface: s.theme.Sans}, padLeft: inputPadX, padRight: inputPadX, padY: textareaPadY, minHeight: max(textareaMinHeight, min(s.MinHeight, gtx.Metric.PxToDp(gtx.Constraints.Max.Y)))} + if s.Bare { + field.minHeight = s.MinHeight + } if s.Mono { field.font.Typeface = s.theme.Mono } @@ -108,7 +114,7 @@ func (s TextareaStyle) Layout(gtx C) D { field.minHeight = unit.Dp(float32(h) / gtx.Metric.PxPerDp) } } - st := inputState{invalid: s.Invalid, disabled: s.Disabled, radius: s.Radius, steady: s.Steady} + st := inputState{invalid: s.Invalid, disabled: s.Disabled, radius: s.Radius, steady: s.Steady, bare: s.Bare} d := inputFrame(gtx, s.theme, s.Editor, st, false, func(gtx C) D { return s.body(gtx, field) }) if s.History != nil { s.History.observe(gtx.Now, s.Editor)