Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
120
crates/luxe-tui/src/view/dock/anchors.rs
Normal file
120
crates/luxe-tui/src/view/dock/anchors.rs
Normal file
@@ -0,0 +1,120 @@
|
||||
//! Dock anchors — clickable rows as section-relative indices, rebased onto the panel's middle,
|
||||
//! and where a scrolling list's window sits.
|
||||
|
||||
use super::{row_width, SCROLLBAR_LANE};
|
||||
use crate::app::App;
|
||||
use crate::workspace_dock::{DockList, DockListMetrics};
|
||||
use ratatui::text::Line;
|
||||
|
||||
/// One clickable region of the dock, as a `middle`-line index and the cells it occupies.
|
||||
pub(super) struct DockHit {
|
||||
/// Index into the scrollable middle region.
|
||||
pub(super) line: usize,
|
||||
/// Cells from the content's left edge, or the whole row when absent.
|
||||
///
|
||||
/// A row carrying two affordances (peek and review share one line) needs each to answer for
|
||||
/// its own words; everything else claims the row it is on.
|
||||
pub(super) columns: Option<(u16, u16)>,
|
||||
/// What a click there means.
|
||||
pub(super) target: crate::mouse::MouseTarget,
|
||||
}
|
||||
|
||||
impl DockHit {
|
||||
/// A hit covering a whole row.
|
||||
pub(super) fn row(line: usize, target: crate::mouse::MouseTarget) -> Self {
|
||||
Self { line, columns: None, target }
|
||||
}
|
||||
}
|
||||
|
||||
/// Clickable dock anchors as `middle`-line indices, published as hit regions by `render`.
|
||||
#[derive(Default)]
|
||||
pub(super) struct DockHitAnchors {
|
||||
/// Everything a pointer can act on in the scrollable middle.
|
||||
pub(super) hits: Vec<DockHit>,
|
||||
/// The footer's clickable rows, when telemetry is here: the model (opens the picker) and the
|
||||
/// mode (switches it).
|
||||
pub(super) footer_rows: Vec<(usize, crate::mouse::MouseTarget)>,
|
||||
/// The lists scrolling inside viewports of their own, each with a lane to draw.
|
||||
pub(super) lists: Vec<DockListAnchor>,
|
||||
}
|
||||
|
||||
/// One scrolling list, as `render` needs it to place a lane and say what steers it.
|
||||
///
|
||||
/// Only present while the list has somewhere to go: a lane on a list that fits would claim there
|
||||
/// is more, and the wheel over it belongs to the panel.
|
||||
pub(super) struct DockListAnchor {
|
||||
/// Which list, so a wheel notch or a dragged thumb reaches the right one.
|
||||
pub(super) list: DockList,
|
||||
/// Half-open span of lines the list's rows occupy.
|
||||
pub(super) rows: (usize, usize),
|
||||
/// Where the window sits in the whole list.
|
||||
pub(super) offset: usize,
|
||||
/// Rows in the whole list.
|
||||
pub(super) total: usize,
|
||||
/// Rows of the list the window shows, where a row can wrap and that is fewer than the lines
|
||||
/// the window spans. `None` when every row is one line.
|
||||
pub(super) window: Option<usize>,
|
||||
}
|
||||
|
||||
/// A built dock section: its lines, what a pointer can act on in them, and the list inside it that
|
||||
/// scrolls on its own.
|
||||
///
|
||||
/// Anchors are section-relative until [`DockSection::land`] rebases them onto the middle region.
|
||||
#[derive(Default)]
|
||||
pub(super) struct DockSection {
|
||||
pub(super) lines: Vec<Line<'static>>,
|
||||
pub(super) hits: Vec<DockHit>,
|
||||
pub(super) list: Option<DockListAnchor>,
|
||||
}
|
||||
|
||||
impl DockSection {
|
||||
/// Appends the section to `middle`, rebasing its anchors onto where it landed.
|
||||
pub(super) fn land(self, middle: &mut Vec<Line<'static>>, anchors: &mut DockHitAnchors) {
|
||||
let base = middle.len();
|
||||
anchors
|
||||
.hits
|
||||
.extend(self.hits.into_iter().map(|hit| DockHit { line: base + hit.line, ..hit }));
|
||||
anchors.lists.extend(
|
||||
self.list.map(|list| DockListAnchor {
|
||||
rows: (base + list.rows.0, base + list.rows.1),
|
||||
..list
|
||||
}),
|
||||
);
|
||||
middle.extend(self.lines);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a dock list is drawn from this frame, and the cells its rows have.
|
||||
///
|
||||
/// Publishing what the layout measured is what lets a wheel notch and a dragged thumb move the
|
||||
/// list without re-deriving any of it. `follow` is where the list sits while nobody has taken it
|
||||
/// over — the top for most, the window around the work in hand for PLAN.
|
||||
pub(super) fn list_window(
|
||||
app: &App,
|
||||
list: DockList,
|
||||
total: usize,
|
||||
cap: usize,
|
||||
follow: usize,
|
||||
) -> (usize, usize) {
|
||||
let metrics = DockListMetrics { max: total.saturating_sub(cap), follow };
|
||||
app.set_dock_list_metrics(list, metrics);
|
||||
let lane = if total > cap { SCROLLBAR_LANE } else { 0 };
|
||||
(app.dock.list_scroll(list, metrics), row_width(app).saturating_sub(lane))
|
||||
}
|
||||
|
||||
/// The anchor a list hands `render`, or nothing when it has nowhere to go.
|
||||
pub(super) fn scrolls(
|
||||
list: DockList,
|
||||
rows: (usize, usize),
|
||||
offset: usize,
|
||||
total: usize,
|
||||
cap: usize,
|
||||
) -> Option<DockListAnchor> {
|
||||
(total > cap && rows.1 > rows.0).then_some(DockListAnchor {
|
||||
list,
|
||||
rows,
|
||||
offset,
|
||||
total,
|
||||
window: None,
|
||||
})
|
||||
}
|
||||
160
crates/luxe-tui/src/view/dock/chrome.rs
Normal file
160
crates/luxe-tui/src/view/dock/chrome.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
//! Dock chrome — section headings, status marks and the plain row helpers every section uses.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::theme::styles::Depth;
|
||||
use crate::workspace_dock::DockChanges;
|
||||
use luxe_core::config::StatuslineStyle;
|
||||
use ratatui::{
|
||||
style::Modifier,
|
||||
text::{Line, Span},
|
||||
};
|
||||
|
||||
/// The color-independent lifecycle marker.
|
||||
const fn change_status_marker(status: luxe_core::workspace::FileChangeStatus) -> &'static str {
|
||||
use luxe_core::workspace::FileChangeStatus as Status;
|
||||
match status {
|
||||
Status::Added => "A",
|
||||
Status::Modified => "M",
|
||||
Status::Deleted => "D",
|
||||
Status::Renamed => "R",
|
||||
Status::Untracked => "?",
|
||||
}
|
||||
}
|
||||
|
||||
/// The dock's marker and color for `status`, for another surface that shows a file's Git status
|
||||
/// and must show it the same way.
|
||||
pub(crate) fn status_mark(
|
||||
status: luxe_core::workspace::FileChangeStatus,
|
||||
theme: &crate::theme::styles::ThemeStyles,
|
||||
) -> (&'static str, ratatui::style::Style) {
|
||||
(change_status_marker(status), status_style(status, theme))
|
||||
}
|
||||
|
||||
fn status_style(
|
||||
status: luxe_core::workspace::FileChangeStatus,
|
||||
theme: &crate::theme::styles::ThemeStyles,
|
||||
) -> ratatui::style::Style {
|
||||
use luxe_core::workspace::FileChangeStatus as Status;
|
||||
match status {
|
||||
Status::Added | Status::Untracked => theme.success,
|
||||
Status::Modified => theme.warning,
|
||||
Status::Deleted => theme.error,
|
||||
Status::Renamed => theme.info,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn plural_files(count: usize) -> String {
|
||||
format!("{count} {}", if count == 1 { "file" } else { "files" })
|
||||
}
|
||||
|
||||
/// The whole-worktree total, dimmed under the headline.
|
||||
pub(super) fn change_summary_line(changes: &DockChanges, app: &App) -> Line<'static> {
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
format!("{} in the worktree · ", plural_files(changes.total_files)),
|
||||
app.theme_styles.dim.patch(app.theme_styles.tool_bg),
|
||||
),
|
||||
Span::styled(
|
||||
format!("+{}", change_count(changes.additions)),
|
||||
app.theme_styles.success.patch(app.theme_styles.tool_bg),
|
||||
),
|
||||
Span::styled(
|
||||
format!(" -{}", change_count(changes.deletions)),
|
||||
app.theme_styles.error.patch(app.theme_styles.tool_bg),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn change_count(count: Option<u64>) -> String {
|
||||
count.map_or_else(|| "?".into(), |count| count.to_string())
|
||||
}
|
||||
|
||||
/// A section of the rail, and the surface its heading badge is cut from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Section {
|
||||
Project,
|
||||
Plan,
|
||||
Files,
|
||||
Elsewhere,
|
||||
Model,
|
||||
Session,
|
||||
}
|
||||
|
||||
impl Section {
|
||||
/// The word on the badge.
|
||||
pub(super) const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Project => "PROJECT",
|
||||
Self::Plan => "PLAN",
|
||||
Self::Files => "FILES",
|
||||
Self::Elsewhere => "ELSEWHERE",
|
||||
Self::Model => "MODEL",
|
||||
Self::Session => "SESSION",
|
||||
}
|
||||
}
|
||||
|
||||
/// How far this section's badge has receded from the accent.
|
||||
///
|
||||
/// The bar's rule stood on end. The accent undiluted at both anchors — PROJECT pinned to the top
|
||||
/// of the rail and MODEL pinned to the bottom beside the composer, the same two facts the bar
|
||||
/// anchors itself with — and everything between them receding: the work in flight one step back,
|
||||
/// the ambient accounting two.
|
||||
///
|
||||
/// Depth belongs to the section rather than to where it landed. ELSEWHERE comes and goes with
|
||||
/// the session, so a positional ramp would re-shade the whole rail every time it appeared.
|
||||
const fn depth(self) -> Depth {
|
||||
match self {
|
||||
Self::Project | Self::Model => Depth::Hero,
|
||||
Self::Plan | Self::Files => Depth::Raised,
|
||||
Self::Elsewhere | Self::Session => Depth::Recessed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Heading for a dock section: its label cut into a slab, at the section's own depth.
|
||||
///
|
||||
/// The badge hugs its word rather than spanning the rail. A slab across a whole row already means
|
||||
/// *chosen* everywhere else in the product ([`crate::widgets::selection_row`]), and at forty cells
|
||||
/// the chamfer is a fortieth of the shape and stops reading as one. Its leading edge sits on the
|
||||
/// column its body rows start at, so a section reads as one block.
|
||||
///
|
||||
/// `statusline.style = "flat"` draws the label the way the rail always did — bold accent text on the
|
||||
/// panel — because the shape is one look across both forms of this surface.
|
||||
pub(super) fn section_heading_line(section: Section, app: &App) -> Line<'static> {
|
||||
Line::from(heading_spans(section, app))
|
||||
}
|
||||
|
||||
/// A heading with `trailing` riding bare beside the badge.
|
||||
///
|
||||
/// The badge stays one word on every section, so the run of them down the rail reads as structure;
|
||||
/// what the heading summarizes follows it on the canvas. Same division the bar makes between a
|
||||
/// module's pill and the strings that ride bare on it.
|
||||
pub(super) fn section_heading_with(section: Section, trailing: String, app: &App) -> Line<'static> {
|
||||
let styles = &app.theme_styles;
|
||||
let mut spans = heading_spans(section, app);
|
||||
spans.push(Span::styled(format!(" {trailing}"), styles.muted.patch(styles.tool_bg)));
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
pub(super) fn heading_spans(section: Section, app: &App) -> Vec<Span<'static>> {
|
||||
let styles = &app.theme_styles;
|
||||
if app.config.statusline.style() == StatuslineStyle::Flat {
|
||||
return vec![Span::styled(
|
||||
section.label(),
|
||||
styles.accent.add_modifier(Modifier::BOLD).patch(styles.tool_bg),
|
||||
)];
|
||||
}
|
||||
let canvas = styles.tool_bg.bg.unwrap_or(styles.slab.canvas);
|
||||
crate::widgets::badge(section.label(), section.depth(), canvas, styles)
|
||||
}
|
||||
|
||||
pub(super) fn text_line(text: String, app: &App) -> Line<'static> {
|
||||
Line::from(vec![Span::styled(text, app.theme_styles.text.patch(app.theme_styles.tool_bg))])
|
||||
}
|
||||
|
||||
pub(super) fn muted_line(text: impl Into<String>, app: &App) -> Line<'static> {
|
||||
Line::from(vec![Span::styled(
|
||||
text.into(),
|
||||
app.theme_styles.muted.patch(app.theme_styles.tool_bg),
|
||||
)])
|
||||
}
|
||||
324
crates/luxe-tui/src/view/dock/elsewhere.rs
Normal file
324
crates/luxe-tui/src/view/dock/elsewhere.rs
Normal file
@@ -0,0 +1,324 @@
|
||||
//! Dock elsewhere — the ELSEWHERE section: changes outside the project, by place and folded.
|
||||
|
||||
use super::anchors::{list_window, scrolls, DockHit, DockSection};
|
||||
use super::chrome::{plural_files, section_heading_line, Section};
|
||||
use super::tree::{change_cells, tree_line, TreeCells, TreeLead};
|
||||
use crate::app::App;
|
||||
use crate::glyphs::{icon_label, Icon};
|
||||
use crate::widgets::truncate_end as truncate_cells;
|
||||
use crate::workspace_dock::{DockChangeRow, DockExternal, DockExternalGroup, DockList};
|
||||
use ratatui::{
|
||||
style::Modifier,
|
||||
text::{Line, Span},
|
||||
};
|
||||
|
||||
/// Rows the ELSEWHERE list may spend before it starts to scroll.
|
||||
///
|
||||
/// A flat budget rather than the leftover height FILES claims: this section is a *pointer* to
|
||||
/// work done somewhere else, and two elastic sections on one rail would each be sized by the
|
||||
/// other. What keeps it complete at that size is the scrollbar — every place and every file under
|
||||
/// it is a wheel notch away, so nothing needs a display cap.
|
||||
const EXTERNAL_ROWS_MAX: usize = 6;
|
||||
|
||||
/// Floor for that budget on a short rail, so the section is a small viewport rather than none.
|
||||
const EXTERNAL_ROWS_MIN: usize = 3;
|
||||
|
||||
/// Rows ELSEWHERE may spend on a dock of `available_height`.
|
||||
pub(super) fn external_row_cap(available_height: usize) -> usize {
|
||||
EXTERNAL_ROWS_MAX.min(available_height / 4).max(EXTERNAL_ROWS_MIN)
|
||||
}
|
||||
|
||||
/// The ELSEWHERE section: what this session changed outside the project.
|
||||
///
|
||||
/// Deliberately without a review affordance, unlike FILES. A review is built from the project's
|
||||
/// Git worktree and its chapters end in commits to it, so offering to open one over a file that
|
||||
/// lives somewhere else would promise something the review cannot do.
|
||||
///
|
||||
/// A *peek* is a different promise and one this section can keep, so its file rows are clickable
|
||||
/// exactly like the project's: another worktree answers the same `git diff` the project does, and
|
||||
/// a file in no repository is measured against the copy the session retained before it wrote
|
||||
/// there. A row drawn in the project's own hand that did nothing would teach a reader that a file
|
||||
/// name only sometimes opens its change.
|
||||
///
|
||||
/// What keeps it from growing without end is that it *recedes*: a file that has been looked at
|
||||
/// dims, a place whose files have all been looked at folds to its one heading, and a click on any
|
||||
/// heading folds or unfolds it by hand. Nothing is hidden that has not been seen, and a place the
|
||||
/// agent touches again comes back. The rest is a viewport: the list keeps a bounded height and
|
||||
/// scrolls, so a place three deep in the session is reachable rather than counted.
|
||||
pub(super) fn external_lines(external: &DockExternal, app: &App, row_cap: usize) -> DockSection {
|
||||
let mut lines = vec![Line::default(), section_heading_line(Section::Elsewhere, app)];
|
||||
let mut hits = Vec::new();
|
||||
lines.push(external_headline(external, app));
|
||||
|
||||
let all = external_rows(external, app);
|
||||
let cap = row_cap.max(1);
|
||||
let (offset, width) = list_window(app, DockList::Elsewhere, all.len(), cap, 0);
|
||||
|
||||
let start = lines.len();
|
||||
// A window that opens under a heading repeats it, or its first rows sit under nothing at all.
|
||||
for index in external_context(&all, offset) {
|
||||
external_row_line(&all[index], width, app, &mut lines, &mut hits);
|
||||
}
|
||||
let mut drawn = 0usize;
|
||||
for row in all.iter().skip(offset).take(cap.saturating_sub(lines.len() - start)) {
|
||||
external_row_line(row, width, app, &mut lines, &mut hits);
|
||||
drawn += 1;
|
||||
}
|
||||
// A window ending on a heading promises rows that are not under it, and this list nests twice,
|
||||
// so a place and the folder under it can both land at the end. A *folded* place is whole on its
|
||||
// own — its count is the row — so only open headings are dropped.
|
||||
while drawn > 0 && all[offset + drawn - 1].is_open_heading() {
|
||||
if matches!(all[offset + drawn - 1], ExternalRow::Place { .. }) {
|
||||
hits.pop();
|
||||
}
|
||||
lines.pop();
|
||||
drawn -= 1;
|
||||
}
|
||||
let end = lines.len();
|
||||
|
||||
DockSection {
|
||||
lines,
|
||||
hits,
|
||||
list: scrolls(DockList::Elsewhere, (start, end), offset, all.len(), cap),
|
||||
}
|
||||
}
|
||||
|
||||
/// One row of the ELSEWHERE list, flat so a window into it is a `skip` and a `take`.
|
||||
pub(super) enum ExternalRow<'a> {
|
||||
/// A place, and whether it is showing its heading alone.
|
||||
Place { group: &'a DockExternalGroup, folded: bool },
|
||||
/// A directory heading or a file, under the place above it.
|
||||
Under { group: &'a DockExternalGroup, row: DockChangeRow },
|
||||
}
|
||||
|
||||
impl ExternalRow<'_> {
|
||||
/// Whether this row is a heading with rows owed underneath it.
|
||||
fn is_open_heading(&self) -> bool {
|
||||
match self {
|
||||
Self::Place { folded, .. } => !folded,
|
||||
Self::Under { row, .. } => matches!(row, DockChangeRow::Directory(_)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every place and everything under it, in the order the rail draws them.
|
||||
///
|
||||
/// Each place's files are grouped by directory through the same directory reduction the changes have always had, so a
|
||||
/// folder reads the same on both. Files at a place's own root get no heading: the place above them
|
||||
/// already is their directory, and a `/ (root)` row under it would say nothing twice.
|
||||
pub(super) fn external_rows<'a>(external: &'a DockExternal, app: &App) -> Vec<ExternalRow<'a>> {
|
||||
let mut rows = Vec::new();
|
||||
for group in &external.groups {
|
||||
let seen: Vec<bool> = group.files.iter().map(|file| peeked(app, group, file)).collect();
|
||||
let folded = folded(app, group, &seen);
|
||||
rows.push(ExternalRow::Place { group, folded });
|
||||
if folded {
|
||||
continue;
|
||||
}
|
||||
rows.extend(
|
||||
crate::workspace_dock::change_rows(&group.files, |file| peeked(app, group, file))
|
||||
.into_iter()
|
||||
.filter(|row| !matches!(row, DockChangeRow::Directory(at) if at.directory == "."))
|
||||
.map(|row| ExternalRow::Under { group, row }),
|
||||
);
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// The headings a window opening at `offset` must repeat, as indices into `rows`.
|
||||
///
|
||||
/// Up to two, because the list nests twice: the place, and the directory inside it. A window that
|
||||
/// opens on a heading of its own needs neither.
|
||||
pub(super) fn external_context(rows: &[ExternalRow<'_>], offset: usize) -> Vec<usize> {
|
||||
let nested = match rows.get(offset) {
|
||||
Some(ExternalRow::Place { .. }) | None => return Vec::new(),
|
||||
Some(ExternalRow::Under { row, .. }) => {
|
||||
matches!(row, DockChangeRow::File { path, .. } if path.contains('/'))
|
||||
}
|
||||
};
|
||||
let place = rows[..offset].iter().rposition(|row| matches!(row, ExternalRow::Place { .. }));
|
||||
let mut context: Vec<usize> = place.into_iter().collect();
|
||||
if nested {
|
||||
let directory = rows[..offset].iter().rposition(|row| {
|
||||
matches!(row, ExternalRow::Under { row, .. } if matches!(row, DockChangeRow::Directory(_)))
|
||||
});
|
||||
context.extend(directory.filter(|index| Some(*index) > place));
|
||||
}
|
||||
context
|
||||
}
|
||||
|
||||
/// Draws one ELSEWHERE row, recording what a click on it means.
|
||||
///
|
||||
/// Drawn by the same hand as FILES' tree, since the two usually sit one above the other: a place is
|
||||
/// a folder row, its directories nest under it, and a file wears its language's mark, a name in
|
||||
/// its git color, and its ± and status letter on the right. What a place says on the right is
|
||||
/// its own: the branch while it is open, and the count it is holding back once folded.
|
||||
fn external_row_line(
|
||||
row: &ExternalRow<'_>,
|
||||
width: usize,
|
||||
app: &App,
|
||||
lines: &mut Vec<Line<'static>>,
|
||||
hits: &mut Vec<DockHit>,
|
||||
) {
|
||||
let styles = &app.theme_styles;
|
||||
match row {
|
||||
ExternalRow::Place { group, folded } => {
|
||||
hits.push(DockHit::row(
|
||||
lines.len(),
|
||||
crate::mouse::MouseTarget::DockExternalPlace(fold_key(group)),
|
||||
));
|
||||
let hovered = matches!(
|
||||
app.pointer.hover.as_ref(),
|
||||
Some(crate::mouse::MouseTarget::DockExternalPlace(place)) if *place == fold_key(group)
|
||||
);
|
||||
lines.push(tree_line(place_cells(group, *folded, width, app), width, hovered, app));
|
||||
}
|
||||
ExternalRow::Under { row: DockChangeRow::Directory(at), .. } => {
|
||||
let cells = TreeCells {
|
||||
depth: 1,
|
||||
lead: TreeLead::Folder { open: true },
|
||||
name: at.directory.clone(),
|
||||
// A directory whose files have all been looked at recedes
|
||||
name_style: match at.reviewed {
|
||||
true => styles.dim,
|
||||
false => styles.text.add_modifier(Modifier::BOLD),
|
||||
},
|
||||
right: Vec::new(),
|
||||
};
|
||||
lines.push(tree_line(cells, width, false, app));
|
||||
}
|
||||
ExternalRow::Under {
|
||||
group,
|
||||
row: DockChangeRow::File { name, path, status, additions, deletions, reviewed },
|
||||
} => {
|
||||
let peek = group.peek(path);
|
||||
hits.push(DockHit::row(
|
||||
lines.len(),
|
||||
crate::mouse::MouseTarget::DockChangeFile(peek.clone()),
|
||||
));
|
||||
let hovered = matches!(
|
||||
app.pointer.hover.as_ref(),
|
||||
Some(crate::mouse::MouseTarget::DockChangeFile(hovered)) if *hovered == peek
|
||||
);
|
||||
let showing = app.changes.as_ref().is_some_and(|view| view.path == peek);
|
||||
let (name_style, right) =
|
||||
change_cells(*status, *additions, *deletions, *reviewed, styles);
|
||||
let cells = TreeCells {
|
||||
// A file at the place's own root sits directly under it; one in a folder sits under
|
||||
// that folder's heading
|
||||
depth: if path.contains('/') { 2 } else { 1 },
|
||||
lead: TreeLead::File { name, faint: false },
|
||||
name: name.clone(),
|
||||
name_style: match showing {
|
||||
true => styles.accent.add_modifier(Modifier::BOLD),
|
||||
false => name_style,
|
||||
},
|
||||
right,
|
||||
};
|
||||
lines.push(tree_line(cells, width, hovered, app));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One place: where it is, and on the right the branch when it is a checkout, or the count it is
|
||||
/// holding back while folded.
|
||||
///
|
||||
/// The branch is not decoration here. A worktree's row lists everything Git reports there,
|
||||
/// including changes this session did not make, and naming the branch is what tells a reader they
|
||||
/// are looking at another repository's whole working tree rather than at a list of Luxe's edits.
|
||||
/// A folded place trades it for the count, which is what a heading standing alone has to say, and
|
||||
/// recedes, since folded reads as dealt with. A branch never takes more than a third of the row:
|
||||
/// the place is what the row is for.
|
||||
fn place_cells<'a>(
|
||||
group: &DockExternalGroup,
|
||||
folded: bool,
|
||||
width: usize,
|
||||
app: &App,
|
||||
) -> TreeCells<'a> {
|
||||
let styles = &app.theme_styles;
|
||||
let branch = group.branch.as_deref().unwrap_or_default();
|
||||
let files = group.files.len() + group.remaining.unwrap_or(0);
|
||||
let right = match (folded, group.git && !branch.is_empty()) {
|
||||
(true, _) => vec![(format!(" {}", plural_files(files)), styles.dim)],
|
||||
(false, true) => vec![(
|
||||
format!(
|
||||
" {}",
|
||||
icon_label(Icon::Branch.glyph(), &truncate_cells(branch, (width / 3).max(6)))
|
||||
),
|
||||
styles.dim,
|
||||
)],
|
||||
(false, false) => Vec::new(),
|
||||
};
|
||||
TreeCells {
|
||||
depth: 0,
|
||||
lead: TreeLead::Folder { open: !folded },
|
||||
name: group.location.clone(),
|
||||
name_style: match folded {
|
||||
true => styles.dim,
|
||||
false => styles.text.add_modifier(Modifier::BOLD),
|
||||
},
|
||||
right,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a place's fold state is filed under — where it is, which is what the reader clicked.
|
||||
fn fold_key(group: &DockExternalGroup) -> String {
|
||||
luxe_core::paths::display(&group.root)
|
||||
}
|
||||
|
||||
/// Whether this file is unchanged since the reader last looked at it.
|
||||
///
|
||||
/// The ± has to match too: a file touched again since is new work, whatever was read before. Same
|
||||
/// rule [`DockChanges::unreviewed`] applies to the project, for the same reason.
|
||||
fn peeked(
|
||||
app: &App,
|
||||
group: &DockExternalGroup,
|
||||
file: &crate::workspace_dock::DockChangeItem,
|
||||
) -> bool {
|
||||
app.external_seen.get(&group.peek_path(file))
|
||||
== Some(&(file.additions.unwrap_or_default(), file.deletions.unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Whether the ELSEWHERE place filed under `place` is showing its heading alone right now.
|
||||
///
|
||||
/// The renderer owns the rule, so a click that toggles it asks here rather than keeping a second
|
||||
/// copy that could disagree with what is on screen.
|
||||
pub(crate) fn external_place_folded(app: &App, place: &str) -> bool {
|
||||
let Some(external) = app.workspace.as_ref().and_then(DockExternal::from_snapshot) else {
|
||||
return false;
|
||||
};
|
||||
let Some(group) = external.groups.iter().find(|group| fold_key(group) == place) else {
|
||||
return false;
|
||||
};
|
||||
let seen: Vec<bool> = group.files.iter().map(|file| peeked(app, group, file)).collect();
|
||||
folded(app, group, &seen)
|
||||
}
|
||||
|
||||
/// Whether a place shows its heading alone: because the reader said so, or because there is
|
||||
/// nothing under it they have not already seen.
|
||||
///
|
||||
/// The automatic half waits while the pane is showing one of its files. Peeking a place's last
|
||||
/// unread file marks it seen, and folding on that would take the row out from under the reader in
|
||||
/// the same frame their click opened it. An explicit choice still wins either way — a fold the
|
||||
/// reader asked for is not a state to be second-guessed.
|
||||
fn folded(app: &App, group: &DockExternalGroup, seen: &[bool]) -> bool {
|
||||
if let Some(chosen) = app.external_folds.get(&fold_key(group)) {
|
||||
return *chosen;
|
||||
}
|
||||
let showing = app
|
||||
.changes
|
||||
.as_ref()
|
||||
.is_some_and(|view| group.files.iter().any(|file| group.peek_path(file) == view.path));
|
||||
!showing && !seen.is_empty() && seen.iter().all(|seen| *seen)
|
||||
}
|
||||
|
||||
/// `3 files outside this project`. No ± total: every file row below carries its own, and a sum
|
||||
/// over places that may be whole other worktrees says less than the rows it would repeat.
|
||||
fn external_headline(external: &DockExternal, app: &App) -> Line<'static> {
|
||||
let styles = &app.theme_styles;
|
||||
let files = external.total_files;
|
||||
Line::from(Span::styled(
|
||||
format!("{files} file{} outside this project", if files == 1 { "" } else { "s" }),
|
||||
styles.text.patch(styles.tool_bg),
|
||||
))
|
||||
}
|
||||
372
crates/luxe-tui/src/view/dock/files.rs
Normal file
372
crates/luxe-tui/src/view/dock/files.rs
Normal file
@@ -0,0 +1,372 @@
|
||||
//! Dock files — the FILES section: its heading, filter, tree viewport and the ways into the change.
|
||||
|
||||
use super::anchors::{list_window, scrolls, DockHit, DockSection};
|
||||
use super::chrome::{change_summary_line, heading_spans, muted_line, Section};
|
||||
use super::plan::PLAN_LOOKAHEAD;
|
||||
use super::row_width;
|
||||
use super::tree::{tree_row_line, tree_row_target};
|
||||
use crate::app::App;
|
||||
use crate::files::{TreeFilter, TreeRow};
|
||||
use crate::workspace_dock::{DockChangeItem, DockChanges, DockList};
|
||||
use ratatui::{
|
||||
style::Modifier,
|
||||
text::{Line, Span},
|
||||
};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
/// Fixed rows FILES spends whatever the tree holds: a leading blank, the heading, a headline, and
|
||||
/// the row of ways into the change under the tree.
|
||||
pub(super) const FILES_FIXED_ROWS: usize = 4;
|
||||
|
||||
/// Floor for the tree's viewport, so FILES does not vanish on a crowded rail.
|
||||
///
|
||||
/// The tree is a viewport onto the whole project, so a budget of nothing would not be a smaller
|
||||
/// section but an unreachable one. On a tall dock with a long plan and a list of places beside it
|
||||
/// the leftover height can be zero, and the answer is to keep a few rows and let the panel's own
|
||||
/// scroll reach what sits below.
|
||||
pub(super) const FILE_ROWS_MIN: usize = 5;
|
||||
|
||||
/// How many tree rows FILES may show: everything the other sections and its own fixed rows leave.
|
||||
///
|
||||
/// No ceiling, unlike the CHANGES list it replaced. A list of changes had a natural length and a
|
||||
/// tall dock spent on it was wasted; a tree has the whole project behind it, and the rail's spare
|
||||
/// height is exactly what browsing it wants.
|
||||
pub(super) fn files_row_cap(available_height: usize, reserved: usize) -> usize {
|
||||
// The floor scales down with the panel so a very short dock still spends most of itself on the
|
||||
// other sections; above that it is a flat few rows, whatever else is competing.
|
||||
let floor = FILE_ROWS_MIN.min(available_height / 4);
|
||||
available_height.saturating_sub(reserved + FILES_FIXED_ROWS).max(floor)
|
||||
}
|
||||
|
||||
/// What FILES says after the work left the working tree, or nothing when it never was there.
|
||||
///
|
||||
/// An empty diff against `HEAD` has two causes that look identical in a snapshot and mean opposite
|
||||
/// things: nothing has happened yet, or it was committed. Saying nothing about the second is how a
|
||||
/// reader loses a review they were about to open — the counts and the markers all disappear at
|
||||
/// once, with nothing left saying there was anything to see.
|
||||
///
|
||||
/// The turn's own baseline outlives the commit (Luxe retains the before and after content on disk,
|
||||
/// not a Git range), so the way in is still open; only the sign of it was missing.
|
||||
fn committed_notice(app: &App) -> Option<Vec<Line<'static>>> {
|
||||
if !app.worktree_emptied || app.review.last_turn.is_none() {
|
||||
return None;
|
||||
}
|
||||
Some(vec![
|
||||
Line::from(Span::styled(
|
||||
"committed — nothing in the working tree".to_string(),
|
||||
app.theme_styles.text.patch(app.theme_styles.tool_bg),
|
||||
)),
|
||||
muted_line("the last turn is still reviewable", app),
|
||||
])
|
||||
}
|
||||
|
||||
/// The FILES section: the project as a tree, with what changed marked in it.
|
||||
///
|
||||
/// It took CHANGES' place and kept its job. Folders on the way to a changed file start open, the
|
||||
/// headline counts the change (against the last review, when there was one), and the two ways into
|
||||
/// the change stay on the row under the tree. What is new is everything else: the rest of the
|
||||
/// project is a click away rather than a terminal away. Every row is a window over the whole
|
||||
/// tree, scrolling in a viewport of its own like the lists around it, and the scope switch on the
|
||||
/// heading narrows it to the changes alone.
|
||||
pub(super) fn file_lines(changes: Option<&DockChanges>, app: &App, row_cap: usize) -> DockSection {
|
||||
let items: &[DockChangeItem] = changes.map_or(&[], |changes| changes.files.as_slice());
|
||||
let seen = app.review.seen.as_ref();
|
||||
let (heading, scope) = files_heading_line(changes, app);
|
||||
let mut lines = vec![Line::default(), heading];
|
||||
let mut hits = vec![scope];
|
||||
if let Some(changes) = changes.filter(|_| seen.is_some()) {
|
||||
lines.push(change_summary_line(changes, app));
|
||||
}
|
||||
let committed = committed_notice(app);
|
||||
let reviewable = committed.is_some();
|
||||
lines.extend(committed.into_iter().flatten());
|
||||
let filter = app.files.filter.as_ref().map(|filter| filter_line(filter, items, app));
|
||||
// the filter's own row comes out of the tree's, so the section keeps its height
|
||||
let row_cap = row_cap.saturating_sub(usize::from(filter.is_some()));
|
||||
lines.extend(filter);
|
||||
|
||||
let rows = app.files.rows(items);
|
||||
let matched = app.files.hits(items);
|
||||
let cap = row_cap.max(1);
|
||||
let open = app.changes.as_ref().map(|view| view.path.as_str());
|
||||
let focus = app.files.cursor.as_deref().or(open);
|
||||
let follow = focus
|
||||
.and_then(|path| rows.iter().position(|row| row.path() == Some(path)))
|
||||
.map_or(0, |at| (at + 1 + PLAN_LOOKAHEAD).saturating_sub(cap));
|
||||
let (offset, width) = list_window(app, DockList::Files, rows.len(), cap, follow);
|
||||
|
||||
let start = lines.len();
|
||||
for row in rows.iter().skip(offset).take(cap) {
|
||||
if let Some(target) = tree_row_target(row) {
|
||||
hits.push(DockHit::row(lines.len(), target));
|
||||
}
|
||||
let mut line = tree_row_line(row, width, open, seen, app);
|
||||
if let Some(positions) = row.path().and_then(|path| matched.positions.get(path)) {
|
||||
light_matches(&mut line, row, positions, app);
|
||||
}
|
||||
lines.push(line);
|
||||
}
|
||||
if rows.is_empty() && app.files.changed_only {
|
||||
lines.push(muted_line("nothing has changed", app));
|
||||
}
|
||||
let end = lines.len();
|
||||
|
||||
// While the keyboard is in the tree, the keys it answers to; otherwise the ways into the
|
||||
// change, and the way to move through the tree without the mouse
|
||||
if app.files.focused {
|
||||
let keys = match app.files.filter.as_ref() {
|
||||
Some(filter) if filter.typing => "↑ ↓ move · enter open · esc clear",
|
||||
Some(_) => "j k move · / edit · esc clear",
|
||||
None => "j k move · l open · / filter · esc back",
|
||||
};
|
||||
lines.push(muted_line(keys, app));
|
||||
}
|
||||
let mut hints = match (app.files.focused, changes.is_some(), reviewable) {
|
||||
(true, ..) => Vec::new(),
|
||||
(false, true, _) => change_hints(app),
|
||||
(false, false, true) => review_hint(app),
|
||||
(false, false, false) => Vec::new(),
|
||||
};
|
||||
if !app.files.focused {
|
||||
// First, so a rail too narrow for every hint gives it up before the ways into the change;
|
||||
// the preview's footer and the key card say it too
|
||||
hints.insert(0, browse_hint(app));
|
||||
}
|
||||
if !hints.is_empty() {
|
||||
let (row, spans) = hint_line(&hints, lines.len(), app);
|
||||
hits.extend(spans);
|
||||
lines.push(row);
|
||||
}
|
||||
DockSection {
|
||||
lines,
|
||||
hits,
|
||||
list: scrolls(DockList::Files, (start, end), offset, rows.len(), cap),
|
||||
}
|
||||
}
|
||||
|
||||
/// `FILES 4 changed +335 −29 all ▾` — the heading, what changed, and what is showing.
|
||||
///
|
||||
/// The scope switch rides the heading's right edge, where a reader looks for a list's filter, and
|
||||
/// answers for its own cells, so the rest of the heading stays a heading.
|
||||
fn files_heading_line(changes: Option<&DockChanges>, app: &App) -> (Line<'static>, DockHit) {
|
||||
let styles = &app.theme_styles;
|
||||
let mut spans = heading_spans(Section::Files, app);
|
||||
if let Some(changes) = changes {
|
||||
let seen = app.review.seen.as_ref();
|
||||
let unreviewed = changes.unreviewed(seen);
|
||||
let (text, style) = match seen.is_some() {
|
||||
false => (format!(" {} changed", changes.total_files), styles.text),
|
||||
true if unreviewed == 0 => (" all reviewed".to_string(), styles.success),
|
||||
true => (format!(" {unreviewed} new since your review"), styles.text),
|
||||
};
|
||||
spans.push(Span::styled(text, style.patch(styles.tool_bg)));
|
||||
// Totals git could not count are left out rather than printed as `?`
|
||||
if let (None, Some(additions), Some(deletions)) =
|
||||
(seen, changes.additions, changes.deletions)
|
||||
{
|
||||
spans
|
||||
.push(Span::styled(format!(" +{additions}"), styles.success.patch(styles.tool_bg)));
|
||||
spans.push(Span::styled(format!(" −{deletions}"), styles.error.patch(styles.tool_bg)));
|
||||
}
|
||||
}
|
||||
let scope = match (app.files.changed_only, app.files.show_ignored) {
|
||||
(true, _) => "changed ▾",
|
||||
(false, false) => "all ▾",
|
||||
(false, true) => "all + ignored ▾",
|
||||
};
|
||||
let used: usize = spans.iter().map(|span| span.content.width()).sum();
|
||||
let width = row_width(app);
|
||||
let column = width.saturating_sub(scope.width()).max(used + 1);
|
||||
spans.push(Span::styled(" ".repeat(column - used), styles.muted.patch(styles.tool_bg)));
|
||||
let target = crate::mouse::MouseTarget::DockFilesScope;
|
||||
let ink = match app.pointer.hover.as_ref() == Some(&target) {
|
||||
true => styles.text.patch(styles.tool_bg).patch(styles.selected_bg),
|
||||
false => styles.muted.patch(styles.tool_bg),
|
||||
};
|
||||
spans.push(Span::styled(scope, ink));
|
||||
let hit = DockHit {
|
||||
line: 1,
|
||||
columns: Some((
|
||||
u16::try_from(column).unwrap_or(u16::MAX),
|
||||
u16::try_from(scope.width()).unwrap_or(u16::MAX),
|
||||
)),
|
||||
target,
|
||||
};
|
||||
(Line::from(spans), hit)
|
||||
}
|
||||
|
||||
/// `/ dock▏ 12 of 340` — what the tree is filtered by, and how much it matched.
|
||||
fn filter_line(filter: &TreeFilter, items: &[DockChangeItem], app: &App) -> Line<'static> {
|
||||
let styles = &app.theme_styles;
|
||||
let ink = |style: ratatui::style::Style| style.patch(styles.tool_bg);
|
||||
let mut spans = vec![
|
||||
Span::styled("/ ", ink(styles.accent)),
|
||||
Span::styled(filter.query.clone(), ink(styles.text.add_modifier(Modifier::BOLD))),
|
||||
];
|
||||
if filter.typing {
|
||||
spans.push(Span::styled("▏", ink(styles.accent)));
|
||||
}
|
||||
let count = match app.files.filtering() {
|
||||
Some(_) => {
|
||||
let hits = app.files.hits(items);
|
||||
match hits.total {
|
||||
0 => "none".to_string(),
|
||||
total if total > crate::files::filter::SHOWN => {
|
||||
format!("{} of {total}", crate::files::filter::SHOWN)
|
||||
}
|
||||
total => format!("{total}"),
|
||||
}
|
||||
}
|
||||
None => "type to filter".to_string(),
|
||||
};
|
||||
let used: usize = spans.iter().map(|span| span.content.width()).sum();
|
||||
let width = row_width(app);
|
||||
let pad = width.saturating_sub(used + count.width()).max(1);
|
||||
spans.push(Span::styled(" ".repeat(pad), ink(styles.muted)));
|
||||
spans.push(Span::styled(count, ink(styles.muted)));
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
/// Lights the characters of a row's name that the filter matched.
|
||||
///
|
||||
/// The positions are in the row's whole path and the name is its tail, so they shift by what comes
|
||||
/// before it. A name elided to fit is left unlit, since its characters no longer sit where the
|
||||
/// positions say.
|
||||
fn light_matches(line: &mut Line<'static>, row: &TreeRow, positions: &[usize], app: &App) {
|
||||
let (Some(path), TreeRow::Folder { name, .. } | TreeRow::File { name, .. }) = (row.path(), row)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(at) = line.spans.iter().position(|span| span.content == name.as_str()) else {
|
||||
return;
|
||||
};
|
||||
let offset = path.chars().count() - name.chars().count();
|
||||
let lit: std::collections::HashSet<usize> =
|
||||
positions.iter().filter_map(|position| position.checked_sub(offset)).collect();
|
||||
let base = line.spans[at].style;
|
||||
let matched = base.patch(app.theme_styles.accent).add_modifier(Modifier::BOLD);
|
||||
let mut pieces: Vec<Span<'static>> = Vec::new();
|
||||
for (index, character) in name.chars().enumerate() {
|
||||
let style = if lit.contains(&index) { matched } else { base };
|
||||
match pieces.last_mut() {
|
||||
Some(last) if last.style == style => last.content.to_mut().push(character),
|
||||
_ => pieces.push(Span::styled(character.to_string(), style)),
|
||||
}
|
||||
}
|
||||
line.spans.splice(at..=at, pieces);
|
||||
}
|
||||
|
||||
/// Cells between two hints on the same row.
|
||||
const HINT_SEPARATOR: &str = " · ";
|
||||
|
||||
/// One way into the change, and the words that offer it.
|
||||
pub(super) struct ChangeHint {
|
||||
/// `Ctrl+P peek`.
|
||||
pub(super) text: String,
|
||||
/// What a click on those words does.
|
||||
pub(super) target: crate::mouse::MouseTarget,
|
||||
}
|
||||
|
||||
/// The two ways into the change: a glance at one file, and the review of all of them.
|
||||
///
|
||||
/// Both were always here — every file row above is already a peek away — but only the review said
|
||||
/// so, which left the cheaper of the two answers a secret. Chords are read back from the live
|
||||
/// keymap rather than typed in, so a remapped binding cannot leave the dock advertising a key that
|
||||
/// does nothing; the slash command is the fallback when an action is unbound.
|
||||
///
|
||||
/// A chord and the verb it performs, which is the shape every other footer in the product uses
|
||||
/// (`Space next`, `Esc close`, `Alt+W no wrap`), and on a forty-cell rail no word is free.
|
||||
pub(super) fn change_hints(app: &App) -> Vec<ChangeHint> {
|
||||
use luxe_core::keymap::UiAction;
|
||||
let chord = |action, fallback: &str| {
|
||||
app.keymap
|
||||
.chords_for(action)
|
||||
.and_then(|chords| chords.first())
|
||||
.map_or_else(|| fallback.to_string(), ToString::to_string)
|
||||
};
|
||||
vec![
|
||||
ChangeHint {
|
||||
text: format!("{} preview", chord(UiAction::ToggleChanges, "/preview")),
|
||||
target: crate::mouse::MouseTarget::DockPeekChanges,
|
||||
},
|
||||
ChangeHint {
|
||||
text: format!("{} review", chord(UiAction::ReviewOpen, "/diff")),
|
||||
target: crate::mouse::MouseTarget::DockReviewChanges,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// `Ctrl+T browse` — the way into the tree from the keyboard.
|
||||
fn browse_hint(app: &App) -> ChangeHint {
|
||||
let chord = app
|
||||
.keymap
|
||||
.chords_for(luxe_core::keymap::UiAction::FocusFiles)
|
||||
.and_then(|chords| chords.first())
|
||||
.map_or_else(|| "ctrl+t".to_string(), ToString::to_string);
|
||||
ChangeHint {
|
||||
text: format!("{chord} browse"),
|
||||
target: crate::mouse::MouseTarget::DockFocusFiles,
|
||||
}
|
||||
}
|
||||
|
||||
/// The review hint on its own, for a change that has already left the working tree.
|
||||
fn review_hint(app: &App) -> Vec<ChangeHint> {
|
||||
change_hints(app)
|
||||
.into_iter()
|
||||
.filter(|hint| hint.target == crate::mouse::MouseTarget::DockReviewChanges)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `Ctrl+P peek · Ctrl+G review` — the hints on one row, with the columns each one owns.
|
||||
///
|
||||
/// Hints are dropped from the front until the row fits the rail, so the row never wraps: a wrapped
|
||||
/// hint puts its second half where the click regions no longer point, and the one that survives is
|
||||
/// the review — the only one of the two a reader cannot reach by clicking a file name above it.
|
||||
///
|
||||
/// Each hint highlights under the pointer on its own, the way the Changes pane's footer does, so a
|
||||
/// row offering two things says which of them is about to happen.
|
||||
pub(super) fn hint_line(
|
||||
hints: &[ChangeHint],
|
||||
line: usize,
|
||||
app: &App,
|
||||
) -> (Line<'static>, Vec<DockHit>) {
|
||||
let styles = &app.theme_styles;
|
||||
let width = row_width(app);
|
||||
let rendered = |hints: &[ChangeHint]| {
|
||||
hints.iter().map(|hint| hint.text.chars().count()).sum::<usize>()
|
||||
+ HINT_SEPARATOR.chars().count() * hints.len().saturating_sub(1)
|
||||
};
|
||||
let mut shown = hints;
|
||||
while shown.len() > 1 && rendered(shown) > width {
|
||||
shown = &shown[1..];
|
||||
}
|
||||
|
||||
let mut spans = Vec::new();
|
||||
let mut regions = Vec::new();
|
||||
let mut column = 0usize;
|
||||
for (index, hint) in shown.iter().enumerate() {
|
||||
if index > 0 {
|
||||
// The rail's own separator, not the footer's dimmer one: every neighboring row here
|
||||
// is muted, and a fainter dot between two of them simply reads as a gap.
|
||||
spans.push(Span::styled(HINT_SEPARATOR, styles.muted.patch(styles.tool_bg)));
|
||||
column += HINT_SEPARATOR.chars().count();
|
||||
}
|
||||
let cells = hint.text.chars().count();
|
||||
let style = if app.pointer.hover.as_ref() == Some(&hint.target) {
|
||||
styles.text.patch(styles.tool_bg).patch(styles.selected_bg)
|
||||
} else {
|
||||
styles.muted.patch(styles.tool_bg)
|
||||
};
|
||||
spans.push(Span::styled(hint.text.clone(), style));
|
||||
regions.push(DockHit {
|
||||
line,
|
||||
columns: Some((
|
||||
u16::try_from(column).unwrap_or(u16::MAX),
|
||||
u16::try_from(cells).unwrap_or(u16::MAX),
|
||||
)),
|
||||
target: hint.target.clone(),
|
||||
});
|
||||
column += cells;
|
||||
}
|
||||
(Line::from(spans), regions)
|
||||
}
|
||||
206
crates/luxe-tui/src/view/dock/plan.rs
Normal file
206
crates/luxe-tui/src/view/dock/plan.rs
Normal file
@@ -0,0 +1,206 @@
|
||||
//! Dock plan — the PLAN section: the checklist and the grants each row carries.
|
||||
|
||||
use super::anchors::{list_window, scrolls, DockListAnchor, DockSection};
|
||||
use super::chrome::{muted_line, section_heading_with, Section};
|
||||
use crate::app::App;
|
||||
use crate::widgets::truncate_end as truncate_cells;
|
||||
use crate::workspace_dock::{DockList, DockPlan, DockPlanItem};
|
||||
use luxe_core::TodoSummaryStatus;
|
||||
use ratatui::{
|
||||
style::Modifier,
|
||||
text::{Line, Span},
|
||||
};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
/// Rows the Plan checklist may spend on todos before it starts folding them into a counted tail.
|
||||
pub(super) const PLAN_ROWS_MAX: usize = 8;
|
||||
|
||||
/// Rows the checklist may spend, beyond one per todo, letting a long subject wrap.
|
||||
///
|
||||
/// A subject cut at the rail's edge hides the part that says which item it is, and a wider rail
|
||||
/// only moves the cut. The rows go first to the work in hand, then to what is next, then to what is
|
||||
/// done, so the budget buys the reading that matters before it buys the record.
|
||||
pub(super) const PLAN_WRAP_ROWS: usize = 4;
|
||||
|
||||
/// Rows of upcoming work the window keeps below the active one before it starts to scroll.
|
||||
pub(super) const PLAN_LOOKAHEAD: usize = 2;
|
||||
|
||||
/// Cells the tree connector spends at the head of a checklist row.
|
||||
const CONNECTOR_WIDTH: usize = 3;
|
||||
|
||||
/// Cells the status glyph and its space spend after it.
|
||||
const GLYPH_WIDTH: usize = 2;
|
||||
|
||||
/// The PLAN section: the session's todos as an actual checklist.
|
||||
///
|
||||
/// A single "current item + counts" line hid the shape of the work. Each todo gets its own row
|
||||
/// with a status glyph, the in-progress one is emphasized, and overflow folds into a counted tail
|
||||
/// so a long list can't swallow the panel.
|
||||
///
|
||||
/// The rows keep the order they were written in. Sorting the finished ones to the bottom made the
|
||||
/// list rearrange itself under the reader every time a box was ticked — a plan is a sequence, and
|
||||
/// the point of ticking one off is watching the line above the next one go green.
|
||||
///
|
||||
/// A checklist longer than the budget scrolls in a viewport of its own, with the window around the
|
||||
/// work in hand as the position it keeps while nobody has moved it.
|
||||
pub(super) fn plan_lines(plan: &DockPlan, app: &App) -> DockSection {
|
||||
let mut lines = vec![
|
||||
Line::default(),
|
||||
plan_heading_line(plan, app),
|
||||
muted_line(
|
||||
format!(
|
||||
"{} pending · {} active · {} done",
|
||||
plan.pending, plan.in_progress, plan.completed
|
||||
),
|
||||
app,
|
||||
),
|
||||
];
|
||||
|
||||
let total = plan.items.len();
|
||||
let (offset, width) =
|
||||
list_window(app, DockList::Plan, total, PLAN_ROWS_MAX, plan_follow(&plan.items));
|
||||
|
||||
let start = lines.len();
|
||||
let window: Vec<&DockPlanItem> = plan.items.iter().skip(offset).take(PLAN_ROWS_MAX).collect();
|
||||
let subject_width = width.saturating_sub(CONNECTOR_WIDTH + GLYPH_WIDTH).max(6);
|
||||
let wrapped: Vec<Vec<String>> =
|
||||
window.iter().map(|item| subject_rows(&item.subject, subject_width)).collect();
|
||||
let grants = plan_row_grants(&window, &wrapped);
|
||||
for (index, ((item, wrapped), rows)) in window.iter().zip(wrapped).zip(grants).enumerate() {
|
||||
// The connector closes the section only where this really is the checklist's last row —
|
||||
// which a plan the snapshot trimmed does not have on the rail at all.
|
||||
let last = offset + index + 1 == total && plan.remaining.unwrap_or(0) == 0;
|
||||
lines.extend(todo_lines(item, wrapped, last, subject_width, rows, app));
|
||||
}
|
||||
let end = lines.len();
|
||||
DockSection {
|
||||
lines,
|
||||
hits: Vec::new(),
|
||||
list: scrolls(DockList::Plan, (start, end), offset, total, PLAN_ROWS_MAX)
|
||||
.map(|list| DockListAnchor { window: Some(window.len()), ..list }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the checklist sits while nobody has scrolled it.
|
||||
///
|
||||
/// Anchored at the top, because that is where the list starts and where a reader working down it is
|
||||
/// looking. It slides only once the row in hand would fall off the end, and then only far enough to
|
||||
/// keep that row and the next couple in view — so the window moves a line at a time rather than
|
||||
/// jumping, and the work in flight is never the thing that got folded away.
|
||||
pub(super) fn plan_follow(items: &[DockPlanItem]) -> usize {
|
||||
if items.len() <= PLAN_ROWS_MAX {
|
||||
return 0;
|
||||
}
|
||||
let focus = items
|
||||
.iter()
|
||||
.position(|item| item.status == TodoSummaryStatus::InProgress)
|
||||
.or_else(|| items.iter().position(|item| item.status != TodoSummaryStatus::Completed))
|
||||
.unwrap_or(items.len() - 1);
|
||||
(focus + 1 + PLAN_LOOKAHEAD).saturating_sub(PLAN_ROWS_MAX).min(items.len() - PLAN_ROWS_MAX)
|
||||
}
|
||||
|
||||
/// How many rows each todo in the window may take: one each, then the wrap budget handed out by
|
||||
/// what the reader needs most — the work in hand (up to three rows), what is next (two), what is
|
||||
/// done (two).
|
||||
pub(super) fn plan_row_grants(window: &[&DockPlanItem], wrapped: &[Vec<String>]) -> Vec<usize> {
|
||||
let wants: Vec<usize> = window
|
||||
.iter()
|
||||
.zip(wrapped)
|
||||
.map(|(item, rows)| {
|
||||
let cap = match item.status {
|
||||
TodoSummaryStatus::InProgress => 3,
|
||||
_ => 2,
|
||||
};
|
||||
rows.len().clamp(1, cap)
|
||||
})
|
||||
.collect();
|
||||
let mut grants = vec![1; window.len()];
|
||||
let mut spare = (PLAN_ROWS_MAX + PLAN_WRAP_ROWS).saturating_sub(window.len());
|
||||
let rank = |status: TodoSummaryStatus| match status {
|
||||
TodoSummaryStatus::InProgress => 0,
|
||||
TodoSummaryStatus::Pending | TodoSummaryStatus::Blocked => 1,
|
||||
TodoSummaryStatus::Completed => 2,
|
||||
};
|
||||
let mut order: Vec<usize> = (0..window.len()).collect();
|
||||
order.sort_by_key(|&index| rank(window[index].status));
|
||||
for index in order {
|
||||
let extra = (wants[index] - 1).min(spare);
|
||||
grants[index] += extra;
|
||||
spare -= extra;
|
||||
}
|
||||
grants
|
||||
}
|
||||
|
||||
/// A subject word-wrapped to `width`, one string per row.
|
||||
pub(super) fn subject_rows(subject: &str, width: usize) -> Vec<String> {
|
||||
if subject.width() <= width {
|
||||
return vec![subject.to_string()];
|
||||
}
|
||||
crate::widgets::wrap_line(&Line::from(subject.to_string()), width)
|
||||
.iter()
|
||||
.map(|row| row.spans.iter().map(|span| span.content.as_ref()).collect::<String>())
|
||||
.map(|row| row.trim_end().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `PLAN 2/5` — the heading carries the completion ratio so a collapsed glance still informs.
|
||||
fn plan_heading_line(plan: &DockPlan, app: &App) -> Line<'static> {
|
||||
section_heading_with(Section::Plan, format!("{}/{}", plan.completed, plan.total), app)
|
||||
}
|
||||
|
||||
/// One checklist row: tree connector, status glyph, subject.
|
||||
///
|
||||
/// A blocked row says so with its mark and nothing else: its blockers' ids appear nowhere on the
|
||||
/// rail, and the row is too narrow to spare the cells.
|
||||
///
|
||||
/// A finished row is struck through as well as green, because green alone has to carry two jobs on
|
||||
/// this rail — "done" here and "added" in Changes — and now that the ticks stay where they were
|
||||
/// written, the strike is what a reader scans for. Decoration, not meaning: the ✓ and the words
|
||||
/// beside it still say it, so a terminal that ignores the attribute loses shine.
|
||||
///
|
||||
/// A subject longer than its row wraps onto up to `rows` rows, hanging under its own first word with
|
||||
/// the connector carried down beside it, and is cut on the last of them.
|
||||
pub(super) fn todo_lines(
|
||||
item: &DockPlanItem,
|
||||
mut wrapped: Vec<String>,
|
||||
last: bool,
|
||||
subject_width: usize,
|
||||
rows: usize,
|
||||
app: &App,
|
||||
) -> Vec<Line<'static>> {
|
||||
let styles = &app.theme_styles;
|
||||
let (glyph, style) = match item.status {
|
||||
TodoSummaryStatus::Completed => (crate::glyphs::Mark::Yes.glyph(), styles.success),
|
||||
TodoSummaryStatus::InProgress => {
|
||||
(crate::glyphs::Mark::Underway.glyph(), styles.text.add_modifier(Modifier::BOLD))
|
||||
}
|
||||
TodoSummaryStatus::Blocked => (crate::glyphs::Mark::Halted.glyph(), styles.warning),
|
||||
TodoSummaryStatus::Pending => ("○", styles.muted),
|
||||
};
|
||||
let subject_style = match item.status {
|
||||
TodoSummaryStatus::Completed => style.add_modifier(Modifier::CROSSED_OUT),
|
||||
_ => style,
|
||||
};
|
||||
let connector = if last { "└─" } else { "├─" };
|
||||
let rows = rows.max(1);
|
||||
if wrapped.len() > rows {
|
||||
let rest = wrapped.split_off(rows - 1).join(" ");
|
||||
wrapped.push(truncate_cells(&rest, subject_width));
|
||||
}
|
||||
let carried = if last { " " } else { "│ " };
|
||||
wrapped
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, text)| {
|
||||
let (lead, mark) = match index {
|
||||
0 => (format!("{connector} "), format!("{glyph} ")),
|
||||
_ => (carried.to_string(), " ".repeat(GLYPH_WIDTH)),
|
||||
};
|
||||
Line::from(vec![
|
||||
Span::styled(lead, styles.border.patch(styles.tool_bg)),
|
||||
Span::styled(mark, style.patch(styles.tool_bg)),
|
||||
Span::styled(text, subject_style.patch(styles.tool_bg)),
|
||||
])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
405
crates/luxe-tui/src/view/dock/telemetry.rs
Normal file
405
crates/luxe-tui/src/view/dock/telemetry.rs
Normal file
@@ -0,0 +1,405 @@
|
||||
//! Dock telemetry — the bottom-pinned footer: model and session telemetry, and the live activity.
|
||||
|
||||
use super::chrome::{section_heading_line, Section};
|
||||
use super::row_width;
|
||||
use crate::app::App;
|
||||
use crate::glyphs::{icon_cells, icon_label, Icon};
|
||||
use crate::statusline::{compact_number, thinking_label};
|
||||
use crate::widgets::truncate_end as truncate_cells;
|
||||
use crate::workspace_dock::DockPresentation;
|
||||
use ratatui::text::{Line, Span};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
/// Builds the bottom-pinned runtime footer: MODEL telemetry and the live activity line, each
|
||||
/// separated by a blank so the cluster reads next to the composer.
|
||||
///
|
||||
/// Returns the assembled footer plus the line index of each clickable row, present only when
|
||||
/// telemetry is relocated here, which is when the statusline is hidden.
|
||||
pub(super) fn footer_lines(
|
||||
app: &App,
|
||||
show_telemetry: bool,
|
||||
presentation: DockPresentation,
|
||||
) -> (Vec<Line<'static>>, Vec<(usize, crate::mouse::MouseTarget)>) {
|
||||
let mut blocks: Vec<Vec<Line<'static>>> = Vec::new();
|
||||
|
||||
let mut telemetry_block = None;
|
||||
if show_telemetry {
|
||||
let telemetry = telemetry_lines(app);
|
||||
if !telemetry.is_empty() {
|
||||
telemetry_block = Some(blocks.len());
|
||||
blocks.push(telemetry);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(activity) = activity_line(app, presentation) {
|
||||
blocks.push(vec![activity]);
|
||||
}
|
||||
|
||||
// Assemble with a blank between blocks, tracking where the telemetry block lands so the
|
||||
// model-name row (the line after its MODEL heading) can be published as a click target.
|
||||
//
|
||||
// A leading blank keeps the bottom-pinned footer off whatever the scrollable middle ends on: at
|
||||
// the wrong height its first heading landed directly under the previous section's last row and
|
||||
// the two read as one block.
|
||||
let mut lines = vec![Line::default()];
|
||||
let mut telemetry_start = None;
|
||||
for (index, block) in blocks.into_iter().enumerate() {
|
||||
if block.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if lines.len() > 1 {
|
||||
lines.push(Line::default());
|
||||
}
|
||||
if Some(index) == telemetry_block {
|
||||
telemetry_start = Some(lines.len());
|
||||
}
|
||||
lines.extend(block);
|
||||
}
|
||||
// Nothing but the leading blank means no runtime state to show: drop it rather than reserving a
|
||||
// row for an empty footer.
|
||||
if lines.len() == 1 {
|
||||
lines.clear();
|
||||
}
|
||||
let rows = telemetry_start
|
||||
.map(|start| {
|
||||
vec![
|
||||
(start + MODEL_ROW, crate::mouse::MouseTarget::DockModelRow),
|
||||
(start + MODE_ROW, crate::mouse::MouseTarget::DockModeRow),
|
||||
]
|
||||
})
|
||||
.unwrap_or_default();
|
||||
(lines, rows)
|
||||
}
|
||||
|
||||
/// Where the model and mode rows sit in [`telemetry_lines`], under its heading.
|
||||
const MODEL_ROW: usize = 1;
|
||||
const MODE_ROW: usize = 3;
|
||||
|
||||
/// Builds the live activity line (spinner + label + elapsed) for the dock footer.
|
||||
///
|
||||
/// Only rendered in replacement, where the dock *is* the whole surface and there is no
|
||||
/// conversation column to anchor the indicator to. Every other layout shows it at the bottom of
|
||||
/// the conversation, just above the composer (see `view::render`).
|
||||
fn activity_line(app: &App, presentation: DockPresentation) -> Option<Line<'static>> {
|
||||
if presentation != DockPresentation::Replacement {
|
||||
return None;
|
||||
}
|
||||
let (spinner, label) = crate::statusline::activity_parts(app)?;
|
||||
let styles = &app.theme_styles;
|
||||
let mut spans = vec![
|
||||
Span::styled(format!("{spinner} "), styles.accent.patch(styles.tool_bg)),
|
||||
Span::styled(label, styles.text.patch(styles.tool_bg)),
|
||||
];
|
||||
if let Some(elapsed) = app.status.elapsed(app.frame_now()) {
|
||||
spans.push(Span::styled(
|
||||
format!(" · {}", crate::statusline::format_elapsed_compact(elapsed)),
|
||||
styles.muted.patch(styles.tool_bg),
|
||||
));
|
||||
}
|
||||
// Follow-ups waiting behind this turn: say how many, so a queued message isn't invisible in
|
||||
// the one layout that hides the tray.
|
||||
let queued = app.queued_count();
|
||||
if queued > 0 {
|
||||
spans.push(Span::styled(
|
||||
format!(" · ⏸ {queued} queued"),
|
||||
styles.warning.patch(styles.tool_bg),
|
||||
));
|
||||
}
|
||||
Some(Line::from(spans))
|
||||
}
|
||||
|
||||
/// Narrowest the label column in the telemetry blocks gets: its width on the default rail.
|
||||
///
|
||||
/// Wide enough to clear the section badge above it, so no value sits under the closing cap of the
|
||||
/// heading that introduces it, and wide enough for the one label that is not ours: the provider
|
||||
/// serving the model takes this column, and a provider can be named anything (`foundry-anthropic`
|
||||
/// is seventeen cells).
|
||||
///
|
||||
/// The room comes out of the value column, and the MODEL row spends what is left on a model's
|
||||
/// name — so this number is a **split**, cell for cell, between two things that both elide. Across
|
||||
/// the models.dev snapshot each cell returned to the name fits about three percent more display
|
||||
/// names, while provider ids cluster well under nineteen and only a gateway prefix pushes one past
|
||||
/// it. Nineteen is where a `foundry-`-prefixed provider still reads in full and the name keeps the
|
||||
/// rest.
|
||||
///
|
||||
/// Every other value is bounded by what it reports — a percentage, a level, a price — or truncates
|
||||
/// itself, as the token row does ([`token_value`]). `every_telemetry_row_fits_the_rail` holds every
|
||||
/// end of that.
|
||||
///
|
||||
/// All of that is arithmetic about a forty-cell rail. A rail dragged wider has cells to spare, so
|
||||
/// [`telemetry_label_width`] grows the column from here rather than holding it.
|
||||
pub(super) const TELEMETRY_LABEL_WIDTH: usize = 19;
|
||||
|
||||
/// The label column for a `row`-wide dock whose longest label is `widest` cells.
|
||||
///
|
||||
/// The floor on the default rail, so that rail reads as it always has. Wider, the column grows to
|
||||
/// seat a provider the floor would cut, and the gap before the values grows with the rail: two
|
||||
/// cells of air read as a pair at forty cells and as a crowd at eighty. Never past two fifths of
|
||||
/// the row, which is what keeps the model's name the thing a wide rail spends its room on.
|
||||
pub(super) fn telemetry_label_width(row: usize, widest: usize) -> usize {
|
||||
let gap = match row {
|
||||
0..48 => 2,
|
||||
48..64 => 3,
|
||||
_ => 4,
|
||||
};
|
||||
(widest + gap).min(row * 2 / 5).max(TELEMETRY_LABEL_WIDTH)
|
||||
}
|
||||
|
||||
/// Cells a telemetry value has left in a `row`-wide dock row, after a `column`-wide label.
|
||||
pub(super) fn telemetry_value_width(row: usize, column: usize) -> usize {
|
||||
row.saturating_sub(column)
|
||||
}
|
||||
|
||||
/// What the session spent, in the room the row has: `↑2.3M ↓210k ⟳98.7M`.
|
||||
///
|
||||
/// The only telemetry value with nothing bounding it — the rest report a percentage, a level, a
|
||||
/// price, or truncate themselves — so it is the one that decides how wide the label column beside
|
||||
/// it may be. Rather than size that column around three figures nobody will ever see at once, the
|
||||
/// row gives up its **third** datum when all three will not fit: cache reuse is a footnote to the
|
||||
/// two counts it is measured against, it is already drawn only when there is any, and losing it is
|
||||
/// cheaper than a row that wraps — which would be two rows where the grid promised one, shifting a
|
||||
/// block pinned to the bottom of the rail.
|
||||
pub(super) fn token_value(totals: &luxe_core::usage::UsageTotals, room: usize) -> String {
|
||||
let spent = format!(
|
||||
"↑{} ↓{}",
|
||||
compact_number(totals.prompt_tokens),
|
||||
compact_number(totals.completion_tokens)
|
||||
);
|
||||
if totals.cache_read_tokens == 0 {
|
||||
return spent;
|
||||
}
|
||||
let cached =
|
||||
format!(" {}{}", crate::glyphs::Mark::CacheReuse, compact_number(totals.cache_read_tokens));
|
||||
match spent.width() + cached.width() <= room {
|
||||
true => spent + &cached,
|
||||
false => spent,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bottom-pinned runtime blocks: MODEL and SESSION.
|
||||
///
|
||||
/// Two sections, because they answer two questions. MODEL is *identity and setting* — what is
|
||||
/// answering, and how hard it is thinking. SESSION is *consumption* — how full the window is, how
|
||||
/// many tokens went through it, what that cost. The window leads SESSION because it is the only row
|
||||
/// with a deadline attached: the rest is a receipt, and this is the one about to make something
|
||||
/// happen. What keeps it from reading as more accounting is its color, which is the datum.
|
||||
///
|
||||
/// Every metric row is the same shape: a label naming it, then a value that leads with its own
|
||||
/// mark. The MODEL block is always here — a session with nothing chosen is a state worth reporting,
|
||||
/// and its row is the pointer's way into the picker; SESSION waits for a turn to measure, so an
|
||||
/// idle, pre-turn dock stays short.
|
||||
pub(super) fn telemetry_lines(app: &App) -> Vec<Line<'static>> {
|
||||
let status = &app.status;
|
||||
// Who is serving it takes the label column the rest of the block uses, so MODEL reads as one
|
||||
// grid with SESSION rather than as a headline with rows under it — and it is the one thing
|
||||
// about the model that its name does not say. Until the engine has announced a model there
|
||||
// is no provider to name, so the row falls back to saying what it is; leaving the column
|
||||
// empty would put the value somewhere no other row's value sits.
|
||||
let served_by = if status.provider.is_empty() { "model" } else { status.provider.as_str() };
|
||||
let row = row_width(app);
|
||||
let column = telemetry_label_width(row, served_by.width());
|
||||
let mut lines = model_telemetry(app, served_by, row, column);
|
||||
lines.extend(session_telemetry(app, row, column));
|
||||
lines
|
||||
}
|
||||
|
||||
/// The MODEL block: who serves it, the model, its thinking level, the mode, and auto-approval.
|
||||
fn model_telemetry(app: &App, served_by: &str, row: usize, column: usize) -> Vec<Line<'static>> {
|
||||
let styles = &app.theme_styles;
|
||||
let status = &app.status;
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
|
||||
lines.push(section_heading_line(Section::Model, app));
|
||||
let room = telemetry_value_width(row, column).saturating_sub(icon_cells(Icon::Model.glyph()));
|
||||
// Nothing chooses a model for the reader, so this row says which it is either way — and stays
|
||||
// the affordance that opens the picker, which is the whole reason a reader with none needs it.
|
||||
let (name, ink) = match status.model.is_empty() {
|
||||
true => ("no model".to_string(), styles.warning),
|
||||
false => (truncate_cells(&status.model, room), styles.text),
|
||||
};
|
||||
lines.push(telemetry_affordance(
|
||||
served_by,
|
||||
icon_label(Icon::Model.glyph(), &name),
|
||||
ink,
|
||||
column,
|
||||
app,
|
||||
&crate::mouse::MouseTarget::DockModelRow,
|
||||
));
|
||||
lines.push(telemetry_row(
|
||||
"thinking",
|
||||
icon_label(Icon::Thinking.glyph(), thinking_label(&status.thinking)),
|
||||
styles.text,
|
||||
column,
|
||||
app,
|
||||
));
|
||||
// Colored only in plan mode, the way the bar draws it; and a click switches, as the title does
|
||||
let mode = status.mode.as_str();
|
||||
let mode_ink = match mode {
|
||||
luxe_core::mode::BUILD => styles.text,
|
||||
_ => crate::modes::accent(mode, styles),
|
||||
};
|
||||
lines.push(telemetry_affordance(
|
||||
"mode",
|
||||
icon_label(crate::modes::icon(mode).glyph(), mode),
|
||||
mode_ink,
|
||||
column,
|
||||
app,
|
||||
&crate::mouse::MouseTarget::DockModeRow,
|
||||
));
|
||||
// The rail carries this only because it is here that the bar is not: telemetry is relocated
|
||||
// when the statusline is hidden, and a session approving its own escalations must not be able
|
||||
// to hide that by the reader turning a bar off. Drawn only while it is on, like the bar's.
|
||||
if app.permission_auto_approve {
|
||||
lines.push(telemetry_row(
|
||||
"approvals",
|
||||
icon_label(Icon::Permission.glyph(), "auto-approve"),
|
||||
styles.warning,
|
||||
column,
|
||||
app,
|
||||
));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// The SESSION block, once a turn has something to measure: the window, tokens, cost, and what
|
||||
/// the review and compaction spent of it.
|
||||
fn session_telemetry(app: &App, row: usize, column: usize) -> Vec<Line<'static>> {
|
||||
let styles = &app.theme_styles;
|
||||
let status = &app.status;
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
let totals = &status.session.total;
|
||||
let cost = status.session_cost_label();
|
||||
let has_tokens = totals.prompt_tokens > 0 || totals.completion_tokens > 0;
|
||||
if !(status.context_window > 0 || has_tokens || cost.is_some()) {
|
||||
return lines;
|
||||
}
|
||||
lines.push(Line::default());
|
||||
lines.push(section_heading_line(Section::Session, app));
|
||||
if status.context_window > 0 {
|
||||
// The one row whose value is also a warning, so it takes the severity hue rather than
|
||||
// body text. It wears the statusline's context glyph rather than one of its own,
|
||||
// because the bar and the rail are two forms of one surface and this is one reading.
|
||||
let percent = status.context_pct.clamp(0.0, 100.0);
|
||||
lines.push(telemetry_row(
|
||||
"context",
|
||||
icon_label(
|
||||
Icon::Context.glyph(),
|
||||
&format!("{percent:.0}% of {}", compact_number(u64::from(status.context_window))),
|
||||
),
|
||||
styles.context_fill(percent),
|
||||
column,
|
||||
app,
|
||||
));
|
||||
}
|
||||
if has_tokens {
|
||||
lines.push(telemetry_row(
|
||||
"tokens",
|
||||
token_value(totals, telemetry_value_width(row, column)),
|
||||
styles.text,
|
||||
column,
|
||||
app,
|
||||
));
|
||||
}
|
||||
if let Some(cost) = cost {
|
||||
lines.push(telemetry_row("cost", cost, styles.text, column, app));
|
||||
}
|
||||
lines.extend(source_cost_rows(app, column));
|
||||
lines
|
||||
}
|
||||
|
||||
/// What the review and compaction cost, each a dimmed share of the session's total.
|
||||
fn source_cost_rows(app: &App, column: usize) -> Vec<Line<'static>> {
|
||||
let styles = &app.theme_styles;
|
||||
let status = &app.status;
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
// What the review and automatic compaction cost, named: "is the review expensive?" is a fair
|
||||
// question that deserves a number rather than a guess.
|
||||
// Dimmed, because each is a share of the total above rather than another bill.
|
||||
for entry in &status.session.by_source {
|
||||
if entry.source == luxe_core::usage::UsageSource::Agent {
|
||||
continue;
|
||||
}
|
||||
// The review's row waits for its spend to settle rather than counting up through it
|
||||
let totals = match entry.source {
|
||||
luxe_core::usage::UsageSource::Review if review_spending(app) => {
|
||||
status.review_held.as_ref()
|
||||
}
|
||||
_ => Some(&entry.totals),
|
||||
};
|
||||
if let Some(cost) = totals.and_then(luxe_core::usage::UsageTotals::cost_label) {
|
||||
lines.push(telemetry_row(entry.source.label(), cost, styles.dim, column, app));
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Whether the review is spending right now: its guide being written, or its summary drafted.
|
||||
fn review_spending(app: &App) -> bool {
|
||||
let writing = app.review.queued.as_ref().is_some_and(|queued| {
|
||||
matches!(queued.state, crate::app::QueuedReviewState::Writing { .. })
|
||||
});
|
||||
let drafting = app
|
||||
.guided_review_workspace
|
||||
.github_post
|
||||
.as_ref()
|
||||
.is_some_and(|post| post.drafting.is_some());
|
||||
writing || drafting
|
||||
}
|
||||
|
||||
/// One `label value` telemetry row: a muted label column, then the value in `ink`.
|
||||
///
|
||||
/// `ink` is body text for a measurement, dim for a share of one above it, and the severity hue for
|
||||
/// the window, which is the one value that is also a warning.
|
||||
fn telemetry_row(
|
||||
label: &str,
|
||||
value: String,
|
||||
ink: ratatui::style::Style,
|
||||
column: usize,
|
||||
app: &App,
|
||||
) -> Line<'static> {
|
||||
Line::from(telemetry_spans(label, value, ink, column, app))
|
||||
}
|
||||
|
||||
/// The same row, clickable — highlighted while the pointer is over it so it reads as actionable.
|
||||
///
|
||||
/// The whole row lights up rather than the value alone: the label is half of what was clicked, and
|
||||
/// a highlight that stopped at the column boundary would read as two rows.
|
||||
fn telemetry_affordance(
|
||||
label: &str,
|
||||
value: String,
|
||||
ink: ratatui::style::Style,
|
||||
column: usize,
|
||||
app: &App,
|
||||
target: &crate::mouse::MouseTarget,
|
||||
) -> Line<'static> {
|
||||
let styles = &app.theme_styles;
|
||||
let spans = telemetry_spans(label, value, ink, column, app);
|
||||
if app.pointer.hover.as_ref() != Some(target) {
|
||||
return Line::from(spans);
|
||||
}
|
||||
let hovered = styles.text.patch(styles.tool_bg).patch(styles.selected_bg);
|
||||
Line::from(
|
||||
spans.into_iter().map(|span| Span::styled(span.content, hovered)).collect::<Vec<_>>(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The two spans a telemetry row is made of.
|
||||
///
|
||||
/// A label too long for its column is cut rather than allowed to push the value out of it — the
|
||||
/// grid is the whole point, and a provider can be named anything. Padded in cells rather than
|
||||
/// characters for the same reason.
|
||||
fn telemetry_spans(
|
||||
label: &str,
|
||||
value: String,
|
||||
ink: ratatui::style::Style,
|
||||
column: usize,
|
||||
app: &App,
|
||||
) -> Vec<Span<'static>> {
|
||||
let styles = &app.theme_styles;
|
||||
let label = truncate_cells(label, column.saturating_sub(1));
|
||||
let pad = " ".repeat(column.saturating_sub(label.width()));
|
||||
vec![
|
||||
Span::styled(format!("{label}{pad}"), styles.muted.patch(styles.tool_bg)),
|
||||
Span::styled(value, ink.patch(styles.tool_bg)),
|
||||
]
|
||||
}
|
||||
13
crates/luxe-tui/src/view/dock/tests.rs
Normal file
13
crates/luxe-tui/src/view/dock/tests.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use super::*;
|
||||
use crate::glyphs::{set_tier, GlyphTier};
|
||||
use crate::workspace_dock::DockChangeItem;
|
||||
use luxe_core::{config::Config, keymap::KeyMap};
|
||||
use ratatui::style::Color;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
mod lists;
|
||||
mod plan;
|
||||
mod rail;
|
||||
mod tree;
|
||||
|
||||
use rail::*;
|
||||
169
crates/luxe-tui/src/view/dock/tests/lists.rs
Normal file
169
crates/luxe-tui/src/view/dock/tests/lists.rs
Normal file
@@ -0,0 +1,169 @@
|
||||
//! Lists — scrolling lists, elsewhere, and the hint row.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) fn changes_of(paths: &[&str]) -> DockChanges {
|
||||
DockChanges {
|
||||
files: paths
|
||||
.iter()
|
||||
.map(|path| DockChangeItem {
|
||||
path: (*path).to_string(),
|
||||
status: luxe_core::workspace::FileChangeStatus::Modified,
|
||||
additions: Some(1),
|
||||
deletions: Some(0),
|
||||
})
|
||||
.collect(),
|
||||
total_files: paths.len(),
|
||||
additions: Some(paths.len() as u64),
|
||||
deletions: Some(0),
|
||||
remaining: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lane is paid for out of the rows it belongs to, and only while it is drawn.
|
||||
///
|
||||
/// A list that fits keeps its full width: two cells is a directory component in a forty-cell
|
||||
/// rail, and giving them up for a bar that is not there would cost every reader a path.
|
||||
#[test]
|
||||
fn a_scrolling_list_gives_up_exactly_the_lane_and_a_settled_one_gives_up_nothing() {
|
||||
let app = app();
|
||||
let paths: Vec<String> = (0..24).map(|index| format!("src/dir{index:02}/f.rs")).collect();
|
||||
let long: Vec<&str> = paths.iter().map(String::as_str).collect();
|
||||
|
||||
let widest = |section: &DockSection| {
|
||||
let (start, end) = section.list.as_ref().map_or((0, section.lines.len()), |l| l.rows);
|
||||
section.lines[start..end]
|
||||
.iter()
|
||||
.map(|line| UnicodeWidthStr::width(text(line).as_str()))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
|
||||
let scrolling = file_lines(Some(&changes_of(&long)), &app, 8);
|
||||
assert!(scrolling.list.is_some(), "twenty-four folders outgrow eight rows");
|
||||
assert!(
|
||||
widest(&scrolling) <= DEFAULT_ROW - SCROLLBAR_LANE,
|
||||
"a row ran into the lane: {}",
|
||||
widest(&scrolling)
|
||||
);
|
||||
|
||||
let settled = file_lines(Some(&changes_of(&long[..2])), &app, 8);
|
||||
assert!(settled.list.is_none(), "two files fit");
|
||||
assert!(widest(&settled) <= DEFAULT_ROW, "and still cannot outgrow the rail");
|
||||
}
|
||||
|
||||
/// A place holding `files`, each as `(path, additions)`.
|
||||
pub(super) fn place(root: &str, files: &[(&str, u64)]) -> DockExternalGroup {
|
||||
DockExternalGroup {
|
||||
root: root.into(),
|
||||
location: root.to_string(),
|
||||
branch: None,
|
||||
git: false,
|
||||
files: files
|
||||
.iter()
|
||||
.map(|(path, additions)| DockChangeItem {
|
||||
path: (*path).to_string(),
|
||||
status: luxe_core::workspace::FileChangeStatus::Modified,
|
||||
additions: Some(*additions),
|
||||
deletions: Some(0),
|
||||
})
|
||||
.collect(),
|
||||
remaining: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Elsewhere reads like Changes one level in: a place, the folders under it, the files under
|
||||
/// those — except at a place's own root, where the place already is the folder.
|
||||
#[test]
|
||||
fn elsewhere_nests_folders_under_a_place_but_not_at_its_root() {
|
||||
let app = app();
|
||||
let external = DockExternal {
|
||||
groups: vec![place("/work/sdk", &[("src/client.ts", 40), ("README.md", 2)])],
|
||||
total_files: 2,
|
||||
};
|
||||
let rows = external_rows(&external, &app);
|
||||
// A→Z, exactly as the changes are grouped — which puts the place's own root ahead of its folders.
|
||||
assert_eq!(
|
||||
shape(&rows),
|
||||
["place", "file", "directory", "file"],
|
||||
"one heading, and the root file has none"
|
||||
);
|
||||
assert!(
|
||||
matches!(&rows[2], ExternalRow::Under { row: DockChangeRow::Directory(at), .. }
|
||||
if at.directory == "src"),
|
||||
"and the heading is the folder the nested file is in"
|
||||
);
|
||||
}
|
||||
|
||||
/// What each ELSEWHERE row is, for a test that cares about the shape rather than the words.
|
||||
pub(super) fn shape<'a>(rows: &'a [ExternalRow<'a>]) -> Vec<&'static str> {
|
||||
rows.iter()
|
||||
.map(|row| match row {
|
||||
ExternalRow::Place { .. } => "place",
|
||||
ExternalRow::Under { row: DockChangeRow::Directory(_), .. } => "directory",
|
||||
ExternalRow::Under { .. } => "file",
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A window opening mid-place repeats what its rows sit under — up to two headings, because
|
||||
/// the list nests twice — and a window opening on a heading of its own repeats nothing.
|
||||
#[test]
|
||||
fn a_window_into_elsewhere_repeats_the_headings_it_opened_under() {
|
||||
let app = app();
|
||||
let external = DockExternal {
|
||||
groups: vec![
|
||||
place("/work/sdk", &[("src/client.ts", 40), ("src/events.ts", 20), ("README.md", 2)]),
|
||||
place("/work/tools", &[("bin/run.sh", 3)]),
|
||||
],
|
||||
total_files: 4,
|
||||
};
|
||||
let rows = external_rows(&external, &app);
|
||||
assert_eq!(
|
||||
shape(&rows),
|
||||
["place", "file", "directory", "file", "file", "place", "directory", "file"]
|
||||
);
|
||||
|
||||
assert!(external_context(&rows, 0).is_empty(), "the top is under nothing");
|
||||
assert!(external_context(&rows, 5).is_empty(), "and so is a place heading");
|
||||
assert_eq!(external_context(&rows, 2), [0], "a folder needs its place");
|
||||
assert_eq!(external_context(&rows, 3), [0, 2], "a nested file needs both");
|
||||
assert_eq!(external_context(&rows, 1), [0], "a root file needs only the place");
|
||||
assert_eq!(external_context(&rows, 7), [5, 6], "and the second place is its own");
|
||||
}
|
||||
|
||||
/// Both ways in, on one row, each answering for its own words — and never wrapped, because a
|
||||
/// wrapped hint puts half of itself where its click region no longer points.
|
||||
#[test]
|
||||
fn the_hint_row_offers_both_ways_in_and_keeps_them_on_one_line() {
|
||||
let app = app();
|
||||
let (line, regions) = hint_line(&change_hints(&app), 7, &app);
|
||||
assert_eq!(text(&line), "ctrl+p preview · ctrl+g review");
|
||||
assert!(
|
||||
UnicodeWidthStr::width(text(&line).as_str()) <= usize::from(CONTEXT_DOCK_WIDTH) - 2,
|
||||
"the rail has to seat it: {:?}",
|
||||
text(&line)
|
||||
);
|
||||
|
||||
// Each region names the columns its own words occupy, on the row it was built for.
|
||||
let (peek, review) = (®ions[0], ®ions[1]);
|
||||
assert_eq!(peek.target, crate::mouse::MouseTarget::DockPeekChanges);
|
||||
assert_eq!((peek.line, peek.columns), (7, Some((0, 14))));
|
||||
assert_eq!(review.target, crate::mouse::MouseTarget::DockReviewChanges);
|
||||
assert_eq!((review.line, review.columns), (7, Some((17, 13))));
|
||||
|
||||
// A rail too narrow for both keeps the review: every file row above already opens the preview.
|
||||
let long = vec![
|
||||
ChangeHint {
|
||||
text: "a very long way to say peek indeed, at length".into(),
|
||||
target: crate::mouse::MouseTarget::DockPeekChanges,
|
||||
},
|
||||
ChangeHint {
|
||||
text: "ctrl+g review".into(),
|
||||
target: crate::mouse::MouseTarget::DockReviewChanges,
|
||||
},
|
||||
];
|
||||
let (line, regions) = hint_line(&long, 0, &app);
|
||||
assert_eq!(text(&line), "ctrl+g review");
|
||||
assert_eq!(regions.len(), 1);
|
||||
}
|
||||
186
crates/luxe-tui/src/view/dock/tests/plan.rs
Normal file
186
crates/luxe-tui/src/view/dock/tests/plan.rs
Normal file
@@ -0,0 +1,186 @@
|
||||
//! Plan — the checklist, its order, its wrapping and its window.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) fn todo(subject: &str, status: TodoSummaryStatus) -> DockPlanItem {
|
||||
DockPlanItem { subject: subject.into(), status }
|
||||
}
|
||||
|
||||
pub(super) fn checklist(statuses: &[TodoSummaryStatus]) -> DockPlan {
|
||||
let items: Vec<DockPlanItem> = statuses
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, status)| todo(&format!("step {index}"), *status))
|
||||
.collect();
|
||||
DockPlan {
|
||||
pending: items.iter().filter(|i| i.status == TodoSummaryStatus::Pending).count(),
|
||||
in_progress: items.iter().filter(|i| i.status == TodoSummaryStatus::InProgress).count(),
|
||||
completed: items.iter().filter(|i| i.status == TodoSummaryStatus::Completed).count(),
|
||||
total: items.len(),
|
||||
remaining: None,
|
||||
items,
|
||||
}
|
||||
}
|
||||
|
||||
/// A plan is a sequence, and ticking a box must not move it.
|
||||
///
|
||||
/// The rows used to be regrouped by status on every render, so finishing the third item sent it
|
||||
/// to the bottom and pulled everything below it up a line — the list rearranged itself under a
|
||||
/// reader who was working down it.
|
||||
#[test]
|
||||
fn the_checklist_keeps_the_order_it_was_written_in() {
|
||||
use TodoSummaryStatus::{Completed, InProgress, Pending};
|
||||
let app = app();
|
||||
let plan = checklist(&[Completed, InProgress, Pending, Completed, Pending]);
|
||||
let rows: Vec<String> = plan_lines(&plan, &app)
|
||||
.lines
|
||||
.iter()
|
||||
.map(text)
|
||||
.filter(|row| row.contains("step "))
|
||||
.collect();
|
||||
let subjects: Vec<&str> =
|
||||
rows.iter().map(|row| row.trim_end().rsplit_once("step ").expect("a subject").1).collect();
|
||||
assert_eq!(subjects, ["0", "1", "2", "3", "4"], "{rows:?}");
|
||||
}
|
||||
|
||||
/// A long subject wraps under its own first word instead of being cut at the rail's edge, and
|
||||
/// the rows for it come out of a budget that serves the work in hand first.
|
||||
#[test]
|
||||
fn a_long_subject_wraps_within_the_plans_budget() {
|
||||
use TodoSummaryStatus::{Completed, InProgress, Pending};
|
||||
let app = app();
|
||||
let long = "Survey the AI Hub codebases (dev/prod, backend/frontend): scale, architecture, \
|
||||
test coverage and every integration that touches billing";
|
||||
let mut plan = checklist(&[Completed, InProgress, Pending]);
|
||||
for item in &mut plan.items {
|
||||
item.subject = long.to_string();
|
||||
}
|
||||
let rows: Vec<String> = plan_lines(&plan, &app).lines.iter().map(text).collect();
|
||||
let body = &rows[3..];
|
||||
assert_eq!(body.len(), 2 + 3 + 2, "done and next get two rows, the work in hand three");
|
||||
assert!(body[1].starts_with("│ "), "the connector carries down: {:?}", body[1]);
|
||||
assert!(body.last().is_some_and(|row| row.starts_with(" ")), "and closes at the end");
|
||||
assert!(body.iter().all(|row| row.width() <= DEFAULT_ROW), "{body:?}");
|
||||
assert!(body[1].ends_with('…'), "what does not fit is still cut: {:?}", body[1]);
|
||||
|
||||
// A full window has fewer spare rows, and the work in hand is first to them
|
||||
let mut busy = checklist(&[Completed; 8]);
|
||||
busy.items[7].status = InProgress;
|
||||
for item in &mut busy.items {
|
||||
item.subject = long.to_string();
|
||||
}
|
||||
let grants = plan_row_grants(
|
||||
&busy.items.iter().collect::<Vec<_>>(),
|
||||
&busy.items.iter().map(|item| subject_rows(&item.subject, 35)).collect::<Vec<_>>(),
|
||||
);
|
||||
assert_eq!(grants[7], 3, "{grants:?}");
|
||||
assert_eq!(grants.iter().sum::<usize>(), PLAN_ROWS_MAX + PLAN_WRAP_ROWS, "{grants:?}");
|
||||
|
||||
// And a subject that fits takes the one row it always did
|
||||
let short = checklist(&[Pending, Pending]);
|
||||
assert_eq!(plan_lines(&short, &app).lines.len(), 3 + 2);
|
||||
}
|
||||
|
||||
/// Done is green *and* struck through; nothing else on the rail is.
|
||||
#[test]
|
||||
fn a_finished_row_is_struck_through_and_only_its_words_are() {
|
||||
let app = app();
|
||||
let done = todo_lines(
|
||||
&todo("ship it", TodoSummaryStatus::Completed),
|
||||
vec!["ship it".into()],
|
||||
true,
|
||||
30,
|
||||
1,
|
||||
&app,
|
||||
)
|
||||
.remove(0);
|
||||
let subject = done.spans.iter().find(|s| s.content.contains("ship it")).expect("subject");
|
||||
assert!(subject.style.add_modifier.contains(Modifier::CROSSED_OUT));
|
||||
assert_eq!(subject.style.fg, app.theme_styles.success.fg, "still green");
|
||||
|
||||
// The tick itself is not struck: a struck ✓ reads as a mistake rather than a finished row.
|
||||
let tick = done.spans.iter().find(|s| s.content.contains('✓')).expect("a tick");
|
||||
assert!(!tick.style.add_modifier.contains(Modifier::CROSSED_OUT));
|
||||
|
||||
for open in
|
||||
[TodoSummaryStatus::Pending, TodoSummaryStatus::InProgress, TodoSummaryStatus::Blocked]
|
||||
{
|
||||
let line =
|
||||
todo_lines(&todo("ship it", open), vec!["ship it".into()], true, 30, 1, &app).remove(0);
|
||||
let subject = line.spans.iter().find(|s| s.content.contains("ship it")).expect("subject");
|
||||
assert!(
|
||||
!subject.style.add_modifier.contains(Modifier::CROSSED_OUT),
|
||||
"{open:?} is not finished"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The follow position is anchored at the top and slides only to keep the work in hand in view.
|
||||
#[test]
|
||||
fn the_plan_window_follows_the_row_in_hand_without_leaving_the_top() {
|
||||
use TodoSummaryStatus::{Completed, InProgress, Pending};
|
||||
let at = |active: usize, total: usize| {
|
||||
let statuses: Vec<TodoSummaryStatus> = (0..total)
|
||||
.map(|index| match index.cmp(&active) {
|
||||
std::cmp::Ordering::Less => Completed,
|
||||
std::cmp::Ordering::Equal => InProgress,
|
||||
std::cmp::Ordering::Greater => Pending,
|
||||
})
|
||||
.collect();
|
||||
plan_follow(&checklist(&statuses).items)
|
||||
};
|
||||
|
||||
// Everything fits: no window at all.
|
||||
assert_eq!(at(3, PLAN_ROWS_MAX), 0);
|
||||
|
||||
// It stays pinned to the top while the active row and its lookahead still fit …
|
||||
assert_eq!(at(0, 20), 0);
|
||||
assert_eq!(at(PLAN_ROWS_MAX - PLAN_LOOKAHEAD - 1, 20), 0);
|
||||
|
||||
// … then slides one row at a time, keeping the lookahead below the active row.
|
||||
assert_eq!(at(PLAN_ROWS_MAX - PLAN_LOOKAHEAD, 20), 1, "one row of history folded away");
|
||||
assert_eq!(at(PLAN_ROWS_MAX - PLAN_LOOKAHEAD + 1, 20), 2);
|
||||
|
||||
// And it stops at the end rather than scrolling past it.
|
||||
assert_eq!(at(19, 20), 12);
|
||||
|
||||
// A finished plan shows its tail, not its head.
|
||||
assert_eq!(plan_follow(&checklist(&[Completed; 20]).items), 12);
|
||||
}
|
||||
|
||||
/// A checklist longer than the rail is a viewport onto the whole thing: the bar says where the
|
||||
/// window sits, nothing counts what is outside it in words, and the active row survives.
|
||||
#[test]
|
||||
fn a_long_checklist_scrolls_under_a_bar_rather_than_counting_its_folds() {
|
||||
use TodoSummaryStatus::{Completed, InProgress, Pending};
|
||||
let app = app();
|
||||
let mut statuses = vec![Completed; 12];
|
||||
statuses[11] = InProgress;
|
||||
statuses.extend([Pending; 8]);
|
||||
let mut plan = checklist(&statuses);
|
||||
plan.remaining = Some(2);
|
||||
plan.total += 2;
|
||||
|
||||
let section = plan_lines(&plan, &app);
|
||||
let rendered: Vec<String> = section.lines.iter().map(text).collect();
|
||||
let all = rendered.join("\n");
|
||||
assert!(!all.contains("earlier"), "the bar says where the window is: {all}");
|
||||
assert!(!all.contains("more"), "and what is below it: {all}");
|
||||
assert!(!all.contains("not listed"), "and the rail counts nothing in words: {all}");
|
||||
assert!(all.contains("step 11"), "the row in hand is never the one folded away: {all}");
|
||||
assert!(all.contains("step 13"), "and the work just after it stays in view: {all}");
|
||||
assert_eq!(rendered.iter().filter(|row| row.contains("step ")).count(), PLAN_ROWS_MAX);
|
||||
|
||||
// The lane exists, spans exactly the todo rows, and gives them their two cells back.
|
||||
let list = section.list.expect("a checklist that outgrew the rail scrolls");
|
||||
assert_eq!(list.total, 20);
|
||||
assert_eq!(list.offset, plan_follow(&plan.items));
|
||||
assert_eq!(list.rows.1 - list.rows.0, PLAN_ROWS_MAX);
|
||||
for row in &rendered[list.rows.0..list.rows.1] {
|
||||
assert!(row.contains("step "), "the lane covers only the checklist: {row:?}");
|
||||
}
|
||||
|
||||
// A checklist that fits gets no lane, and keeps its full width.
|
||||
let short = checklist(&[Completed, InProgress, Pending]);
|
||||
assert!(plan_lines(&short, &app).list.is_none());
|
||||
}
|
||||
505
crates/luxe-tui/src/view/dock/tests/rail.rs
Normal file
505
crates/luxe-tui/src/view/dock/tests/rail.rs
Normal file
@@ -0,0 +1,505 @@
|
||||
//! Rail — the telemetry rows, their columns, and what the session says about itself.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A row of the default rail, which is what every test app draws.
|
||||
pub(super) const DEFAULT_ROW: usize = CONTEXT_DOCK_WIDTH as usize - 2;
|
||||
|
||||
pub(super) fn app() -> App {
|
||||
let (tx, _rx) = tokio::sync::mpsc::channel(4);
|
||||
App::new(tx, KeyMap::defaults(), Config { theme: Some("nord".into()), ..Config::default() })
|
||||
}
|
||||
|
||||
pub(super) fn text(line: &Line<'_>) -> String {
|
||||
line.spans.iter().map(|span| span.content.as_ref()).collect()
|
||||
}
|
||||
|
||||
/// The rail carries walk-away mode too, because it is what remains when the bar is hidden.
|
||||
///
|
||||
/// Telemetry relocates here exactly then, so without this row a reader who turned the
|
||||
/// statusline off would have no standing word that every escalation is being approved — and
|
||||
/// turning a bar off is not consent to that.
|
||||
#[test]
|
||||
fn the_rail_reports_a_session_that_is_approving_its_own_asks() {
|
||||
let mut app = app();
|
||||
app.status.model = "claude-sonnet-5".into();
|
||||
let quiet: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
assert!(
|
||||
!quiet.iter().any(|row| row.contains("auto-approve")),
|
||||
"prompting is not news: {quiet:?}"
|
||||
);
|
||||
|
||||
app.permission_auto_approve = true;
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
let row = rendered
|
||||
.iter()
|
||||
.find(|row| row.starts_with("approvals"))
|
||||
.unwrap_or_else(|| panic!("no approvals row in {rendered:?}"));
|
||||
assert!(row.contains("auto-approve"), "{row}");
|
||||
}
|
||||
|
||||
/// The surface behind the span carrying `needle` — the slab the badge is cut from.
|
||||
pub(super) fn surface_behind(line: &Line<'_>, needle: &str) -> Color {
|
||||
line.spans
|
||||
.iter()
|
||||
.find(|span| span.content.contains(needle))
|
||||
.and_then(|span| span.style.bg)
|
||||
.unwrap_or_else(|| panic!("no surface behind {needle:?}"))
|
||||
}
|
||||
|
||||
/// The bar's rule stood on end: the accent undiluted at both anchors, receding between them.
|
||||
///
|
||||
/// Pinned by section rather than by color literal, so a theme cannot break it and a section
|
||||
/// moving to a new depth has to say so here — which is the point, because the rail's colors are
|
||||
/// only legible as a ramp while the assignment stays deliberate.
|
||||
#[test]
|
||||
fn the_rail_is_anchored_at_both_ends_and_recedes_between_them() {
|
||||
let app = app();
|
||||
let shades = app.theme_styles.slab;
|
||||
let surface =
|
||||
|section: Section| surface_behind(§ion_heading_line(section, &app), section.label());
|
||||
|
||||
for anchor in [Section::Project, Section::Model] {
|
||||
assert_eq!(surface(anchor), shades.hero, "{anchor:?} anchors the rail");
|
||||
}
|
||||
for live in [Section::Plan, Section::Files] {
|
||||
assert_eq!(surface(live), shades.at(Depth::Raised), "{live:?} is one step back");
|
||||
}
|
||||
for ambient in [Section::Elsewhere, Section::Session] {
|
||||
assert_eq!(surface(ambient), shades.at(Depth::Recessed), "{ambient:?} is two");
|
||||
}
|
||||
// Or every assertion above passes on a theme with no ramp at all.
|
||||
assert_ne!(shades.hero, shades.at(Depth::Raised));
|
||||
assert_ne!(shades.at(Depth::Raised), shades.at(Depth::Recessed));
|
||||
}
|
||||
|
||||
/// A badge opens on the column its body rows start at, so a section reads as one block — which
|
||||
/// puts its label one cap and one pad further in, at every glyph tier, because a cap keeps its
|
||||
/// cell when the font cannot draw it.
|
||||
#[test]
|
||||
fn a_badge_opens_on_the_column_its_body_starts_at() {
|
||||
let app = app();
|
||||
for tier in [GlyphTier::Nerd, GlyphTier::Unicode, GlyphTier::Ascii] {
|
||||
set_tier(tier);
|
||||
let heading = text(§ion_heading_line(Section::Files, &app));
|
||||
let at = heading.find("FILES").expect("the label is on the row");
|
||||
assert_eq!(UnicodeWidthStr::width(&heading[..at]), 2, "at {tier:?}: {heading:?}");
|
||||
}
|
||||
set_tier(GlyphTier::Nerd);
|
||||
assert_eq!(text(&text_line("12 files".into(), &app)), "12 files", "body hugs the margin");
|
||||
}
|
||||
|
||||
/// Every badge holds one word, so the run of them down the rail reads as structure; what a
|
||||
/// heading summarizes follows it on the canvas, past the closing cap.
|
||||
#[test]
|
||||
fn a_heading_summary_rides_bare_beside_its_badge() {
|
||||
let app = app();
|
||||
let line = section_heading_with(Section::Plan, "4/9".into(), &app);
|
||||
assert!(text(&line).ends_with(" 4/9"), "{:?}", text(&line));
|
||||
assert_eq!(surface_behind(&line, "PLAN"), app.theme_styles.slab.at(Depth::Raised));
|
||||
assert_eq!(
|
||||
surface_behind(&line, "4/9"),
|
||||
app.theme_styles.tool_bg.bg.expect("the panel names its fill"),
|
||||
"the ratio sits on the panel, not on the badge"
|
||||
);
|
||||
}
|
||||
|
||||
/// The project row wears the statusline project module's folder, the way the branch and model
|
||||
/// rows under it wear their modules' icons: one fact, drawn the same on both forms of a surface.
|
||||
#[test]
|
||||
fn the_project_row_carries_the_statusline_folder() {
|
||||
use luxe_core::workspace::{ProjectIdentity, WorkspaceScopeId, WorkspaceSnapshot};
|
||||
let app = app();
|
||||
let snapshot = WorkspaceSnapshot::empty(
|
||||
WorkspaceScopeId::new("dock-project"),
|
||||
ProjectIdentity {
|
||||
root: "/work/luxe".into(),
|
||||
display_name: "luxe".into(),
|
||||
display_path: "~/work/luxe".into(),
|
||||
git_branch: Some("main".into()),
|
||||
git_head: None,
|
||||
git_dirty: false,
|
||||
},
|
||||
);
|
||||
let model = DockSectionModel::from_snapshot(&snapshot);
|
||||
let (header, ..) = region_lines(&model, &app, 40, false, DockPresentation::SideBySide);
|
||||
let project = text(&header[1]);
|
||||
assert_eq!(project, icon_label(Icon::Folder.glyph(), "luxe"), "{project:?}");
|
||||
assert!(text(&header[2]).starts_with(&icon_label(Icon::Branch.glyph(), "")), "the branch");
|
||||
}
|
||||
|
||||
/// One look, one setting. A bar asked to go flat takes the rail with it: this is the same shape
|
||||
/// on both forms of one surface, and half of it obeying would be worse than neither.
|
||||
#[test]
|
||||
fn a_flat_bar_flattens_the_rail_too() {
|
||||
let mut app = app();
|
||||
app.config.statusline.style = Some(StatuslineStyle::Flat);
|
||||
let heading = section_heading_line(Section::Project, &app);
|
||||
assert_eq!(text(&heading), "PROJECT", "no caps and no padding");
|
||||
assert_eq!(heading.spans[0].style.fg, app.theme_styles.accent.fg);
|
||||
}
|
||||
|
||||
/// The rail reports the model either way, and the row that opens the picker is there either way.
|
||||
///
|
||||
/// The section used to be suppressed when nothing was chosen, which hid the pointer's only way
|
||||
/// into the picker from the one reader who had not chosen yet.
|
||||
#[test]
|
||||
fn the_rail_says_when_no_model_is_selected() {
|
||||
let app = app();
|
||||
assert!(app.status.model.is_empty(), "nothing is chosen for the reader");
|
||||
let rendered: String =
|
||||
telemetry_lines(&app).iter().map(|line| format!("{}\n", text(line))).collect();
|
||||
assert!(rendered.contains("no model"), "{rendered}");
|
||||
|
||||
let mut chosen = app;
|
||||
chosen.status.model = "claude-sonnet-5".into();
|
||||
let rendered: String =
|
||||
telemetry_lines(&chosen).iter().map(|line| format!("{}\n", text(line))).collect();
|
||||
assert!(rendered.contains("claude-sonnet-5"), "{rendered}");
|
||||
assert!(!rendered.contains("no model"), "{rendered}");
|
||||
}
|
||||
|
||||
/// The review's row holds what the review had cost while its guide is being written, and
|
||||
/// shows the whole figure once it lands, rather than a batch's share of it partway through.
|
||||
#[test]
|
||||
fn the_review_row_waits_for_its_spend_to_settle() {
|
||||
use luxe_core::usage::{SessionUsage, SourceUsage, UsageSource, UsageTotals};
|
||||
let spent = |review: f64| {
|
||||
let totals = |cost_usd| UsageTotals { calls: 1, cost_usd, ..Default::default() };
|
||||
SessionUsage {
|
||||
total: totals(review),
|
||||
by_source: vec![SourceUsage { source: UsageSource::Review, totals: totals(review) }],
|
||||
}
|
||||
};
|
||||
let review_row = |app: &App| {
|
||||
telemetry_lines(app)
|
||||
.iter()
|
||||
.map(text)
|
||||
.find(|row| row.starts_with("review"))
|
||||
.map(|row| row.trim_start_matches("review").trim().to_owned())
|
||||
};
|
||||
let mut app = app();
|
||||
app.status.session = spent(0.10);
|
||||
assert_eq!(review_row(&app).as_deref(), Some("$0.10"));
|
||||
|
||||
app.status.hold_review_cost();
|
||||
app.review.queued = Some(crate::app::QueuedReview {
|
||||
target: luxe_core::guided_review::ReviewTarget::WorkingTree,
|
||||
state: crate::app::QueuedReviewState::Writing { since: std::time::Instant::now() },
|
||||
});
|
||||
app.status.session = spent(0.17);
|
||||
assert_eq!(review_row(&app).as_deref(), Some("$0.10"), "held while the guide is written");
|
||||
|
||||
app.review.queued.as_mut().expect("queued").state = crate::app::QueuedReviewState::Ready;
|
||||
app.status.session = spent(0.32);
|
||||
assert_eq!(review_row(&app).as_deref(), Some("$0.32"), "the whole figure once it lands");
|
||||
}
|
||||
|
||||
/// Every telemetry value opens on the same column, and it clears the badge above it.
|
||||
///
|
||||
/// The column only holds while every row goes through it — including the widest label there is,
|
||||
/// which is a cost breakdown's.
|
||||
#[test]
|
||||
fn every_telemetry_value_opens_on_one_column_clear_of_the_badge() {
|
||||
let mut app = app();
|
||||
app.status.model = "claude-sonnet-5".into();
|
||||
app.status.provider = "anthropic".into();
|
||||
app.status.context_window = 1_000_000;
|
||||
app.status.context_pct = 3.0;
|
||||
app.status.session = luxe_core::usage::SessionUsage {
|
||||
total: luxe_core::usage::UsageTotals {
|
||||
calls: 12,
|
||||
prompt_tokens: 295_000,
|
||||
completion_tokens: 5_300,
|
||||
cache_read_tokens: 266_000,
|
||||
cost_usd: 0.18,
|
||||
..Default::default()
|
||||
},
|
||||
by_source: vec![luxe_core::usage::SourceUsage {
|
||||
source: luxe_core::usage::UsageSource::Compaction,
|
||||
totals: luxe_core::usage::UsageTotals {
|
||||
calls: 2,
|
||||
cost_usd: 0.02,
|
||||
..Default::default()
|
||||
},
|
||||
}],
|
||||
};
|
||||
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
let value_at = |label: &str| -> usize {
|
||||
let row = rendered
|
||||
.iter()
|
||||
.find(|row| row.starts_with(label))
|
||||
.unwrap_or_else(|| panic!("no {label} row in {rendered:?}"));
|
||||
UnicodeWidthStr::width(&row[..row.len() - row.trim_start_matches(label).trim_start().len()])
|
||||
};
|
||||
for label in ["anthropic", "thinking", "context", "tokens", "cost", "compaction"] {
|
||||
assert_eq!(value_at(label), TELEMETRY_LABEL_WIDTH, "{label} in {rendered:?}");
|
||||
}
|
||||
|
||||
// The badge is a cap, a pad, the word and a pad, then the closing cap.
|
||||
let badge =
|
||||
UnicodeWidthStr::width(text(§ion_heading_line(Section::Session, &app)).as_str());
|
||||
assert!(badge < TELEMETRY_LABEL_WIDTH, "a value would sit under the badge: {badge}");
|
||||
|
||||
// And the widest row still fits the rail it is drawn in.
|
||||
let widest = rendered.iter().map(|row| UnicodeWidthStr::width(row.as_str())).max();
|
||||
assert!(
|
||||
widest.is_some_and(|width| width <= usize::from(CONTEXT_DOCK_WIDTH) - 2),
|
||||
"the rail cannot seat it: {rendered:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The token row keeps the two counts and gives up the footnote when the rail is tight.
|
||||
///
|
||||
/// It is the only value with nothing bounding it, so it is the one that used to decide how
|
||||
/// wide the label column beside it could be. Shedding cache reuse at the top of the range buys
|
||||
/// that column four cells for every session, at the cost of a figure only the largest sessions
|
||||
/// lose — and it is a footnote to the two counts it sits beside.
|
||||
#[test]
|
||||
fn the_token_row_sheds_its_footnote_rather_than_the_rail() {
|
||||
let totals = |prompt, completion, cache| luxe_core::usage::UsageTotals {
|
||||
prompt_tokens: prompt,
|
||||
completion_tokens: completion,
|
||||
cache_read_tokens: cache,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Ordinary and large-but-real sessions keep all three.
|
||||
let room = telemetry_value_width(DEFAULT_ROW, TELEMETRY_LABEL_WIDTH);
|
||||
let ordinary = token_value(&totals(900_000, 42_000, 600_000), room);
|
||||
assert_eq!(ordinary, format!("↑900k ↓42k {}600k", crate::glyphs::Mark::CacheReuse));
|
||||
let large = token_value(&totals(12_300_000, 340_000, 9_800_000), room);
|
||||
assert!(
|
||||
large.contains(&crate::glyphs::Mark::CacheReuse.to_string()),
|
||||
"a session with room keeps its footnote: {large}"
|
||||
);
|
||||
|
||||
// At the top of the range the footnote goes, and the counts never do.
|
||||
let vast = token_value(&totals(999_900_000, 999_900_000, 999_900_000), room);
|
||||
assert_eq!(vast, "↑999.9M ↓999.9M", "the two counts are the row");
|
||||
assert!(vast.width() <= room, "{vast} still overruns");
|
||||
|
||||
// Nothing to report is not the same as no room to report it.
|
||||
assert_eq!(token_value(&totals(900_000, 42_000, 0), room), "↑900k ↓42k");
|
||||
}
|
||||
|
||||
/// The label column is paid for out of the value column, so the widest value still has to fit.
|
||||
///
|
||||
/// Not the sample figures above but the widest the formatters can produce: `compact_number`
|
||||
/// tops out at six cells (`999.9M`), and the token row spends two of those plus their marks
|
||||
/// and a space. A row that outgrows the rail wraps, and a wrapped telemetry row is two rows
|
||||
/// where the grid promised one — under a block pinned to the bottom of the rail, so it moves
|
||||
/// what the reader was looking at.
|
||||
#[test]
|
||||
fn every_telemetry_row_fits_the_rail() {
|
||||
let mut app = app();
|
||||
app.status.model = "a-very-long-model-identifier".into();
|
||||
app.status.provider = "a-self-hosted-gateway".into();
|
||||
app.status.context_window = 999_999_999;
|
||||
app.status.context_pct = 99.9;
|
||||
app.permission_auto_approve = true;
|
||||
app.status.session.total = luxe_core::usage::UsageTotals {
|
||||
calls: 9,
|
||||
prompt_tokens: 999_900_000,
|
||||
completion_tokens: 999_900_000,
|
||||
cache_read_tokens: 999_900_000,
|
||||
cost_usd: 98_765.43,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let content = usize::from(CONTEXT_DOCK_WIDTH) - 2;
|
||||
for row in telemetry_lines(&app).iter().map(text) {
|
||||
assert!(
|
||||
UnicodeWidthStr::width(row.as_str()) <= content,
|
||||
"{row:?} is {} cells, and the rail seats {content}",
|
||||
UnicodeWidthStr::width(row.as_str())
|
||||
);
|
||||
}
|
||||
|
||||
// The other end of the same budget: the column has to seat the longest provider anyone has
|
||||
// put in front of it, or this is all arithmetic about nothing.
|
||||
assert!(
|
||||
TELEMETRY_LABEL_WIDTH > "foundry-anthropic".width(),
|
||||
"a gateway-prefixed provider is cut, which is the whole reason for the column's width"
|
||||
);
|
||||
app.status.provider = "foundry-anthropic".into();
|
||||
app.status.model = "Claude Fable 5.1 (EU)".into();
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
assert!(
|
||||
rendered.iter().any(|row| row.starts_with("foundry-anthropic ")),
|
||||
"the provider is elided: {rendered:?}"
|
||||
);
|
||||
|
||||
// And the third end: the label column is a split, so taking a cell from the value is
|
||||
// taking it from a model's name. Both of these elide, and a column that seated every
|
||||
// provider id ever written would leave the names — where the variety actually is — paying
|
||||
// for it on every row of every session.
|
||||
let name_room = telemetry_value_width(DEFAULT_ROW, TELEMETRY_LABEL_WIDTH)
|
||||
.saturating_sub(icon_cells(Icon::Model.glyph()));
|
||||
assert!(
|
||||
name_room >= "Claude Sonnet 4.6".width(),
|
||||
"a routine model name does not fit in {name_room} cells"
|
||||
);
|
||||
}
|
||||
|
||||
/// The model row is a row like the others: who serves it on the left, what it is on the right.
|
||||
///
|
||||
/// It used to be the block's headline — the one line in MODEL and SESSION with no label column,
|
||||
/// so its icon sat where every other row's *label* starts and the grid broke at the top. The
|
||||
/// provider is what the column was missing: the one fact about the model its name does not say.
|
||||
#[test]
|
||||
fn the_model_row_is_labeled_by_who_serves_it() {
|
||||
let mut app = app();
|
||||
app.status.model = "claude-sonnet-5".into();
|
||||
app.status.provider = "anthropic".into();
|
||||
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
let model = rendered.iter().find(|row| row.contains("claude-sonnet-5")).expect("a model");
|
||||
assert!(model.starts_with("anthropic"), "{model:?}");
|
||||
assert!(
|
||||
model.ends_with(&crate::glyphs::icon_label(Icon::Model.glyph(), "claude-sonnet-5")),
|
||||
"the value keeps its own mark: {model:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A provider longer than the column is cut rather than allowed to shove the value out of it —
|
||||
/// provider ids are whatever a config names them, and the grid is the whole point of the block.
|
||||
#[test]
|
||||
fn a_long_provider_is_cut_to_its_column() {
|
||||
let mut app = app();
|
||||
app.status.model = "claude-sonnet-5".into();
|
||||
app.status.provider = "a-self-hosted-gateway".into();
|
||||
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
let model = rendered.iter().find(|row| row.contains(Icon::Model.glyph())).expect("a model");
|
||||
let opens_at = model.find(Icon::Model.glyph()).expect("the value's mark");
|
||||
assert_eq!(
|
||||
UnicodeWidthStr::width(&model[..opens_at]),
|
||||
TELEMETRY_LABEL_WIDTH,
|
||||
"the value moved off its column: {model:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A rail dragged wide gives the grid air and the provider its whole name; the default rail
|
||||
/// keeps the column it has always had.
|
||||
#[test]
|
||||
fn a_wide_rail_widens_the_grid_and_seats_a_long_provider() {
|
||||
let mut app = app();
|
||||
app.status.model = "claude-opus-5".into();
|
||||
app.status.provider = "foundry-anthropic".into();
|
||||
app.status.context_window = 1_000_000;
|
||||
let value_column = |app: &App| -> Vec<usize> {
|
||||
telemetry_lines(app)
|
||||
.iter()
|
||||
.map(text)
|
||||
.filter(|row| row.starts_with("foundry-anthropic") || row.starts_with("context"))
|
||||
.map(|row| {
|
||||
let label = row.split_whitespace().next().unwrap_or_default().to_string();
|
||||
let value = row[label.len()..].trim_start();
|
||||
UnicodeWidthStr::width(&row[..row.len() - value.len()])
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(value_column(&app), [TELEMETRY_LABEL_WIDTH; 2], "the default rail is unchanged");
|
||||
|
||||
app.dock_rail.set(crate::workspace_layout::DOCK_MAX_WIDTH);
|
||||
let wide = value_column(&app);
|
||||
assert_eq!(wide, [21; 2], "seventeen cells of provider, four of air, one grid: {wide:?}");
|
||||
|
||||
app.status.provider = "a-self-hosted-gateway-provider".into();
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
assert!(
|
||||
rendered.iter().any(|row| row.starts_with("a-self-hosted-gateway-provider ")),
|
||||
"a wide rail seats the whole name: {rendered:?}"
|
||||
);
|
||||
for row in &rendered {
|
||||
assert!(UnicodeWidthStr::width(row.as_str()) <= row_width(&app), "{row:?} overruns");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_label_column_grows_only_where_there_is_room() {
|
||||
assert_eq!(telemetry_label_width(40, 17), TELEMETRY_LABEL_WIDTH);
|
||||
assert_eq!(telemetry_label_width(40, 30), TELEMETRY_LABEL_WIDTH, "cut, as it always was");
|
||||
assert_eq!(telemetry_label_width(78, 8), TELEMETRY_LABEL_WIDTH, "short labels keep the floor");
|
||||
assert_eq!(telemetry_label_width(78, 17), 21);
|
||||
assert_eq!(telemetry_label_width(78, 60), 31, "never past two fifths of the row");
|
||||
}
|
||||
|
||||
/// Before the engine has said anything there is no provider to name, and a blank label column
|
||||
/// would leave the value sitting where no other row's value sits.
|
||||
#[test]
|
||||
fn a_model_with_no_provider_yet_still_labels_its_row() {
|
||||
let mut app = app();
|
||||
app.status.model = "claude-sonnet-5".into();
|
||||
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
let model = rendered.iter().find(|row| row.contains("claude-sonnet-5")).expect("a model");
|
||||
assert!(model.starts_with("model"), "{model:?}");
|
||||
}
|
||||
|
||||
/// One block for what the session consumed, so the window is not a section of its own.
|
||||
///
|
||||
/// Three headings over five rows spent as much rail on the badges as on the numbers. What keeps
|
||||
/// the window from reading as more accounting was never the badge — it is the color, which it
|
||||
/// keeps.
|
||||
#[test]
|
||||
fn the_window_is_read_under_session_rather_than_a_heading_of_its_own() {
|
||||
let mut app = app();
|
||||
app.status.model = "claude-sonnet-5".into();
|
||||
app.status.context_window = 200_000;
|
||||
app.status.context_pct = 42.0;
|
||||
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
assert!(!rendered.iter().any(|row| row.contains("CONTEXT")), "{rendered:?}");
|
||||
assert!(!rendered.iter().any(|row| row.starts_with("used")), "{rendered:?}");
|
||||
|
||||
let session = rendered.iter().position(|row| row.contains("SESSION")).expect("a heading");
|
||||
let window = rendered.iter().position(|row| row.starts_with("context")).expect("a window");
|
||||
assert_eq!(window, session + 1, "the window leads the block: {rendered:?}");
|
||||
assert!(rendered[window].ends_with("42% of 200k"), "{:?}", rendered[window]);
|
||||
assert!(rendered[window].contains(Icon::Context.glyph()), "{:?}", rendered[window]);
|
||||
}
|
||||
|
||||
/// Occupancy is a figure, not a chart — the same rule `/context` already holds itself to.
|
||||
///
|
||||
/// A ten-cell bar between the glyph and the number drew what the number already said, and left
|
||||
/// this the one row in the block whose value missed the column its neighbors share. At the
|
||||
/// occupancy a session spends most of its life at it was mostly empty rail, which read as a
|
||||
/// trench rather than a meter. The severity hue survives it, because that part is information.
|
||||
#[test]
|
||||
fn the_window_is_a_figure_rather_than_a_bar() {
|
||||
let mut app = app();
|
||||
app.status.model = "claude-sonnet-5".into();
|
||||
app.status.context_window = 200_000;
|
||||
|
||||
// The section badges are cut from Block Elements themselves, so they are dropped before
|
||||
// the scan rather than exempting their whole row — a gauge smuggled back into a heading
|
||||
// would still be caught.
|
||||
let caps = [crate::widgets::Cap::Open.glyph(), crate::widgets::Cap::Close.glyph()];
|
||||
for percent in [0.0, 12.4, 42.0, 80.0, 95.0, 100.0] {
|
||||
app.status.context_pct = percent;
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
assert!(
|
||||
!rendered.iter().any(|row| row
|
||||
.chars()
|
||||
.filter(|glyph| !caps.contains(&glyph.to_string().as_str()))
|
||||
.any(|glyph| ('\u{2580}'..='\u{259f}').contains(&glyph))),
|
||||
"a block element is drawn at {percent}%: {rendered:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// And the figure opens on the value column, level with the rows underneath it.
|
||||
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
|
||||
let window = rendered.iter().find(|row| row.starts_with("context")).expect("a window");
|
||||
let sibling = rendered.iter().find(|row| row.starts_with("thinking")).expect("a sibling");
|
||||
let opens_at = |row: &str, label: &str| {
|
||||
UnicodeWidthStr::width(&row[..row.len() - row.trim_start_matches(label).trim_start().len()])
|
||||
};
|
||||
assert_eq!(
|
||||
opens_at(window, "context"),
|
||||
opens_at(sibling, "thinking"),
|
||||
"{window:?} against {sibling:?}"
|
||||
);
|
||||
}
|
||||
136
crates/luxe-tui/src/view/dock/tests/tree.rs
Normal file
136
crates/luxe-tui/src/view/dock/tests/tree.rs
Normal file
@@ -0,0 +1,136 @@
|
||||
//! Tree — the file tree in the rail, its filter and its commit hint.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_tree_takes_the_height_the_rest_of_the_rail_leaves() {
|
||||
// A tall dock gives the tree everything else does not use: it is the project, not a list
|
||||
assert_eq!(files_row_cap(40, 8), 40 - 8 - FILES_FIXED_ROWS);
|
||||
|
||||
// A crowded rail keeps a usable window rather than collapsing: the tree scrolls, so the
|
||||
// rows it cannot show are reachable, and the sections underneath it are reached by
|
||||
// scrolling the panel.
|
||||
assert_eq!(files_row_cap(20, 16), FILE_ROWS_MIN);
|
||||
assert_eq!(files_row_cap(40, 36), FILE_ROWS_MIN);
|
||||
|
||||
// The floor scales down with the panel, so a very short dock still spends most of itself
|
||||
// on everything else — a quarter of the rail rather than a flat five rows.
|
||||
assert_eq!(files_row_cap(12, 10), 3);
|
||||
assert_eq!(files_row_cap(6, 4), 1);
|
||||
}
|
||||
|
||||
/// A commit must not take the way into the review with it.
|
||||
///
|
||||
/// This is the loss a real session reported: the agent committed at the end of its turn, the
|
||||
/// diff against `HEAD` went to zero, the section rendered nothing, and the review that was
|
||||
/// about to be walked had no affordance left anywhere on the surface.
|
||||
/// A filter says what it is filtering by and how much it found, takes a row from the tree
|
||||
/// rather than growing the section, and lights the matched characters in the accent.
|
||||
#[test]
|
||||
fn a_filter_says_what_it_matched_and_lights_it() {
|
||||
let mut app = app();
|
||||
let files = ["src/view/dock.rs".to_string(), "src/app.rs".to_string()];
|
||||
crate::fixture::filter_tree(&mut app, &files, "dock");
|
||||
let section = file_lines(None, &app, 8);
|
||||
let lines: Vec<String> = section.lines.iter().map(text).collect();
|
||||
assert!(lines.iter().any(|line| line.starts_with("/ dock▏") && line.ends_with('1')));
|
||||
assert!(lines.iter().any(|line| line.contains("esc clear")), "{lines:?}");
|
||||
let row = section.lines.iter().find(|line| text(line).contains("dock.rs")).unwrap();
|
||||
let lit: String = row
|
||||
.spans
|
||||
.iter()
|
||||
.filter(|span| span.style.fg == app.theme_styles.accent.fg)
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect();
|
||||
assert_eq!(lit, "dock");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_commit_leaves_the_review_reachable_instead_of_an_empty_rail() {
|
||||
let mut app = app();
|
||||
let rendered = |app: &App| -> String {
|
||||
file_lines(None, app, 8).lines.iter().map(text).collect::<Vec<_>>().join("\n")
|
||||
};
|
||||
assert!(!rendered(&app).contains("committed"), "nothing has happened yet");
|
||||
|
||||
app.worktree_emptied = true;
|
||||
assert!(!rendered(&app).contains("committed"), "and nothing is retained to review");
|
||||
|
||||
app.review.last_turn = Some(("session-1".into(), "turn-1".into()));
|
||||
let rendered = rendered(&app);
|
||||
assert!(rendered.contains("FILES"), "{rendered}");
|
||||
assert!(rendered.contains("committed"), "says where the work went: {rendered}");
|
||||
assert!(rendered.contains("still reviewable"), "and that it is not lost: {rendered}");
|
||||
assert!(rendered.contains("ctrl+g review"), "and how to get there: {rendered}");
|
||||
assert!(
|
||||
!rendered.contains("preview"),
|
||||
"and not how to glance, with nothing left in the worktree to glance at: {rendered}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The way into the review is a row of its own that answers a click.
|
||||
#[test]
|
||||
fn the_committed_review_hint_is_a_row_that_opens_the_review() {
|
||||
let mut app = app();
|
||||
app.worktree_emptied = true;
|
||||
app.review.last_turn = Some(("session-1".into(), "turn-1".into()));
|
||||
let section = file_lines(None, &app, 8);
|
||||
let last = section.lines.len() - 1;
|
||||
assert_eq!(text(§ion.lines[last]), "ctrl+t browse · ctrl+g review");
|
||||
assert!(section
|
||||
.hits
|
||||
.iter()
|
||||
.any(|hit| hit.line == last && hit.target == crate::mouse::MouseTarget::DockReviewChanges));
|
||||
}
|
||||
|
||||
/// The file showing in the preview is told apart by its name, accent and bold, and the band is
|
||||
/// left to the row the keyboard is on, so the two never look alike on different rows.
|
||||
#[test]
|
||||
fn the_showing_file_wears_its_name_and_the_keyboard_row_wears_the_band() {
|
||||
let mut app = app();
|
||||
let showing = TreeRow::File {
|
||||
path: "CHANGELOG.md".into(),
|
||||
name: "CHANGELOG.md".into(),
|
||||
depth: 0,
|
||||
change: None,
|
||||
ignored: false,
|
||||
};
|
||||
let line = tree_row_line(&showing, 40, Some("CHANGELOG.md"), None, &app);
|
||||
let name = line.spans.iter().find(|span| span.content.contains("CHANGELOG")).unwrap();
|
||||
assert_eq!(name.style.fg, app.theme_styles.accent.fg, "the name says it is showing");
|
||||
assert!(name.style.add_modifier.contains(Modifier::BOLD));
|
||||
assert_ne!(name.style.bg, app.theme_styles.selected_bg.bg, "but wears no band");
|
||||
|
||||
app.files.focused = true;
|
||||
app.files.cursor = Some("src".into());
|
||||
let keyed = TreeRow::Folder {
|
||||
path: "src".into(),
|
||||
name: "src".into(),
|
||||
depth: 0,
|
||||
open: false,
|
||||
holds_change: false,
|
||||
ignored: false,
|
||||
};
|
||||
let line = tree_row_line(&keyed, 40, Some("CHANGELOG.md"), None, &app);
|
||||
let name = line.spans.iter().find(|span| span.content == "src").unwrap();
|
||||
assert_eq!(name.style.bg, app.theme_styles.selected_bg.bg, "the keyboard's row is banded");
|
||||
}
|
||||
|
||||
/// The tree says how to reach it from the keyboard, and once the keyboard is in it, what the
|
||||
/// keys do there; the hint answers a click by putting the keyboard in.
|
||||
#[test]
|
||||
fn the_tree_says_how_to_move_through_it_with_keys() {
|
||||
let mut app = app();
|
||||
let section = file_lines(None, &app, 8);
|
||||
let last = section.lines.len() - 1;
|
||||
assert_eq!(text(§ion.lines[last]), "ctrl+t browse");
|
||||
assert!(section
|
||||
.hits
|
||||
.iter()
|
||||
.any(|hit| hit.line == last && hit.target == crate::mouse::MouseTarget::DockFocusFiles));
|
||||
|
||||
app.files.focused = true;
|
||||
let section = file_lines(None, &app, 8);
|
||||
let last = section.lines.len() - 1;
|
||||
assert_eq!(text(§ion.lines[last]), "j k move · l open · / filter · esc back");
|
||||
}
|
||||
218
crates/luxe-tui/src/view/dock/tree.rs
Normal file
218
crates/luxe-tui/src/view/dock/tree.rs
Normal file
@@ -0,0 +1,218 @@
|
||||
//! Dock tree — one row of the file tree: its lead, name and change cells, fitted to the rail.
|
||||
|
||||
use super::chrome::status_mark;
|
||||
use crate::app::App;
|
||||
use crate::files::TreeRow;
|
||||
use crate::glyphs::{icon_cells, icon_label, Icon};
|
||||
use crate::widgets::truncate_end as truncate_cells;
|
||||
use ratatui::{
|
||||
style::Modifier,
|
||||
text::{Line, Span},
|
||||
};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
/// What a click on a tree row does.
|
||||
pub(super) fn tree_row_target(row: &TreeRow) -> Option<crate::mouse::MouseTarget> {
|
||||
match row {
|
||||
TreeRow::Folder { path, .. } => Some(crate::mouse::MouseTarget::DockFolder(path.clone())),
|
||||
TreeRow::File { path, .. } => Some(crate::mouse::MouseTarget::DockFile(path.clone())),
|
||||
TreeRow::Note { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One tree row: indent guides, a chevron on a folder, an icon, the name, and on the right what git
|
||||
/// says about it.
|
||||
///
|
||||
/// A changed file wears the color and letter CHANGES gave it, and its ± counts; a closed folder with
|
||||
/// a change somewhere under it carries a dot, so nothing changed can hide behind a fold. The row
|
||||
/// showing in the Changes pane, the one the keyboard is on and the one under the pointer all wear
|
||||
/// the selection slab, which means *this one* everywhere else in the product.
|
||||
pub(super) fn tree_row_line(
|
||||
row: &TreeRow,
|
||||
width: usize,
|
||||
open: Option<&str>,
|
||||
seen: Option<&luxe_core::guided_review::SeenReview>,
|
||||
app: &App,
|
||||
) -> Line<'static> {
|
||||
let styles = &app.theme_styles;
|
||||
let path = row.path();
|
||||
let hovered = matches!(
|
||||
app.pointer.hover.as_ref(),
|
||||
Some(crate::mouse::MouseTarget::DockFile(hovered) | crate::mouse::MouseTarget::DockFolder(hovered))
|
||||
if Some(hovered.as_str()) == path
|
||||
);
|
||||
let keyed = app.files.focused && app.files.cursor.as_deref() == path && path.is_some();
|
||||
// The band is where the pointer or the keyboard is; the file showing in the preview says so
|
||||
// in its name instead, so the two never look alike when they are on different rows
|
||||
let highlight = hovered || keyed;
|
||||
let showing = path.is_some() && path == open;
|
||||
|
||||
let cells = match row {
|
||||
TreeRow::Note { depth, text } => TreeCells {
|
||||
depth: *depth,
|
||||
lead: TreeLead::Bare,
|
||||
name: text.clone(),
|
||||
name_style: styles.dim,
|
||||
right: Vec::new(),
|
||||
},
|
||||
// What `.gitignore` ignores is drawn faint, since it is there only because it was asked for
|
||||
TreeRow::Folder { name, depth, open: unfolded, holds_change, ignored, .. } => TreeCells {
|
||||
depth: *depth,
|
||||
lead: TreeLead::Folder { open: *unfolded },
|
||||
name: name.clone(),
|
||||
name_style: match ignored {
|
||||
true => styles.dim,
|
||||
false => styles.text.add_modifier(Modifier::BOLD),
|
||||
},
|
||||
right: match *holds_change && !*unfolded {
|
||||
true => vec![(" •".to_string(), styles.warning)],
|
||||
false => Vec::new(),
|
||||
},
|
||||
},
|
||||
TreeRow::File { name, depth, change, ignored, .. } => {
|
||||
let (name_style, right) = match change {
|
||||
Some(change) => {
|
||||
let reviewed = seen.is_some_and(|seen| {
|
||||
seen.covers_file(
|
||||
&change.path,
|
||||
change.additions.unwrap_or_default(),
|
||||
change.deletions.unwrap_or_default(),
|
||||
)
|
||||
});
|
||||
change_cells(
|
||||
change.status,
|
||||
change.additions,
|
||||
change.deletions,
|
||||
reviewed,
|
||||
styles,
|
||||
)
|
||||
}
|
||||
None if *ignored => (styles.dim, Vec::new()),
|
||||
None => (styles.text, Vec::new()),
|
||||
};
|
||||
TreeCells {
|
||||
depth: *depth,
|
||||
lead: TreeLead::File { name, faint: *ignored },
|
||||
name: name.clone(),
|
||||
name_style: match showing {
|
||||
true => styles.accent.add_modifier(Modifier::BOLD),
|
||||
false => name_style,
|
||||
},
|
||||
right,
|
||||
}
|
||||
}
|
||||
};
|
||||
tree_line(cells, width, highlight, app)
|
||||
}
|
||||
|
||||
/// What a tree row draws, whichever list it sits in: FILES' tree, or a place under ELSEWHERE.
|
||||
pub(super) struct TreeCells<'a> {
|
||||
/// Levels under the list's top, one `│ ` guide each
|
||||
pub(super) depth: usize,
|
||||
pub(super) lead: TreeLead<'a>,
|
||||
pub(super) name: String,
|
||||
pub(super) name_style: ratatui::style::Style,
|
||||
/// What sits at the right edge, after the name has given way
|
||||
pub(super) right: Vec<(String, ratatui::style::Style)>,
|
||||
}
|
||||
|
||||
/// What comes between a row's guides and its name.
|
||||
pub(super) enum TreeLead<'a> {
|
||||
/// A chevron and a folder
|
||||
Folder { open: bool },
|
||||
/// The chevron's cells left blank, then the language mark for the file `name`
|
||||
File { name: &'a str, faint: bool },
|
||||
/// Nothing: a note stands where entries would
|
||||
Bare,
|
||||
}
|
||||
|
||||
/// A changed file's name style and what its row says on the right: `+6 −0 M`.
|
||||
///
|
||||
/// A file with no counts prints none. Git says nothing about a binary blob, and rendering that
|
||||
/// silence as `+0 −0` claims the file did not change, which is worse than saying nothing. A file
|
||||
/// already looked at recedes, and keeps its counts so the reader can still see how big it was.
|
||||
pub(super) fn change_cells(
|
||||
status: luxe_core::workspace::FileChangeStatus,
|
||||
additions: Option<u64>,
|
||||
deletions: Option<u64>,
|
||||
reviewed: bool,
|
||||
styles: &crate::theme::styles::ThemeStyles,
|
||||
) -> (ratatui::style::Style, Vec<(String, ratatui::style::Style)>) {
|
||||
let mut right = Vec::new();
|
||||
if let (Some(additions), Some(deletions)) = (additions, deletions) {
|
||||
right.push((format!(" +{additions}"), styles.success));
|
||||
right.push((format!(" −{deletions}"), styles.error));
|
||||
}
|
||||
let (marker, marker_style) = status_mark(status, styles);
|
||||
right.push((format!(" {marker}"), marker_style));
|
||||
(if reviewed { styles.dim } else { marker_style }, right)
|
||||
}
|
||||
|
||||
/// Draws a [`TreeCells`]: guides, lead, the name elided to fit, and the right edge.
|
||||
pub(super) fn tree_line(
|
||||
cells: TreeCells<'_>,
|
||||
width: usize,
|
||||
highlight: bool,
|
||||
app: &App,
|
||||
) -> Line<'static> {
|
||||
let styles = &app.theme_styles;
|
||||
let tool_bg = styles.tool_bg;
|
||||
let ink = |base: ratatui::style::Style| match highlight {
|
||||
true => base.patch(tool_bg).patch(styles.selected_bg),
|
||||
false => base.patch(tool_bg),
|
||||
};
|
||||
let mut left = vec![Span::styled("│ ".repeat(cells.depth), styles.border.patch(tool_bg))];
|
||||
let elide = match cells.lead {
|
||||
TreeLead::Folder { open } => {
|
||||
left.push(Span::styled(if open { "▾ " } else { "▸ " }, ink(styles.muted)));
|
||||
left.push(Span::styled(
|
||||
icon_label(Icon::Folder.glyph(), ""),
|
||||
ink(styles.accent_secondary),
|
||||
));
|
||||
true
|
||||
}
|
||||
TreeLead::File { name, faint } => {
|
||||
let extension = name.rsplit_once('.').map_or("", |(_, extension)| extension);
|
||||
let icon = crate::widgets::language_icon(&extension.to_ascii_lowercase());
|
||||
// A language the tier has no mark for keeps the mark's cells, so a file's name lines
|
||||
// up with its neighbors' whatever the font can draw
|
||||
let column = icon_cells(Icon::Folder.glyph());
|
||||
let mark = format!("{:<column$}", icon_label(icon.glyph(), ""));
|
||||
let mark_style = match faint {
|
||||
true => styles.dim,
|
||||
false => crate::widgets::language_hue(icon, styles),
|
||||
};
|
||||
left.push(Span::raw(" "));
|
||||
left.push(Span::styled(mark, ink(mark_style)));
|
||||
true
|
||||
}
|
||||
TreeLead::Bare => false,
|
||||
};
|
||||
left.push(Span::styled(cells.name, ink(cells.name_style)));
|
||||
let right: Vec<Span<'static>> =
|
||||
cells.right.into_iter().map(|(text, style)| Span::styled(text, ink(style))).collect();
|
||||
|
||||
// The name is the one part that gives way: elided in the middle, so the extension survives
|
||||
let fixed: usize =
|
||||
left[..left.len() - 1].iter().map(|span| span.content.width()).sum::<usize>()
|
||||
+ right.iter().map(|span| span.content.width()).sum::<usize>();
|
||||
let budget = width.saturating_sub(fixed + crate::widgets::SELECTION_FRAME);
|
||||
if let Some(name) = left.last_mut() {
|
||||
name.content = match elide {
|
||||
true => crate::widgets::truncate_middle(&name.content, budget).into(),
|
||||
false => truncate_cells(&name.content, budget).into(),
|
||||
};
|
||||
}
|
||||
let used: usize = left.iter().chain(&right).map(|span| span.content.width()).sum();
|
||||
let pad = width.saturating_sub(used + crate::widgets::SELECTION_FRAME);
|
||||
left.push(Span::styled(" ".repeat(pad), ink(styles.text)));
|
||||
left.extend(right);
|
||||
crate::widgets::selection_row_on(
|
||||
left,
|
||||
width,
|
||||
0,
|
||||
highlight,
|
||||
tool_bg.bg.unwrap_or(styles.slab.canvas),
|
||||
styles,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user