use super::common::PaginatedViewState;
use super::theme;
use iced::advanced::layout::{self, Layout};
use iced::advanced::overlay;
use iced::advanced::renderer;
use iced::advanced::text::{IntoFragment, Span};
use iced::advanced::widget::Operation;
use iced::advanced::widget::tree::{self, Tree};
use iced::advanced::{Clipboard, Shell, Widget};
use iced::mouse;
use iced::widget::{
self, Column, Row, Space, button, column, container, mouse_area, row, scrollable, stack, text,
tooltip,
};
use iced::{
Alignment, Color, Element, Event, Length, Padding, Point, Rectangle, Size, Task, Vector,
};
use iced_fonts::lucide;
use std::borrow::Cow;
use std::collections::HashSet;
use std::path::Path;
use std::time::{Duration, Instant};
#[derive(Debug, Clone)]
pub struct PickOption {
pub value: String,
pub label: String,
}
impl PartialEq for PickOption {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl Eq for PickOption {}
impl std::fmt::Display for PickOption {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.label)
}
}
#[must_use]
pub fn page<'a, Message: 'a>(content: impl Into<Element<'a, Message>>) -> Element<'a, Message> {
container(content)
.width(Length::Fill)
.height(Length::Fill)
.padding(theme::PAGE_PADDING)
.style(theme::base_container_style)
.into()
}
#[must_use]
pub fn page_bare<'a, Message: 'a>(
content: impl Into<Element<'a, Message>>,
) -> Element<'a, Message> {
container(content)
.width(Length::Fill)
.height(Length::Fill)
.style(theme::base_container_style)
.into()
}
#[must_use]
pub fn page_with_dialog<'a, Message: 'a>(
content: impl Into<Element<'a, Message>>,
dialog: Element<'a, Message>,
) -> Element<'a, Message> {
stack([page(content), dialog]).into()
}
#[must_use]
pub fn no_dialog<'a, Message: 'a>() -> Element<'a, Message> {
stack([empty_stack_placeholder()]).into()
}
fn editor_field_style(border_color: Color) -> impl Fn(&iced::Theme) -> container::Style {
move |_theme: &iced::Theme| theme::container_style(theme::BG_ELEVATED, 4.0, 1.0, border_color)
}
#[expect(clippy::too_many_arguments)] fn editor_field<'a, M: 'a>(
buffer: &'a super::editor_widget::EditorBuffer,
placeholder: &'a str,
enter: super::editor_widget::EnterBehavior,
masked: bool,
border_color: Color,
width: Length,
id: Option<iced::widget::Id>,
on_action: impl Fn(super::editor_widget::EditorAction) -> M + 'a,
) -> Element<'a, M> {
let mut editor = super::editor_widget::EditorWidget::new(buffer)
.single_line(true)
.masked(masked)
.show_gutter(false)
.code_mode(false)
.enter(enter)
.placeholder(placeholder)
.padding(theme::PAD_5)
.background(Some(theme::BG_ELEVATED))
.keyboard_passthrough(super::is_dashboard_shortcut);
if let Some(id) = id {
editor = editor.id(id);
}
let element = iced::Element::new(editor).map(on_action);
container(element)
.width(width)
.style(editor_field_style(border_color))
.into()
}
#[must_use]
pub fn single_line_editor<'a, M: 'a>(
buffer: &'a super::editor_widget::EditorBuffer,
placeholder: &'a str,
submit_on_enter: bool,
width: Length,
id: Option<iced::widget::Id>,
on_action: impl Fn(super::editor_widget::EditorAction) -> M + 'a,
) -> Element<'a, M> {
let enter = if submit_on_enter {
super::editor_widget::EnterBehavior::Submit
} else {
super::editor_widget::EnterBehavior::Newline
};
editor_field(
buffer,
placeholder,
enter,
false,
theme::BORDER_STRONG,
width,
id,
on_action,
)
}
#[must_use]
#[expect(clippy::too_many_arguments)]
pub fn password_field_editor<'a, M: Clone + 'a>(
buffer: &'a super::editor_widget::EditorBuffer,
placeholder: &'a str,
show: bool,
width: Length,
highlight: bool,
id: Option<iced::widget::Id>,
on_action: impl Fn(super::editor_widget::EditorAction) -> M + 'a,
on_toggle: M,
) -> Element<'a, M> {
let border_color = if highlight {
theme::ACCENT
} else {
theme::BORDER_STRONG
};
let field = editor_field(
buffer,
placeholder,
super::editor_widget::EnterBehavior::Submit,
!show,
border_color,
width,
id,
on_action,
);
let eye_icon: Element<'_, M> = if show {
lucide::eye_off::<iced::Theme, iced::Renderer>()
.size(theme::TEXT_14)
.color(theme::TEXT_MUTED)
.into()
} else {
lucide::eye::<iced::Theme, iced::Renderer>()
.size(theme::TEXT_14)
.color(theme::TEXT_MUTED)
.into()
};
let toggle = button(eye_icon)
.padding(theme::PAD_2)
.style(theme::button_secondary)
.on_press(on_toggle);
row![field, Space::new().width(theme::SPACE_4), toggle]
.align_y(Alignment::Center)
.into()
}
fn error_banner_body<'a, Message: 'a>(err: &'a str) -> container::Container<'a, Message> {
container(text(err).size(theme::TEXT_13).color(theme::STATUS_ERROR))
.padding(theme::PAD_8)
.style(theme::pill_style(theme::STATUS_ERROR.scale_alpha(0.08)))
}
#[must_use]
pub fn error_banner<'a, Message: 'a>(err: &'a str) -> Element<'a, Message> {
error_banner_body(err).into()
}
#[must_use]
pub fn error_banner_fill<'a, Message: 'a>(err: &'a str) -> Element<'a, Message> {
error_banner_body(err).width(Length::Fill).into()
}
#[must_use]
pub fn loading_text<'a, Message: 'a>() -> Element<'a, Message> {
text("Loading\u{2026}")
.size(theme::TEXT_14)
.color(theme::TEXT_MUTED)
.into()
}
#[must_use]
pub fn push_error_banner<'a, Message: 'a>(
col: Column<'a, Message>,
err: Option<&'a str>,
) -> Column<'a, Message> {
push_banner(col, err, false)
}
#[must_use]
pub fn push_error_banner_inset<'a, Message: 'a>(
col: Column<'a, Message>,
err: Option<&'a str>,
) -> Column<'a, Message> {
push_banner(col, err, true)
}
fn push_banner<'a, Message: 'a>(
mut col: Column<'a, Message>,
err: Option<&'a str>,
inset: bool,
) -> Column<'a, Message> {
if let Some(err) = err {
let banner = error_banner(err);
col = col.push(if inset {
scroll_h_inset(banner)
} else {
banner
});
col = col.push(Space::new().height(8));
}
col
}
#[must_use]
pub fn scroll_h_inset<'a, Message: 'a>(
content: impl Into<Element<'a, Message>>,
) -> Element<'a, Message> {
container(content.into())
.padding([0.0, SCROLL_H_PAD])
.into()
}
#[must_use]
pub fn empty_state_placeholder<'a, Message: 'a>(
icon: iced::widget::Text<'a, iced::Theme, iced::Renderer>,
label: &'a str,
accent: iced::Color,
) -> Element<'a, Message> {
container(
column![
icon.size(48).color(accent),
text(label).size(theme::TEXT_14).color(accent),
]
.spacing(theme::SPACE_12)
.align_x(Alignment::Center),
)
.width(Length::Fill)
.height(Length::Fill)
.center_x(Length::Fill)
.center_y(Length::Fill)
.into()
}
#[must_use]
pub fn paginated_body<'a, T, Message: 'a>(
state: &'a PaginatedViewState<T>,
empty_icon: iced::widget::Text<'a, iced::Theme, iced::Renderer>,
empty_label: &'a str,
row: impl Fn(&'a T) -> Element<'a, Message>,
) -> Element<'a, Message> {
let mut content = push_error_banner_inset(Column::new(), state.load_state.error());
if state.load_state.loading() && !state.load_state.has_loaded() {
content = content.push(scroll_h_inset(loading_text()));
} else if state.entries.is_empty() {
content = content.push(empty_state_placeholder(
empty_icon,
empty_label,
theme::TEXT_MUTED,
));
} else {
content = content.push(vscroll(
Column::with_children(state.entries.iter().map(row).collect::<Vec<_>>())
.spacing(theme::SPACE_2),
));
}
page(content)
}
#[derive(Debug, Clone, Copy)]
pub struct PillMetrics {
pub text_size: f32,
pub padding: [f32; 2], }
pub const PILL_COMPACT: PillMetrics = PillMetrics {
text_size: theme::TEXT_10,
padding: [theme::PAD_1, theme::PAD_6],
};
pub const PILL_MODAL: PillMetrics = PillMetrics {
text_size: theme::TEXT_12,
padding: [theme::PAD_2, theme::PAD_8],
};
#[must_use]
pub fn badge_pill<'a, Message: 'a>(
label: String,
colors: (Color, Color),
metrics: PillMetrics,
) -> Element<'a, Message> {
container(
text(label)
.size(metrics.text_size)
.color(colors.0)
.wrapping(iced::widget::text::Wrapping::None),
)
.padding(metrics.padding)
.style(theme::pill_style(colors.1))
.into()
}
#[must_use]
pub fn section_heading<'a>(
title: impl Into<String>,
) -> iced::widget::Text<'a, iced::Theme, iced::Renderer> {
text(title.into())
.font(theme::JETBRAINS_MONO)
.size(theme::TEXT_16)
.color(theme::TEXT_SECONDARY)
}
#[must_use]
pub fn section_subheading<'a>(
title: impl Into<String>,
) -> iced::widget::Text<'a, iced::Theme, iced::Renderer> {
text(title.into())
.font(theme::JETBRAINS_MONO)
.size(theme::TEXT_13)
.color(theme::TEXT_SECONDARY)
}
pub const ACTION_ICON_SIZE: f32 = theme::TEXT_16;
#[must_use]
pub fn icon_tooltip_button<'a, Message>(
icon: impl Into<Element<'a, Message>>,
tooltip_text: impl Into<Cow<'a, str>>,
on_press: Option<Message>,
padding: impl Into<Padding>,
style: impl Fn(&iced::Theme, iced::widget::button::Status) -> iced::widget::button::Style + 'a,
position: tooltip::Position,
) -> Element<'a, Message>
where
Message: Clone + 'a,
{
tooltip(
button(icon)
.style(style)
.padding(padding)
.on_press_maybe(on_press),
text(tooltip_text.into()).size(theme::TEXT_11),
position,
)
.style(theme::tooltip_style)
.into()
}
#[must_use]
pub(crate) fn tooltip_hint<'a, Message: Clone + 'a>(
content: impl Into<Element<'a, Message>>,
label: impl Into<Cow<'a, str>>,
) -> Element<'a, Message> {
tooltip(
content,
text(label.into()).size(theme::TEXT_11),
tooltip::Position::Top,
)
.style(theme::tooltip_style)
.into()
}
#[must_use]
pub fn compact_x_button<'a, Message: Clone + 'a>(
color: Color,
size: f32,
padding: impl Into<Padding>,
on_press: Option<Message>,
tooltip_text: Option<&'a str>,
) -> Element<'a, Message> {
let glyph =
lucide::x::<iced::Theme, iced::Renderer>()
.size(size)
.color(if on_press.is_some() {
color
} else {
theme::TEXT_MUTED
});
match tooltip_text {
Some(tooltip_text) => icon_tooltip_button(
glyph,
tooltip_text,
on_press,
padding,
theme::button_text,
tooltip::Position::Top,
),
None => button(glyph)
.padding(padding)
.style(theme::button_text)
.on_press_maybe(on_press)
.into(),
}
}
#[must_use]
pub fn ghost_icon_button<Message: 'static + Clone>() -> Element<'static, Message> {
container(
button(lucide::circle_check::<iced::Theme, iced::Renderer>().size(ACTION_ICON_SIZE))
.padding(button::DEFAULT_PADDING),
)
.width(0)
.clip(true)
.into()
}
pub fn selectable_text<'a, Message: 'a>(
content: impl IntoFragment<'a>,
color: Color,
) -> super::selectable::Selectable<'a, (), Message, iced::Theme, iced::Renderer> {
super::selectable::rich_text([Span::new(content)]).style(move |_theme| {
super::selectable::Style {
color: Some(color),
selection: theme::ACCENT_DIM,
}
})
}
#[must_use]
pub fn tab_close_button<'a, Message: Clone + 'a>(
is_active: bool,
on_press: Message,
) -> widget::Button<'a, Message> {
widget::button(
lucide::x::<iced::Theme, iced::Renderer>()
.size(theme::TEXT_12)
.color(if is_active {
theme::TEXT_SECONDARY
} else {
theme::TEXT_FAINT
}),
)
.on_press(on_press)
.style(theme::button_transparent)
.padding(0)
}
pub const SCROLL_H_PAD: f32 = 8.0;
#[must_use]
pub fn tab_scrollable<'a, Message: 'a>(
tab_buttons: Vec<Element<'a, Message>>,
scroll_id: Option<widget::Id>,
on_scroll: Option<impl Fn(scrollable::Viewport) -> Message + 'a>,
) -> Element<'a, Message> {
container(hscroll(
row(tab_buttons).spacing(0).width(Length::Fill),
scroll_id,
on_scroll,
))
.style(theme::surface_container_style)
.width(Length::Fill)
.into()
}
#[must_use]
pub fn vscroll<'a, Message: 'a>(content: impl Into<Element<'a, Message>>) -> Element<'a, Message> {
vscroll_sized(content, Length::Fill, Length::Fill)
}
#[must_use]
pub fn vscroll_sized<'a, Message: 'a>(
content: impl Into<Element<'a, Message>>,
width: Length,
height: Length,
) -> Element<'a, Message> {
vscroll_base(content, width, height).into()
}
#[must_use]
pub fn vscroll_tracked<'a, Message: 'a>(
content: impl Into<Element<'a, Message>>,
width: Length,
height: Length,
id: widget::Id,
on_scroll: impl Fn(scrollable::Viewport) -> Message + 'a,
) -> Element<'a, Message> {
vscroll_base(content, width, height)
.id(id)
.on_scroll(on_scroll)
.into()
}
fn vscroll_base<'a, Message: 'a>(
content: impl Into<Element<'a, Message>>,
width: Length,
height: Length,
) -> widget::Scrollable<'a, Message, iced::Theme, iced::Renderer> {
scrollable(
container(content.into())
.width(Length::Fill)
.padding([0.0, SCROLL_H_PAD]),
)
.width(width)
.height(height)
.direction(theme::vertical_scrollbar())
.style(theme::scrollbar_style)
}
fn hscroll<'a, Message: 'a>(
content: impl Into<Element<'a, Message>>,
id: Option<widget::Id>,
on_scroll: Option<impl Fn(scrollable::Viewport) -> Message + 'a>,
) -> Element<'a, Message> {
let mut sc = scrollable(container(content.into()).width(Length::Fill))
.width(Length::Fill)
.height(Length::Shrink)
.direction(theme::horizontal_scrollbar())
.style(theme::scrollbar_style);
if let Some(id) = id {
sc = sc.id(id);
}
if let Some(on_scroll) = on_scroll {
sc = sc.on_scroll(on_scroll);
}
sc.into()
}
pub const CHAT_VERTICAL_RHYTHM: f32 = 8.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BubbleSide {
Left,
Right,
}
#[must_use]
pub(crate) fn align_bubble<'a, Msg: 'a>(
element: impl Into<Element<'a, Msg>>,
side: BubbleSide,
) -> Element<'a, Msg> {
let element = element.into();
match side {
BubbleSide::Left => row![element, Space::new().width(Length::FillPortion(1))].into(),
BubbleSide::Right => row![Space::new().width(Length::FillPortion(1)), element].into(),
}
}
pub struct ChatComposerOptions<'a, M> {
pub sending: bool,
pub min_height: f32,
pub max_height: f32,
pub controls: Vec<Element<'a, M>>,
pub grey_on_empty: bool,
pub send_tooltip: &'a str,
pub id: Option<iced::widget::Id>,
pub attachments_on_paste: bool,
}
#[must_use]
pub fn chat_composer<'a, M: Clone + 'a>(
content: &'a super::editor_widget::EditorBuffer,
on_action: impl Fn(super::editor_widget::EditorAction) -> M + 'a,
send_msg: M,
placeholder: &'a str,
options: ChatComposerOptions<'a, M>,
) -> Element<'a, M> {
let send_msg_btn = send_msg.clone();
let mut editor = super::editor_widget::EditorWidget::new(content)
.show_gutter(false)
.code_mode(false)
.enter(super::editor_widget::EnterBehavior::Submit)
.placeholder(placeholder)
.min_height(options.min_height)
.max_height(options.max_height)
.padding(theme::PAD_5)
.background(Some(theme::BG_ELEVATED))
.attachments_on_paste(options.attachments_on_paste)
.keyboard_passthrough(super::is_dashboard_shortcut);
if let Some(id) = options.id {
editor = editor.id(id);
}
let input_editor: Element<'a, M> =
container(iced::Element::new(editor).map(move |action| match action {
super::editor_widget::EditorAction::Submit => send_msg.clone(),
other => on_action(other),
}))
.width(Length::Fill)
.height(Length::Shrink)
.into();
let send_disabled =
options.sending || (options.grey_on_empty && content.text().trim().is_empty());
let send_btn = icon_tooltip_button(
lucide::send_horizontal::<iced::Theme, iced::Renderer>()
.size(theme::composer_icon(theme::TEXT_14))
.color(if send_disabled {
theme::TEXT_MUTED
} else {
theme::ACCENT
}),
options.send_tooltip,
if send_disabled {
None
} else {
Some(send_msg_btn)
},
4,
theme::icon_button_style(send_disabled),
tooltip::Position::Top,
);
let mut toolbar = Row::new()
.spacing(theme::SPACE_6)
.align_y(Alignment::Center);
toolbar = toolbar.push(Space::new().width(Length::Fill));
for c in options.controls {
toolbar = toolbar.push(c);
}
toolbar = toolbar.push(send_btn);
container(column![input_editor, toolbar].spacing(theme::SPACE_6))
.padding(theme::PAD_10)
.style(theme::bubble_style(
theme::BG_ELEVATED,
Some(theme::TEXT_PRIMARY),
))
.width(Length::Fill)
.into()
}
#[must_use]
pub fn diff_stats_row<'a, Message: 'a>(added: i64, removed: i64, size: f32) -> Row<'a, Message> {
let mut parts: Vec<Element<'a, Message>> = Vec::new();
if added > 0 {
parts.push(
text(format!("+{added}"))
.size(size)
.color(theme::STATUS_SUCCESS)
.into(),
);
}
if added > 0 && removed > 0 {
parts.push(text("/").size(size).color(theme::TEXT_MUTED).into());
}
if removed > 0 {
parts.push(
text(format!("\u{2212}{removed}"))
.size(size)
.color(theme::STATUS_ERROR)
.into(),
);
}
Row::with_children(parts)
.spacing(0)
.align_y(Alignment::Center)
}
#[must_use]
pub fn git_footer_stats<'a, Message: 'a>(
added: i64,
removed: i64,
huge_binary_file_count: usize,
omitted_file_count: usize,
size: f32,
) -> Option<Row<'a, Message>> {
if added == 0 && removed == 0 && huge_binary_file_count == 0 && omitted_file_count == 0 {
return None;
}
let mut parts: Vec<Element<'a, Message>> = Vec::new();
if added != 0 || removed != 0 {
parts.push(diff_stats_row::<Message>(added, removed, size).into());
}
if huge_binary_file_count > 0 {
parts.push(
lucide::files::<iced::Theme, iced::Renderer>()
.size(size)
.color(theme::TEXT_MUTED)
.into(),
);
parts.push(
text(format!("{huge_binary_file_count} files"))
.size(size)
.color(theme::TEXT_SECONDARY)
.into(),
);
}
if omitted_file_count > 0 {
parts.push(
lucide::triangle_alert::<iced::Theme, iced::Renderer>()
.size(size)
.color(theme::STATUS_WARNING)
.into(),
);
parts.push(
text(format!("{omitted_file_count} left out"))
.size(size)
.color(theme::STATUS_WARNING)
.into(),
);
}
Some(
Row::with_children(parts)
.spacing(theme::SPACE_3)
.align_y(Alignment::Center),
)
}
pub async fn debounce_sleep(ms: u64, generation: u64) -> u64 {
tokio::time::sleep(Duration::from_millis(ms)).await;
generation
}
#[derive(Debug, Clone)]
pub struct TreeNode {
pub name: String,
pub full_path: String,
pub is_dir: bool,
pub children: Vec<TreeNode>,
pub error: Option<String>,
pub ignored: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TreeNavDirection {
Up,
Down,
}
pub struct FileTree {
pub nodes: Vec<TreeNode>,
pub expanded_dirs: HashSet<String>,
pub tree_focused: bool,
pub tree_focus_index: usize,
pub visible_tree_nodes: Vec<(String, bool)>,
pub tree_scroll_id: iced::widget::Id,
pub scroll_y: f32,
pub viewport_h: Option<f32>,
}
impl FileTree {
#[must_use]
pub fn new(scroll_id: iced::widget::Id) -> Self {
Self {
nodes: Vec::new(),
expanded_dirs: HashSet::new(),
tree_focused: false,
tree_focus_index: 0,
visible_tree_nodes: Vec::new(),
tree_scroll_id: scroll_id,
scroll_y: 0.0,
viewport_h: None,
}
}
pub fn rebuild_visible(&mut self) {
self.visible_tree_nodes.clear();
Self::flatten_tree_nodes(
&self.nodes,
&self.expanded_dirs,
&mut self.visible_tree_nodes,
);
if self.visible_tree_nodes.is_empty() {
self.tree_focus_index = 0;
} else {
self.tree_focus_index = self.tree_focus_index.min(self.visible_tree_nodes.len() - 1);
}
}
#[must_use]
fn nav_up(&mut self) -> bool {
if self.tree_focused && self.tree_focus_index > 0 {
self.tree_focus_index -= 1;
true
} else {
false
}
}
#[must_use]
fn nav_down(&mut self) -> bool {
if self.tree_focused && self.tree_focus_index + 1 < self.visible_tree_nodes.len() {
self.tree_focus_index += 1;
true
} else {
false
}
}
fn flatten_tree_nodes(
nodes: &[TreeNode],
expanded: &HashSet<String>,
out: &mut Vec<(String, bool)>,
) {
for node in nodes {
out.push((node.full_path.clone(), node.is_dir));
if node.is_dir && expanded.contains(&node.full_path) && !node.children.is_empty() {
Self::flatten_tree_nodes(&node.children, expanded, out);
}
}
}
pub fn sort_nodes(nodes: &mut [TreeNode]) {
nodes.sort_by(|a, b| {
if a.is_dir != b.is_dir {
return b.is_dir.cmp(&a.is_dir);
}
a.name.to_lowercase().cmp(&b.name.to_lowercase())
});
for node in nodes {
Self::sort_nodes(&mut node.children);
}
}
pub fn focus_path(&mut self, path: &str) -> Option<usize> {
let pos = self
.visible_tree_nodes
.iter()
.position(|(p, _)| p == path)?;
self.tree_focus_index = pos;
Some(pos)
}
pub fn expand_dir_and_focus_first_child<Message: 'static>(
&mut self,
path: &str,
) -> Task<Message> {
debug_assert!(
self.expanded_dirs.contains(path),
"expand_dir_and_focus_first_child: path must be in expanded_dirs before calling"
);
self.rebuild_visible();
if let Some(dir_idx) = self.focus_path(path) {
if dir_idx + 1 < self.visible_tree_nodes.len() {
self.tree_focus_index = dir_idx + 1;
return scroll_to_tree_focus(self, ScrollMode::SnapToTop);
}
}
Task::none()
}
pub fn collapse_dir_and_keep_focus<Message: 'static>(&mut self, path: &str) -> Task<Message> {
debug_assert!(
!self.expanded_dirs.contains(path),
"collapse_dir_and_keep_focus: path must have been removed from expanded_dirs \
before calling"
);
self.rebuild_visible();
if self.focus_path(path).is_some() {
return scroll_to_tree_focus(self, ScrollMode::SnapToTop);
}
Task::none()
}
pub fn focus_parent<Message: 'static>(&mut self) -> Task<Message> {
match self.focused_parent_path() {
Some(ref p) if self.focus_path(p).is_some() => {
scroll_to_tree_focus(self, ScrollMode::SnapToTop)
}
_ => Task::none(),
}
}
pub fn focus_next_row<Message: 'static>(&mut self, idx: usize) -> Task<Message> {
if idx + 1 < self.visible_tree_nodes.len() {
self.tree_focus_index = idx + 1;
scroll_to_tree_focus(self, ScrollMode::SnapToTop)
} else {
Task::none()
}
}
pub fn nav_and_scroll<Message: 'static>(
&mut self,
direction: TreeNavDirection,
) -> Task<Message> {
let moved = match direction {
TreeNavDirection::Up => self.nav_up(),
TreeNavDirection::Down => self.nav_down(),
};
if moved {
scroll_to_tree_focus(self, ScrollMode::ScrollIntoView)
} else {
Task::none()
}
}
#[must_use]
pub fn focused_tree_node(&self) -> Option<(usize, String, bool)> {
if !self.tree_focused || self.visible_tree_nodes.is_empty() {
return None;
}
let idx = self.tree_focus_index.min(self.visible_tree_nodes.len() - 1);
let path = self.visible_tree_nodes[idx].0.clone();
let is_dir = self.visible_tree_nodes[idx].1;
Some((idx, path, is_dir))
}
#[must_use]
pub fn focused_is_expanded_dir(&self) -> bool {
self.focused_tree_node()
.is_some_and(|(_, ref path, is_dir)| is_dir && self.expanded_dirs.contains(path))
}
#[must_use]
fn focused_parent_path(&self) -> Option<String> {
let (_idx, path, _is_dir) = self.focused_tree_node()?;
let parent = Path::new(&path).parent()?;
let parent_str = parent.to_string_lossy().to_string();
if parent_str.is_empty() {
None
} else {
Some(parent_str)
}
}
}
pub const TREE_FONT_SIZE: f32 = 14.0;
pub const TREE_ICON_SIZE: f32 = 15.0;
pub const TREE_MIN_WIDTH: f32 = 260.0;
pub const TREE_MAX_WIDTH: f32 = 400.0;
const JETBRAINS_MONO_ADVANCE: f32 = 0.6;
const LUCIDE_ADVANCE: f32 = 1.0;
#[must_use]
#[expect(clippy::cast_precision_loss)] fn mono_text_width(chars: usize, size: f32) -> f32 {
chars as f32 * size * JETBRAINS_MONO_ADVANCE
}
#[must_use]
pub fn tree_row_natural_width(
guide_chars: usize,
icon_size: f32,
name: &str,
name_size: f32,
name_suffix: Option<(&str, f32)>,
counts: Option<(&str, &str)>,
) -> f32 {
let mut w = mono_text_width(guide_chars, TREE_FONT_SIZE)
+ icon_size * LUCIDE_ADVANCE
+ 4.0
+ mono_text_width(name.chars().count(), name_size);
if let Some((suffix, size)) = name_suffix {
w += 4.0 + mono_text_width(suffix.chars().count(), size);
}
if let Some((add, rem)) = counts {
let counts_chars = if add.is_empty() {
rem.chars().count()
} else if rem.is_empty() {
add.chars().count()
} else {
add.chars().count() + 1 + rem.chars().count()
};
w += mono_text_width(counts_chars, 10.0) + 6.0;
}
w
}
pub fn collect_tree_row_widths(
nodes: &[TreeNode],
expanded: &HashSet<String>,
row_width: impl Fn(&TreeNode, usize) -> f32,
) -> Vec<f32> {
fn walk(
nodes: &[TreeNode],
expanded: &HashSet<String>,
row_width: &impl Fn(&TreeNode, usize) -> f32,
depth: usize,
out: &mut Vec<f32>,
) {
for node in nodes {
out.push(row_width(node, depth));
if node.is_dir && expanded.contains(&node.full_path) {
walk(&node.children, expanded, row_width, depth + 1, out);
}
}
}
let mut out = Vec::new();
walk(nodes, expanded, &row_width, 0, &mut out);
out
}
#[must_use]
#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)] fn tree_panel_width(file_tree: &FileTree, row_widths: &[f32]) -> f32 {
let widest = match file_tree.viewport_h {
Some(viewport_h) if viewport_h > 0.0 => {
let row_h = ESTIMATED_TREE_ROW_HEIGHT;
let first = (file_tree.scroll_y / row_h).floor().max(0.0) as usize;
let last = ((file_tree.scroll_y + viewport_h) / row_h).ceil() as usize + 1;
row_widths
.iter()
.enumerate()
.skip(first.saturating_sub(1))
.take(last - first + 2)
.map(|(_, w)| *w)
.fold(0.0f32, f32::max)
}
_ => row_widths.iter().copied().fold(0.0f32, f32::max),
};
(widest + 2.0 * SCROLL_H_PAD).clamp(TREE_MIN_WIDTH, TREE_MAX_WIDTH)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ScrollMode {
SnapToTop,
ScrollIntoView,
}
const ESTIMATED_TREE_ROW_HEIGHT: f32 = TREE_ICON_SIZE * 1.3;
#[expect(clippy::cast_precision_loss)]
fn scroll_to_tree_focus<Message: 'static>(
file_tree: &mut FileTree,
mode: ScrollMode,
) -> Task<Message> {
if file_tree.visible_tree_nodes.is_empty() {
return Task::none();
}
let focus_y = file_tree.tree_focus_index as f32 * ESTIMATED_TREE_ROW_HEIGHT;
match mode {
ScrollMode::SnapToTop => absolute_scroll_to(file_tree, focus_y),
ScrollMode::ScrollIntoView => match file_tree.viewport_h {
None => {
absolute_scroll_to(file_tree, focus_y)
}
Some(viewport_h) => {
let row_bottom = focus_y + ESTIMATED_TREE_ROW_HEIGHT;
let viewport_bottom = file_tree.scroll_y + viewport_h;
if row_bottom <= file_tree.scroll_y {
absolute_scroll_to(file_tree, focus_y)
} else if focus_y >= viewport_bottom {
file_tree.scroll_y = (file_tree.scroll_y + ESTIMATED_TREE_ROW_HEIGHT).max(0.0);
iced::widget::operation::scroll_by(
file_tree.tree_scroll_id.clone(),
iced::widget::operation::AbsoluteOffset {
x: 0.0,
y: ESTIMATED_TREE_ROW_HEIGHT,
},
)
} else {
Task::none()
}
}
},
}
}
fn absolute_scroll_to<Message: 'static>(file_tree: &mut FileTree, y: f32) -> Task<Message> {
file_tree.scroll_y = y.max(0.0);
iced::widget::operation::scroll_to(
file_tree.tree_scroll_id.clone(),
iced::widget::operation::AbsoluteOffset { x: 0.0, y },
)
}
pub fn build_tree_panel<'a, Message: 'a>(
file_tree: &'a FileTree,
tree_rows: Vec<Element<'a, Message>>,
row_widths: &[f32],
top_inset: f32,
on_scroll: impl Fn(scrollable::Viewport) -> Message + 'a,
) -> Element<'a, Message> {
let panel_width = tree_panel_width(file_tree, row_widths);
let tree_body = vscroll_tracked(
column(tree_rows).spacing(0),
Length::Fill,
Length::Fill,
file_tree.tree_scroll_id.clone(),
on_scroll,
);
let tree_inner: Element<'_, Message> = container(tree_body)
.width(Length::Fixed(panel_width))
.height(Length::Fill)
.padding(Padding::default().top(top_inset))
.style(theme::surface_container_style)
.into();
if file_tree.tree_focused {
container(tree_inner)
.style(|_t: &iced::Theme| container::Style {
border: iced::Border {
color: theme::ACCENT_LIGHT,
width: 2.0,
radius: 0.0.into(),
},
..Default::default()
})
.into()
} else {
tree_inner
}
}
#[must_use]
pub fn tree_guide_prefix(ancestor_mask: u64, depth: usize, is_last: bool) -> String {
debug_assert!(
depth < 64,
"tree_guide_prefix: depth {depth} exceeds u64 bit limit (max 63)"
);
let mut s = String::new();
for d in 0..depth.saturating_sub(1) {
if ancestor_mask & (1u64 << d) != 0 {
s.push('│');
} else {
s.push(' ');
}
s.push(' ');
}
if depth > 0 {
if is_last {
s.push('â””');
} else {
s.push('├');
}
s.push(' ');
}
s
}
pub fn render_tree_children<'a, Message>(
children: &'a [TreeNode],
depth: usize,
ancestor_mask: u64,
is_last: bool,
render_node: impl Fn(&'a TreeNode, usize, u64, bool) -> Element<'a, Message>,
) -> Vec<Element<'a, Message>> {
let child_count = children.len();
let cont_bit = if !is_last { 1u64 << depth } else { 0u64 };
let child_mask = ancestor_mask | cont_bit;
children
.iter()
.enumerate()
.map(|(i, child)| {
let child_is_last = i == child_count - 1;
render_node(child, depth + 1, child_mask, child_is_last)
})
.collect()
}
pub fn render_tree_node<'a, Message>(
is_dir: bool,
render_dir: impl FnOnce() -> Element<'a, Message>,
render_file: impl FnOnce() -> Element<'a, Message>,
) -> Element<'a, Message> {
if is_dir { render_dir() } else { render_file() }
}
#[must_use]
pub fn tree_node_focused(tree: &FileTree, node_path: &str) -> bool {
tree.tree_focused
&& tree.tree_focus_index < tree.visible_tree_nodes.len()
&& tree.visible_tree_nodes[tree.tree_focus_index].0 == node_path
}
fn tree_node_button_style(
is_highlighted: bool,
) -> impl Fn(&iced::Theme, button::Status) -> button::Style {
move |_t: &iced::Theme, status| {
let bg = if is_highlighted {
theme::HOVER_STRONG
} else if status == button::Status::Hovered {
theme::HOVER
} else {
iced::Color::TRANSPARENT
};
button::Style {
background: Some(iced::Background::Color(bg)),
..Default::default()
}
}
}
pub fn tree_node_button<'a, Message: Clone + 'a>(
content: impl Into<Element<'a, Message>>,
is_highlighted: bool,
on_press: Option<Message>,
) -> Element<'a, Message> {
let mut btn = widget::button(content)
.style(tree_node_button_style(is_highlighted))
.width(Length::Fill)
.padding(Padding::ZERO);
if let Some(msg) = on_press {
btn = btn.on_press(msg);
}
btn.into()
}
pub fn tree_row<'a, Message: 'a>(
guide: String,
icon: Element<'a, Message>,
name: Element<'a, Message>,
counts: Option<Element<'a, Message>>,
) -> Row<'a, Message> {
let mut row = Row::new()
.push(text(guide).size(TREE_FONT_SIZE).color(theme::TEXT_MUTED))
.push(icon)
.push(Space::new().width(theme::SPACE_4))
.push(name)
.push(Space::new().width(Length::Fill));
if let Some(counts) = counts {
row = row.push(counts).push(Space::new().width(theme::SPACE_6));
}
row.align_y(Alignment::Center)
}
pub(super) fn modal_backdrop_layer<'a, Message: 'a + Clone>(
on_backdrop: Message,
opacity: f32,
) -> Element<'a, Message> {
mouse_area(
container(text(""))
.width(Length::Fill)
.height(Length::Fill)
.style(move |_theme: &iced::Theme| container::Style {
background: Some(iced::Background::Color(Color::from_rgba(
0.0, 0.0, 0.0, opacity,
))),
..container::Style::default()
}),
)
.interaction(iced::mouse::Interaction::Idle)
.on_press(on_backdrop)
.into()
}
pub(super) fn dialog_click_guard<'a, Message: 'a + Clone>(
content: impl Into<Element<'a, Message>>,
) -> Element<'a, Message> {
mouse_area(content)
.interaction(iced::mouse::Interaction::Idle)
.into()
}
pub fn modal_backdrop<'a, Message: 'a + Clone>(
content: impl Into<Element<'a, Message>>,
on_backdrop: Message,
opacity: f32,
) -> Element<'a, Message> {
let backdrop = modal_backdrop_layer(on_backdrop, opacity);
let centered = container(dialog_click_guard(content))
.width(Length::Fill)
.height(Length::Fill)
.center_x(Length::Fill)
.center_y(Length::Fill);
stack([backdrop, centered.into()]).into()
}
pub fn empty_stack_placeholder<'a, Message: 'a>() -> Element<'a, Message> {
container(text(""))
.width(Length::Shrink)
.height(Length::Shrink)
.into()
}
#[must_use]
pub fn click_to_toggle<'a, Message: Clone + 'a>(
content: impl Into<Element<'a, Message>>,
on_click: Message,
on_cancel: Message,
) -> Element<'a, Message> {
ClickToggle {
content: content.into(),
on_click,
on_cancel,
}
.into()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ClickKind {
Click,
Drag,
MultiClick,
}
pub(crate) const CLICK_DRAG_MAX_DISTANCE: f32 = 6.0;
pub(crate) const DOUBLE_CLICK_WINDOW: Duration = Duration::from_millis(300);
fn classify_click(distance: f32, since_last_click: Option<Duration>) -> ClickKind {
if distance > CLICK_DRAG_MAX_DISTANCE {
return ClickKind::Drag;
}
if since_last_click.is_some_and(|elapsed| elapsed <= DOUBLE_CLICK_WINDOW) {
return ClickKind::MultiClick;
}
ClickKind::Click
}
#[derive(Default, Clone)]
struct ClickToggleState {
press: Option<Point>,
last_click: Option<Instant>,
click_count: u32,
drag_canceled: bool,
}
struct ClickToggle<'a, Message, Theme = iced::Theme, Renderer = iced::Renderer> {
content: Element<'a, Message, Theme, Renderer>,
on_click: Message,
on_cancel: Message,
}
impl<'a, Message, Theme, Renderer> From<ClickToggle<'a, Message, Theme, Renderer>>
for Element<'a, Message, Theme, Renderer>
where
Message: 'a + Clone,
Theme: 'a,
Renderer: 'a + renderer::Renderer,
{
fn from(widget: ClickToggle<'a, Message, Theme, Renderer>) -> Self {
Self::new(widget)
}
}
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
for ClickToggle<'_, Message, Theme, Renderer>
where
Renderer: renderer::Renderer,
Message: Clone,
{
fn tag(&self) -> tree::Tag {
tree::Tag::of::<ClickToggleState>()
}
fn state(&self) -> tree::State {
tree::State::new(ClickToggleState::default())
}
fn children(&self) -> Vec<Tree> {
vec![Tree::new(&self.content)]
}
fn diff(&self, tree: &mut Tree) {
tree.diff_children(std::slice::from_ref(&self.content));
}
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn layout(
&mut self,
tree: &mut Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
self.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn Operation,
) {
self.content
.as_widget_mut()
.operate(&mut tree.children[0], layout, renderer, operation);
}
fn update(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
let mut child_messages = Vec::new();
let mut child_shell = Shell::new(&mut child_messages);
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
&mut child_shell,
viewport,
);
let child_published = !child_shell.is_empty();
shell.merge(child_shell, std::convert::identity);
self.handle_mouse(tree, event, layout, cursor, shell, child_published);
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
let content_interaction = self.content.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
);
match (content_interaction, cursor.is_over(layout.bounds())) {
(mouse::Interaction::None, true) => mouse::Interaction::Pointer,
_ => content_interaction,
}
}
fn draw(
&self,
tree: &Tree,
renderer: &mut Renderer,
theme: &Theme,
renderer_style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
renderer_style,
layout,
cursor,
viewport,
);
}
fn overlay<'a>(
&'a mut self,
tree: &'a mut Tree,
layout: Layout<'a>,
renderer: &Renderer,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'a, Message, Theme, Renderer>> {
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
impl<Message: Clone, Theme, Renderer> ClickToggle<'_, Message, Theme, Renderer> {
fn handle_mouse(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
shell: &mut Shell<'_, Message>,
child_published: bool,
) {
let state: &mut ClickToggleState = tree.state.downcast_mut();
match event {
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
if cursor.is_over(layout.bounds())
&& let Some(position) = cursor.position()
{
state.press = Some(position);
state.drag_canceled = false;
}
}
Event::Mouse(mouse::Event::CursorMoved { .. }) => {
if let (Some(press_position), Some(position)) = (state.press, cursor.position())
&& position.distance(press_position) > CLICK_DRAG_MAX_DISTANCE
{
self.publish_cancel_once(state, shell);
}
}
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
let Some(press_position) = state.press.take() else {
return;
};
let Some(release_position) = cursor.position() else {
return;
};
let kind = classify_click(
release_position.distance(press_position),
state.last_click.map(|t| t.elapsed()),
);
if kind == ClickKind::Drag {
state.last_click = None;
state.click_count = 0;
self.publish_cancel_once(state, shell);
return;
}
if child_published {
if state.click_count > 0 {
shell.publish(self.on_cancel.clone());
}
state.last_click = None;
state.click_count = 0;
return;
}
state.click_count = if kind == ClickKind::Click {
1
} else {
state.click_count + 1
};
state.last_click = Some(Instant::now());
match state.click_count {
1 => shell.publish(self.on_click.clone()),
2 => shell.publish(self.on_cancel.clone()),
_ => {}
}
}
_ => {}
}
}
fn publish_cancel_once(&self, state: &mut ClickToggleState, shell: &mut Shell<'_, Message>) {
if !state.drag_canceled {
state.drag_canceled = true;
shell.publish(self.on_cancel.clone());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
type Nodes = &'static [(&'static str, bool)];
const SRC: Nodes = &[("src", true), ("src/main.rs", false), ("Cargo.toml", false)];
const AB: Nodes = &[("a", false), ("b", false)];
const INTO: ScrollMode = ScrollMode::ScrollIntoView;
const TOP: ScrollMode = ScrollMode::SnapToTop;
fn make_tree(nodes: Nodes) -> FileTree {
let mut tree = FileTree::new(iced::widget::Id::new("test"));
tree.visible_tree_nodes = nodes.iter().map(|&(p, d)| (p.to_string(), d)).collect();
tree
}
fn file(path: &str) -> TreeNode {
TreeNode {
name: path.rsplit('/').next().unwrap_or(path).into(),
full_path: path.into(),
is_dir: false,
children: vec![],
error: None,
ignored: false,
}
}
fn dir(path: &str, children: Vec<TreeNode>) -> TreeNode {
TreeNode {
name: path.into(),
full_path: path.into(),
is_dir: true,
children,
error: None,
ignored: false,
}
}
type FocusCase<'a> = (&'a str, Nodes, &'a str, (usize, Option<usize>, usize));
#[test]
fn focus_path_cases() {
let cases: &[FocusCase] = &[
("found", SRC, "src/main.rs", (0, Some(1), 1)),
("empty tree", &[], "anything", (0, None, 0)),
("first node", SRC, "src", (0, Some(0), 0)),
("last node", SRC, "Cargo.toml", (0, Some(2), 2)),
("invisible keeps index", SRC, "nonexistent", (42, None, 42)),
("refocus", SRC, "src", (2, Some(0), 0)),
];
for &(name, nodes, path, (start, found, index)) in cases {
let mut tree = make_tree(nodes);
tree.tree_focus_index = start;
assert_eq!(tree.focus_path(path), found, "case {name}");
assert_eq!(tree.tree_focus_index, index, "case {name}: index");
}
}
type NavCase = (&'static str, bool, bool, (usize, bool, usize));
#[test]
fn nav_cases() {
let cases: &[NavCase] = &[
("up at top", true, true, (0, false, 0)),
("down at bottom", false, true, (1, false, 1)),
("up moves", true, true, (1, true, 0)),
("down moves", false, true, (0, true, 1)),
("up unfocused", true, false, (0, false, 0)),
("down unfocused", false, false, (0, false, 0)),
];
for &(name, up, focused, (start, moved, index)) in cases {
let mut tree = make_tree(AB);
tree.tree_focused = focused;
tree.tree_focus_index = start;
let moved_now = if up { tree.nav_up() } else { tree.nav_down() };
assert_eq!(moved_now, moved, "case {name}");
assert_eq!(tree.tree_focus_index, index, "case {name}: index");
}
}
type NodeCase<'a> = (
&'a str,
Nodes,
(bool, usize),
Option<(usize, &'a str, bool)>,
);
type DirCase<'a> = (&'a str, Nodes, (bool, Option<&'a str>), bool);
#[test]
fn focused_tree_node_cases() {
let node_cases: &[NodeCase] = &[
("not focused", SRC, (false, 0), None),
("empty nodes", &[], (true, 0), None),
("clamps index", AB, (true, 10), Some((1, "b", false))),
(
"finds node",
SRC,
(true, 1),
Some((1, "src/main.rs", false)),
),
("directory", SRC, (true, 0), Some((0, "src", true))),
];
for &(name, nodes, (focused, focus_index), expected) in node_cases {
let mut tree = make_tree(nodes);
tree.tree_focused = focused;
tree.tree_focus_index = focus_index;
let shown = expected.map(|(i, p, d)| (i, p.to_string(), d));
assert_eq!(tree.focused_tree_node(), shown, "case {name}");
}
let dir_cases: &[DirCase] = &[
("not focused", SRC, (false, None), false),
("empty tree", &[], (true, None), false),
("file", &[("main.rs", false)], (true, None), false),
("collapsed dir", &[("src", true)], (true, None), false),
("expanded dir", &[("src", true)], (true, Some("src")), true),
];
for &(name, nodes, (focused, expanded), expected) in dir_cases {
let mut tree = make_tree(nodes);
tree.tree_focused = focused;
if let Some(dir) = expanded {
tree.expanded_dirs.insert(dir.into());
}
assert_eq!(tree.focused_is_expanded_dir(), expected, "case {name}");
}
let parent_cases: &[(&str, Nodes, bool, Option<&str>)] = &[
("not focused", &[("src/main.rs", false)], false, None),
("empty tree", &[], true, None),
("root item", &[("src", true)], true, None),
("nested", &[("src/main.rs", false)], true, Some("src")),
("deep", &[("a/b/c/file.rs", false)], true, Some("a/b/c")),
];
for &(name, nodes, focused, expected) in parent_cases {
let mut tree = make_tree(nodes);
tree.tree_focused = focused;
let parent = tree.focused_parent_path();
assert_eq!(parent.as_deref(), expected, "case {name}");
}
}
fn tree_with_src_dir() -> FileTree {
let mut tree = FileTree::new(iced::widget::Id::new("test"));
tree.nodes = vec![dir("src", vec![file("src/lib.rs"), file("src/main.rs")])];
tree
}
type ExpandDirCase<'a> = (&'a str, bool, (bool, bool), (&'a [&'a str], usize));
#[test]
fn expand_collapse_dir_cases() {
let cases: &[ExpandDirCase] = &[
(
"expand advances",
true,
(false, false),
(&["src", "src/lib.rs", "src/main.rs"], 1),
),
("expand no children", true, (false, true), (&["src"], 0)),
(
"collapse after rebuild",
false,
(true, false),
(&["src"], 0),
),
(
"collapse without rebuild",
false,
(false, false),
(&["src"], 0),
),
];
for &(name, expand, (rebuilt, no_children), (visible, focus)) in cases {
let mut tree = tree_with_src_dir();
if no_children {
tree.nodes[0].children.clear();
}
if expand {
tree.expanded_dirs.insert("src".into());
assert!(
tree.visible_tree_nodes.is_empty(),
"case {name}: no rows yet"
);
let _task = tree.expand_dir_and_focus_first_child::<()>("src");
} else {
if rebuilt {
tree.expanded_dirs.insert("src".into());
tree.rebuild_visible();
assert_eq!(
tree.visible_tree_nodes.len(),
3,
"case {name}: expanded rows"
);
tree.expanded_dirs.remove("src");
}
let _task = tree.collapse_dir_and_keep_focus::<()>("src");
}
let rows: Vec<&str> = tree
.visible_tree_nodes
.iter()
.map(|(p, _)| p.as_str())
.collect();
assert_eq!(rows, visible, "case {name}");
assert_eq!(tree.tree_focus_index, focus, "case {name}: focus");
}
}
fn tree_with_viewport(n: usize, scroll_y: f32, viewport_h: Option<f32>) -> FileTree {
let mut tree = FileTree::new(iced::widget::Id::new("scroll_test"));
tree.visible_tree_nodes = (0..n).map(|i| (format!("file_{i}.rs"), false)).collect();
tree.scroll_y = scroll_y;
tree.viewport_h = viewport_h;
tree
}
type ScrollCase = (&'static str, f32, Option<f32>, usize, ScrollMode, f32);
#[test]
fn scroll_to_tree_focus_positions_viewport() {
let cases: &[ScrollCase] = &[
("fully visible", 40.0, Some(400.0), 3, INTO, 40.0),
("below viewport", 0.0, Some(200.0), 15, INTO, 19.5),
("above viewport", 100.0, Some(400.0), 3, INTO, 58.5),
("top edge partial", 50.0, Some(400.0), 2, INTO, 50.0),
("no viewport snaps", 10.0, None, 10, INTO, 195.0),
("snap to top", 0.0, Some(400.0), 8, TOP, 156.0),
];
for &(name, scroll_y, viewport_h, focus, mode, expected) in cases {
let mut tree = tree_with_viewport(30, scroll_y, viewport_h);
tree.tree_focus_index = focus;
let _task = scroll_to_tree_focus::<()>(&mut tree, mode);
let got = tree.scroll_y;
assert!((got - expected).abs() < 0.01, "case {name}: scroll_y {got}");
}
let mut tree = tree_with_viewport(0, 0.0, Some(400.0));
let _task = scroll_to_tree_focus::<()>(&mut tree, INTO);
assert!(tree.scroll_y.abs() < f32::EPSILON, "case empty tree");
}
}