use super::{Click, Opened, ReviewView, Row, Screen, Tab, Thing};
use super::{CreateStage, Field, Press};
use crate::config::Rgba;
use crate::render::glyphs::STYLE_BOLD;
use crate::render::gpu::{MODE_SOLID, Quad};
use crate::render::{Ctx, mix, quad, rounded, text, with_alpha};
use crate::review::diff::{FileDiff, Kind as DiffKind, Status};
use crate::review::forge::Method;
use crate::review::guide::{self, Kind as StageKind};
use crate::review::render::snippet;
use crate::review::rules::{Finding, Level};
use crate::review::session::{self, Seen, State, Verdict};
use crate::terminal::layout::Rect;
mod change;
mod flow;
use change::*;
use flow::*;
pub type Piece = (String, bool);
pub fn wrap(source: &str, cols: usize) -> Vec<Vec<Piece>> {
let cols = cols.max(4);
let paired = source.matches('`').count() / 2 * 2;
let mut seen = 0;
let mut code = false;
let mut words: Vec<Vec<(char, bool)>> = vec![Vec::new()];
for c in source.chars() {
if c == '`' && seen < paired {
seen += 1;
code = !code;
} else if c == ' ' || c == '\n' || c == '\t' {
words.push(Vec::new());
} else if !c.is_control() {
words.last_mut().expect("never empty").push((c, code));
}
}
let mut lines: Vec<Vec<(char, bool)>> = vec![Vec::new()];
for word in words.into_iter().filter(|w| !w.is_empty()) {
let line = lines.last_mut().expect("never empty");
if !line.is_empty() {
if line.len() + 1 + word.len() <= cols {
let inside = line.last().is_some_and(|l| l.1) && word[0].1;
line.push((' ', inside));
} else {
lines.push(Vec::new());
}
}
for c in word {
if lines.last().expect("never empty").len() >= cols {
lines.push(Vec::new());
}
lines.last_mut().expect("never empty").push(c);
}
}
lines
.into_iter()
.map(|line| {
let mut pieces: Vec<Piece> = Vec::new();
for (c, code) in line {
match pieces.last_mut() {
Some(p) if p.1 == code => p.0.push(c),
_ => pieces.push((c.to_string(), code)),
}
}
pieces
})
.collect()
}
fn level_tag(level: Level) -> &'static str {
match level {
Level::Risk => "RISK",
Level::Warn => "WARNING",
Level::Note => "NOTE",
}
}
pub fn draw(ctx: &mut Ctx, view: &mut ReviewView, rect: Rect, out: &mut Vec<Quad>) -> bool {
let colors = Colors::new(ctx);
let (cw, ch, s) = (ctx.glyphs.cell_w, ctx.glyphs.cell_h, ctx.scale);
view.rect = rect;
view.list_rect = Rect::default();
view.hits.clear();
let radius = ctx.config.radius * s;
let edge = if view.focused && ctx.focused { colors.accent } else { colors.line };
out.push(rounded(rect, colors.panel, radius, (1.5 * s).round().max(1.0), edge, crate::render::NO_CLIP));
let pad = (14.0 * s).round().min(rect.w * 0.05);
let inner = Rect::new(rect.x + pad, rect.y + pad, (rect.w - 2.0 * pad).max(0.0), (rect.h - 2.0 * pad).max(0.0));
if inner.w < cw * 12.0 || inner.h < ch * 8.0 {
return false;
}
let (title, subtitle) = titles(view);
let header_h = (ch * 1.6).round();
let mut right = inner.right();
{
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, inner, 0.0);
let close = button("\u{2715}", Click::Close);
let w = f.button_width(&close);
right -= w;
f.button_at(Rect::new(right, inner.y, w, header_h), close);
right -= 6.0 * s;
f.put(inner.x, inner.y + (header_h - ch) * 0.5, &title, colors.fg, STYLE_BOLD, right - inner.x);
if !short(inner.h, ch) {
f.y = inner.y + header_h + (ch * 0.25).round();
f.put(inner.x, f.y, &subtitle, colors.muted, 0, inner.w);
}
}
let top = inner.y + header_h + (ch * if short(inner.h, ch) { 0.35 } else { 1.75 }).round();
let body = Rect::new(inner.x, top, inner.w, (inner.bottom() - top).max(0.0));
let focused = view.focused;
match &view.screen {
Screen::Git(_) => return draw_git(ctx, view, body, out),
Screen::Create(_) => return draw_create(ctx, view, body, out),
Screen::Pick(_) => draw_picker(ctx, view, body, out),
Screen::Open(_) => {
let again = draw_change(ctx, view, body, out);
draw_menu(ctx, view, rect, out);
return again;
}
Screen::Loading(what) => {
let what = what.clone();
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, body, 0.0);
f.gap(1.0);
f.para(&format!("{what}\u{2026}"), colors.soft, 0, 0.0);
f.gap(0.5);
f.para("A pull request is fetched from its host first.", colors.muted, 0, 0.0);
}
Screen::Message { text: message, error } => {
let (message, error) = (message.clone(), *error);
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, body, 0.0);
f.gap(0.5);
f.callout(&message, if error { colors.red } else { colors.cyan });
f.gap(1.0);
f.buttons(vec![button("\u{2039} All changes", Click::Back), button("Try again", Click::Reload)]);
if focused {
f.gap(1.0);
f.keys(&[("esc", "back to the list"), ("r", "try again")]);
}
}
}
false
}
fn titles(view: &ReviewView) -> (String, String) {
let folder = view.cwd.to_string_lossy().into_owned();
match &view.screen {
Screen::Git(g) => (
"Git".into(),
g.snapshot
.as_ref()
.map_or(folder, |s| format!("{} \u{00b7} {} changed \u{00b7} {}", s.branch, s.dirty, s.root.display())),
),
Screen::Pick(_) => ("Review a change".to_string(), folder),
Screen::Create(_) => ("New pull request".to_string(), folder),
Screen::Loading(_) | Screen::Message { .. } => ("Review".to_string(), folder),
Screen::Open(o) => {
let r = &o.change.report;
let project =
if r.project.is_empty() { String::new() } else { format!(" \u{00b7} {}", r.project.join(", ")) };
let files = if r.files == 1 { "file" } else { "files" };
(
o.change.title.clone(),
format!("{} \u{00b7} {} {files} +{} \u{2212}{}{project}", r.against, r.files, r.added, r.removed),
)
}
}
}
fn draw_git(ctx: &mut Ctx, view: &mut ReviewView, body: Rect, out: &mut Vec<Quad>) -> bool {
use super::workspace::{Control, Form, Tab};
use crate::review::workspace::Action;
let Screen::Git(g) = &view.screen else { return false };
let c = Colors::new(ctx);
let ch = ctx.glyphs.cell_h;
let cw = ctx.glyphs.cell_w;
let hints: Hints = if g.busy {
Vec::new()
} else if g.form.is_some() || g.preview.is_some() {
vec![("enter", "confirm"), ("esc", "cancel")]
} else if g.tab == Tab::Branches {
vec![
("\u{2191}\u{2193}", "choose"),
("enter", "switch"),
("n", "new"),
("/", "filter"),
("tab", "commits"),
("p", "PR"),
("c", "copy"),
("esc", "terminal"),
]
} else {
vec![
("\u{2191}\u{2193}", "choose"),
("space", "select to here"),
("enter", "review"),
("m", "move"),
("u", "undo"),
("y", "publish"),
("tab", "branches"),
("esc", "terminal"),
]
};
let said = if view.status.is_some() { ch * 3.75 } else { 0.0 };
let footer_h = said + ch + hint_rows(&hints, body.w, cw) as f32 * hint_row_height(ch);
let area = Rect::new(body.x, body.y, body.w, (body.h - footer_h).max(0.0));
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, area, view.scroll);
let start = f.y;
let mut chosen = None;
let action = |name, control| button(name, Click::GitAction(control));
if let Some(preview) = &g.preview {
let (title, movement) = match preview {
Action::Move(m) => ("Move commits", Some(m)),
Action::Undo(m) => ("Undo move", Some(m)),
Action::Publish { movement, .. } => ("Publish recovery", Some(movement)),
_ => ("Git", None),
};
f.para(title, c.fg, STYLE_BOLD, 0.0);
f.gap(0.7);
if let Some(m) = movement {
let short = |id: &str| id.chars().take(8).collect::<String>();
let (from, to) = if matches!(preview, Action::Undo(_)) { (&m.base, &m.old) } else { (&m.old, &m.base) };
if let Action::Publish { expected, desired, remote, .. } = preview {
f.para(&crate::review::workspace::remote_label(remote), c.soft, 0, 0.0);
f.para(&format!("Remote {}: {} \u{2192} {}", m.source, short(expected), short(desired)), c.fg, 0, 0.0);
f.para("Atomic push \u{00b7} force-with-lease", c.yellow, 0, 0.0);
} else {
f.para(&format!("{}: {} \u{2192} {}", m.source, short(from), short(to)), c.fg, 0, 0.0);
}
f.para(&format!("{}: {} \u{00b7} {} commits", m.destination, short(&m.old), m.count), c.soft, 0, 0.0);
f.gap(0.7);
if !matches!(preview, Action::Publish { .. }) {
f.para("Local only \u{00b7} undo available", c.muted, 0, 0.0);
}
}
f.gap(1.0);
f.buttons(vec![action("Confirm", Control::Accept).key("enter"), action("Cancel", Control::Cancel).key("esc")]);
} else {
f.buttons(vec![
action(if g.tab == Tab::Branches { "Branches \u{2022}" } else { "Branches" }, Control::Branches),
action(if g.tab == Tab::Commits { "Commits \u{2022}" } else { "Commits" }, Control::Commits),
action("PR", Control::PullRequest).key("p"),
action("Refresh", Control::Refresh).key("r"),
action("Fetch", Control::Fetch).key("f"),
]);
f.gap(0.5);
if let Some(form) = g.form {
let label = match form {
Form::Create => "New branch",
Form::Move(_) => "Move to new branch",
Form::Filter => "Filter branches",
};
f.para(label, c.soft, 0, 0.0);
f.field(&g.text, "enter name", view.focused, None);
f.gap(0.5);
} else if !g.filter.is_empty() && g.tab == Tab::Branches {
f.para(&format!("/ {}", g.filter), c.muted, 0, 0.0);
}
if let Some(s) = &g.snapshot {
if g.tab == Tab::Commits {
f.para(
&format!("{} selected \u{00b7} latest first", (g.oldest + 1).min(s.commits.len())),
c.muted,
0,
0.0,
);
f.gap(0.3);
}
if s.recovery.is_some() {
f.para(
if s.undo.is_some() {
"Recovery \u{00b7} undo u \u{00b7} publish y"
} else {
"Restored \u{00b7} publish y"
},
c.soft,
0,
0.0,
);
f.gap(0.4);
}
let rows = g.rows();
if rows.is_empty() {
f.para("No matches", c.muted, 0, 0.0);
}
for (i, (name, detail)) in rows.iter().enumerate() {
let row = Rect::new(f.x, f.y, f.w, (f.ch * 1.65).round());
let selected = i == g.selected;
if selected {
f.fill(row, mix(c.panel, c.accent, 0.18), 6.0);
} else if f.hovered(row) {
f.fill(row, c.raised, 6.0);
}
let label = if detail == "current" {
format!("\u{2022} {name}")
} else if detail == "remote" {
format!("{name} \u{00b7} remote")
} else {
name.clone()
};
f.put(
row.x + f.cw,
row.y + f.ch * 0.25,
&label,
if selected { c.fg } else { c.soft },
0,
row.w - f.cw * 2.0,
);
f.hit(row, Click::GitRow(i));
f.y = row.bottom();
if selected {
chosen = Some((row.y - start, row.h));
}
}
} else {
f.para(if g.busy { "Loading\u{2026}" } else { "Refresh to retry" }, c.muted, 0, 0.0);
}
}
let height = f.y - start;
view.max_scroll = (height - area.h).max(0.0);
let previous = view.scroll;
if view.reveal {
if let Some(chosen) = chosen.filter(|_| g.form.is_none()) {
view.scroll = scrolled_to(view.scroll, chosen, area.h, ch);
}
view.reveal = false;
}
view.scroll = view.scroll.clamp(0.0, view.max_scroll);
scrollbar(out, area, view.scroll, view.max_scroll, ctx.scale, c);
let footer = below(body, area.bottom() + ch * 0.3, footer_h - ch * 0.3);
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, footer, 0.0);
f.rule();
f.gap(0.3);
if let Some((message, error)) = &view.status {
for line in wrap(message, f.cols(f.w)).into_iter().take(3) {
let text: String = line.into_iter().map(|(s, _)| s).collect();
f.put(f.x, f.y, &text, if *error { c.red } else { c.green }, 0, f.w);
f.y += f.line_height();
}
}
if g.busy {
f.para("Working\u{2026}", c.muted, 0, 0.0);
} else {
f.keys(&hints);
}
(previous - view.scroll).abs() > 1.0
}
fn draw_create(ctx: &mut Ctx, view: &mut ReviewView, body: Rect, out: &mut Vec<Quad>) -> bool {
let Screen::Create(c) = &view.screen else { return false };
let colors = Colors::new(ctx);
let ch = ctx.glyphs.cell_h;
let said = if view.status.is_some() { ch * 3.0 } else { 0.0 };
let footer_h = said + ch + 2.0 * hint_row_height(ch);
let area = Rect::new(body.x, body.y, body.w, (body.h - footer_h).max(0.0));
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, area, view.scroll);
let start = f.y;
let mut chosen = None;
let press = |name: &str, p: Press| button(name, Click::Create(p));
let hint: Hints = match &c.stage {
CreateStage::Loading => {
f.gap(0.5);
f.para("Looking at the branch and asking the host\u{2026}", colors.soft, 0, 0.0);
vec![("esc", "back")]
}
CreateStage::Failed(why) => {
f.gap(0.5);
f.callout(why, colors.red);
f.gap(1.0);
f.buttons(vec![press("\u{2039} All changes", Press::Cancel)]);
vec![("r", "try again"), ("esc", "back")]
}
CreateStage::Done { pull, created } => {
f.gap(0.5);
let said = match created {
Some(host) => format!("Created pull request #{} on {host}", pull.number),
None => format!("This branch already has an open pull request, #{}", pull.number),
};
f.callout(&said, colors.green);
f.gap(0.7);
f.para(&pull.title, colors.fg, STYLE_BOLD, 0.0);
f.para(&pull.url, colors.muted, 0, 0.0);
f.gap(1.0);
f.buttons(vec![
press("Review it", Press::Review),
press("Open in browser", Press::Open),
press("Copy link", Press::Copy),
]);
vec![("enter", "review it"), ("o", "browser"), ("c", "copy link"), ("esc", "back")]
}
CreateStage::Form | CreateStage::Confirm | CreateStage::Sending => match &c.proposal {
None => vec![("esc", "back")],
Some(p) => {
f.para(&format!("{} \u{2192} {}", p.pull.head, p.pull.base), colors.accent, STYLE_BOLD, 0.0);
let count =
if p.commits.len() == 1 { "1 commit".into() } else { format!("{} commits", p.commits.len()) };
f.para(&format!("{count} \u{00b7} {}", p.host), colors.muted, 0, 0.0);
if p.dirty > 0 {
f.gap(0.4);
let left = format!("Uncommitted changes in {} files are not part of it", p.dirty);
f.callout(&left, colors.yellow);
}
f.gap(0.8);
if matches!(c.stage, CreateStage::Form) {
for (label, field, value) in
[("Title", Field::Title, &p.pull.title), ("Merge into", Field::Base, &p.pull.base)]
{
let top = f.y;
f.para(label, colors.soft, 0, 0.0);
let on = c.field == field;
f.field(value, label, on && view.focused, Some(Click::Create(Press::Focus(field))));
if on {
chosen = Some((top - start, f.y - top));
}
f.gap(0.6);
}
let top = f.y;
f.para("Description", colors.soft, 0, 0.0);
let on = c.field == Field::Description;
f.text_box(&p.pull.body, on && view.focused, Click::Create(Press::Focus(Field::Description)));
if on {
let (from, to) = (top - start, f.y - start);
let shown = (to - from).min(area.h * 0.8);
chosen = Some((to - shown, shown));
}
f.gap(0.8);
let top = f.y;
let mut next = press("Continue \u{203a}", Press::Accept);
if c.field == Field::Continue {
next = next.tone(colors.accent, true);
chosen = Some((top - start, ch * 2.0));
}
f.buttons(vec![next]);
vec![("tab", "next field"), ("enter", "next, or a new line in the description"), ("esc", "back")]
} else {
f.para(&p.pull.title, colors.fg, STYLE_BOLD, 0.0);
f.gap(0.4);
for line in p.pull.body.lines() {
f.para(line, colors.soft, 0, 0.0);
}
f.gap(0.8);
let push = if p.push {
format!("1. Push {} to {} (not forced). ", p.pull.head, p.remote) + "2. "
} else {
String::new()
};
let will = format!("{push}Create a pull request on {} into {}.", p.host, p.pull.base);
f.callout(&will, colors.yellow);
f.gap(1.0);
if matches!(c.stage, CreateStage::Sending) {
f.para("Sending\u{2026}", colors.soft, 0, 0.0);
vec![("esc", "terminal; it carries on")]
} else {
f.buttons(vec![
press("Create", Press::Accept).key("enter"),
press("Back", Press::Cancel).key("esc"),
]);
vec![("enter", "create"), ("esc", "back to editing")]
}
}
}
},
};
let height = f.y - start;
view.max_scroll = (height - area.h).max(0.0);
let previous = view.scroll;
if view.reveal {
if let Some(chosen) = chosen {
view.scroll = scrolled_to(view.scroll, chosen, area.h, ch);
}
view.reveal = false;
}
view.scroll = view.scroll.clamp(0.0, view.max_scroll);
scrollbar(out, area, view.scroll, view.max_scroll, ctx.scale, colors);
let footer = below(body, area.bottom() + ch * 0.3, footer_h - ch * 0.3);
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, footer, 0.0);
f.rule();
f.gap(0.3);
if let Some((message, error)) = &view.status {
let color = if *error { colors.red } else { colors.green };
for line in wrap(message, f.cols(f.w)).into_iter().take(3) {
let text: String = line.into_iter().map(|(s, _)| s).collect();
f.put(f.x, f.y, &text, color, 0, f.w);
f.y += f.line_height();
}
}
f.keys(&hint);
(previous - view.scroll).abs() > 1.0
}
fn draw_picker(ctx: &mut Ctx, view: &mut ReviewView, body: Rect, out: &mut Vec<Quad>) {
let Screen::Pick(picker) = &view.screen else { return };
let rows = picker.rows();
let (filter, selected) = (picker.filter.clone(), picker.selected);
let (ch, s) = (ctx.glyphs.cell_h, ctx.scale);
let colors = Colors::new(ctx);
let hints: Hints = if view.focused {
vec![("\u{2191}\u{2193}", "choose"), ("enter", "review"), ("type", "to filter"), ("esc", "clear, or terminal")]
} else {
vec![("click", "here to type")]
};
let rows_h = hint_rows(&hints, body.w, ctx.glyphs.cell_w) as f32 * hint_row_height(ch);
let footer_h = rows_h + (ch * 0.3).round();
let field_end = {
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, body, 0.0);
f.field(&filter, "Filter, or type a PR number, branch or commit", view.focused, None);
f.y
};
let list = Rect::new(
body.x,
field_end + (ch * 0.5).round(),
body.w,
(body.bottom() - footer_h - field_end - ch * 0.5).max(0.0),
);
let entry_h = (ch * 2.55).round();
let heading_h = (ch * 1.9).round();
let note_h = |text: &str, cols: usize| wrap(text, cols).len() as f32 * (ch * 1.25).round() + (ch * 0.3).round();
let note_cols = ((list.w - 2.0 * ctx.glyphs.cell_w) / ctx.glyphs.cell_w).floor().max(4.0) as usize;
let mut total = 0.0;
let mut chosen = (0.0, 0.0);
let mut n = 0;
for row in &rows {
let h = match row {
Row::Heading(_) => heading_h,
Row::Note(t) => note_h(t, note_cols),
Row::Entry(_) => {
if n == selected {
chosen = (total, entry_h);
}
n += 1;
entry_h
}
};
total += h;
}
view.max_scroll = (total - list.h).max(0.0);
if view.reveal {
view.scroll = scrolled_to(view.scroll, chosen, list.h, heading_h);
view.reveal = false;
}
view.scroll = view.scroll.clamp(0.0, view.max_scroll);
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, list, view.scroll);
let mut n = 0;
for row in &rows {
match row {
Row::Heading(name) => {
f.put(f.x, f.y + ch * 0.7, &name.to_uppercase(), colors.muted, STYLE_BOLD, f.w);
f.y += heading_h;
}
Row::Note(message) => {
let start = f.y;
f.para(message, colors.muted, 0, f.cw);
f.y = start + note_h(message, note_cols);
}
Row::Entry(entry) => {
let r = Rect::new(f.x, f.y, f.w, entry_h - (3.0 * s).round());
let hover = f.hovered(r);
if n == selected {
let fill = mix(colors.panel, colors.accent, 0.18);
f.framed(r, fill, mix(colors.panel, colors.accent, 0.5), 7.0);
} else if hover {
f.fill(r, colors.raised, 7.0);
}
f.put(r.x + f.cw, r.y + ch * 0.15, &entry.title, colors.fg, 0, r.w - 2.0 * f.cw);
f.put(r.x + f.cw, r.y + ch * 1.25, &entry.detail, colors.muted, 0, r.w - 2.0 * f.cw);
f.hit(r, Click::Choose(n));
f.y += entry_h;
n += 1;
}
}
}
scrollbar(out, list, view.scroll, view.max_scroll, s, colors);
let foot = Rect::new(body.x, body.bottom() - rows_h, body.w, rows_h);
Flow::new(ctx, out, &mut view.hits, view.mouse, foot, 0.0).keys(&hints);
}
fn short(height: f32, cell: f32) -> bool {
height < cell * 22.0
}
fn below(body: Rect, y: f32, h: f32) -> Rect {
Rect::new(body.x, y, body.w, h.min(body.bottom() - y).max(0.0))
}
fn scrolled_to(scroll: f32, (top, height): (f32, f32), h: f32, above: f32) -> f32 {
if top - above < scroll {
(top - above).max(0.0)
} else if top + height > scroll + h {
top + height - h
} else {
scroll
}
}
fn scrollbar(out: &mut Vec<Quad>, area: Rect, scroll: f32, max: f32, s: f32, colors: Colors) {
if max <= 0.0 || area.h <= 0.0 {
return;
}
let thumb = (area.h * area.h / (area.h + max)).max(18.0 * s).min(area.h);
let y = area.y + (scroll / max) * (area.h - thumb);
let r = Rect::new(area.right() + 3.0 * s, y, 3.0 * s, thumb);
out.push(rounded(r, with_alpha(colors.fg, 0.25), 1.5 * s, 0.0, [0.0; 4], crate::render::NO_CLIP));
}
fn draw_menu(ctx: &mut Ctx, view: &mut ReviewView, rect: Rect, out: &mut Vec<Quad>) {
let Screen::Open(o) = &view.screen else { return };
let Some(menu) = &o.menu else { return };
let actions = o.menu_actions();
let (query, selected, mut scroll) = (menu.query.clone(), menu.selected, menu.scroll);
let colors = Colors::new(ctx);
let (cw, ch, s) = (ctx.glyphs.cell_w, ctx.glyphs.cell_h, ctx.scale);
let radius = ctx.config.radius * s;
out.push(rounded(rect, with_alpha(ctx.palette.background, 0.7), radius, 0.0, [0.0; 4], crate::render::NO_CLIP));
view.hits.push((rect, Click::Menu));
let pad = (cw * 1.2).round();
let w = (rect.w - 2.0 * pad).min(cw * 80.0).max(0.0);
let mut moving: Hints = vec![
("\u{2191}\u{2193}", "read on"),
("j k", "jump"),
("\u{2190}\u{2192}", "stage"),
("1-9", "stage by number"),
("PgUp PgDn", "page"),
("Home End", "first, last"),
];
if rect.h < ch * 24.0 {
moving.clear();
}
let inner_w = w - 2.0 * pad;
let moving_h = if moving.is_empty() { 0.0 } else { hint_rows(&moving, inner_w, cw) as f32 * hint_row_height(ch) };
let field_h = (ch * 1.8).round();
let row_h = (ch * 1.55).round();
let heading_h = (ch * 1.6).round();
let fixed = pad * 2.0 + field_h + (ch * 1.3).round() + moving_h + hint_row_height(ch);
let mut places = Vec::new();
let mut total = 0.0;
let mut group = "";
for a in &actions {
if a.group != group {
group = a.group;
total += heading_h;
}
places.push(total);
total += row_h;
}
let top = rect.y + (rect.h * 0.07).max(pad).round();
let room = (rect.bottom() - pad - top - fixed).max(row_h);
let list_h = total.max(row_h).min(room);
let card = Rect::new(rect.x + ((rect.w - w) * 0.5).round(), top, w, (fixed + list_h).min(rect.bottom() - top));
out.push(rounded(
card,
colors.panel,
12.0 * s,
s.max(1.0),
mix(colors.panel, colors.accent, 0.55),
crate::render::NO_CLIP,
));
view.hits.push((card, Click::Inert));
let inner = Rect::new(card.x + pad, card.y + pad, inner_w, card.h - 2.0 * pad);
let list_top = inner.y + field_h + (ch * 0.5).round();
{
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, inner, 0.0);
f.field(&query, "Type to find an action", view.focused, None);
}
let list = Rect::new(inner.x, list_top, inner.w, list_h);
if let Some(&at) = places.get(selected) {
scroll = scrolled_to(scroll, (at, row_h), list.h, heading_h);
}
scroll = scroll.clamp(0.0, (total - list.h).max(0.0));
{
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, list, scroll);
let start = f.y;
if actions.is_empty() {
f.put(f.x + f.cw, f.y + f.ch * 0.25, "Nothing matches", colors.muted, 0, f.w);
}
let mut group = "";
for (i, (a, at)) in actions.iter().zip(&places).enumerate() {
if a.group != group {
group = a.group;
let y = start + at - heading_h + ch * 0.45;
f.put(f.x, y, &group.to_uppercase(), colors.muted, STYLE_BOLD, f.w);
}
let r = Rect::new(f.x, start + at, f.w, row_h - (2.0 * s).round());
if i == selected {
f.fill(r, mix(colors.panel, colors.accent, 0.2), 6.0);
} else if f.hovered(r) {
f.fill(r, colors.raised, 6.0);
}
let ty = r.y + (r.h - ch) * 0.5;
let key_w = a.key.chars().count() as f32 * cw;
if !a.key.is_empty() {
f.put(r.right() - cw - key_w, ty, &a.key, colors.muted, 0, key_w + 1.0);
}
let color = if i == selected { colors.fg } else { colors.soft };
f.put(r.x + cw, ty, &a.label, color, 0, (r.w - key_w - cw * 3.0).max(0.0));
f.hit(r, Click::MenuRow(i));
}
}
scrollbar(out, list, scroll, (total - list.h).max(0.0), s, colors);
let foot =
Rect::new(inner.x, list.bottom() + (ch * 0.4).round(), inner.w, (card.bottom() - list.bottom()).max(0.0));
{
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, foot, 0.0);
f.rule();
f.gap(0.4);
if !moving.is_empty() {
f.keys(&moving);
}
f.keys(&[("enter", "run"), ("esc", "close")]);
}
if let Some(menu) = view.opened().and_then(|o| o.menu.as_mut()) {
menu.scroll = scroll;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn flat(lines: &[Vec<Piece>]) -> Vec<String> {
lines
.iter()
.map(|l| l.iter().map(|(t, code)| if *code { format!("[{t}]") } else { t.clone() }).collect())
.collect()
}
#[test]
fn wraps_words_and_marks_code() {
assert_eq!(flat(&wrap("run `php artisan test` now please", 12)), ["run [php]", "[artisan test]", "now please"]);
assert_eq!(flat(&wrap("a lone ` tick", 40)), ["a lone ` tick"]);
assert_eq!(flat(&wrap("abcdefghij kl", 4)), ["abcd", "efgh", "ij", "kl"]);
assert_eq!(flat(&wrap("", 10)), [""]);
assert_eq!(flat(&wrap("a\x1bb\r\nc", 10)), ["ab c"]);
}
#[test]
fn scrolls_only_as_far_as_needed() {
assert_eq!(scrolled_to(100.0, (150.0, 20.0), 200.0, 10.0), 100.0);
assert_eq!(scrolled_to(100.0, (50.0, 20.0), 200.0, 10.0), 40.0);
assert_eq!(scrolled_to(0.0, (300.0, 20.0), 200.0, 10.0), 120.0);
}
}