Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

git_ui: make git graph columns toggleable (#59850)

Remco Smitsfcd0f7695218
diff --git a/crates/git_ui/src/git_graph.rs b/crates/git_ui/src/git_graph.rs
index 9366039969e..b360e1ec578 100644
--- a/crates/git_ui/src/git_graph.rs
+++ b/crates/git_ui/src/git_graph.rs
@@ -55,8 +55,8 @@ use ui::{
Divider, HeaderResizeInfo, HighlightedLabel, ListItem, ListItemSpacing,
RedistributableColumnsState, ScrollableHandle, Table, TableInteractionState,
TableRenderContext, TableResizeBehavior, Tooltip, WithScrollbar, bind_redistributable_columns,
- prelude::*, render_redistributable_columns_resize_handles, render_table_header,
- table_row::TableRow,
+ prelude::*, redistribute_hidden_fractions, redistribute_hidden_widths,
+ render_redistributable_columns_resize_handles, render_table_header, table_row::TableRow,
};
use util::{ResultExt, debug_panic};
use workspace::{
@@ -73,6 +73,7 @@ const RESIZE_HANDLE_WIDTH: f32 = 8.0;
const COPIED_STATE_DURATION: Duration = Duration::from_secs(2);
const COMMIT_TAG_LIST_WIDTH_IN_REMS: Rems = rems(10.);
const CUSTOM_GIT_COMMANDS_DOCS_SLUG: &str = "tasks#custom-git-commands";
+const TABLE_COLUMN_COUNT: usize = 4;
// Extra vertical breathing room added to the UI line height when computing
// the git graph's row height, so commit dots and lines have space around them.
const ROW_VERTICAL_PADDING: Pixels = px(4.0);
@@ -1320,7 +1321,7 @@ fn compute_diff_stats(diff: &CommitDiff) -> (usize, usize) {
struct GitGraphContextMenu {
menu: Entity<ContextMenu>,
position: Point<Pixels>,
- entry_idx: usize,
+ entry_idx: Option<usize>,
_subscription: Subscription,
}
@@ -1339,6 +1340,9 @@ pub struct GitGraph {
context_menu: Option<GitGraphContextMenu>,
table_interaction_state: Entity<TableInteractionState>,
column_widths: Entity<RedistributableColumnsState>,
+ /// Per-column visibility mask owned by the view (not the resize state) so columns can be
+ /// hidden regardless of whether the table is resizable. `true` means the column is hidden.
+ column_visibility: TableRow<bool>,
selected_entry_idx: Option<usize>,
hovered_entry_idx: Option<usize>,
graph_canvas_bounds: Rc<Cell<Option<Bounds<Pixels>>>>,
@@ -1402,22 +1406,32 @@ impl GitGraph {
}
fn preview_column_fractions(&self, window: &Window, cx: &App) -> [f32; 5] {
- // todo(git_graph): We should make a column/table api that allows removing table columns
- let fractions = self
+ let raw = self
.column_widths
.read(cx)
.preview_fractions(window.rem_size());
+ let fractions = redistribute_hidden_fractions(&raw, Some(&self.column_visibility));
+
+ // Hidden columns occupy no space in the layout, so report them as zero here even though
+ // the shared redistribution helper preserves their stored width for when they return.
+ let value = |idx: usize| {
+ if self.column_visibility.get(idx).copied().unwrap_or(false) {
+ 0.0
+ } else {
+ fractions[idx]
+ }
+ };
let is_path_history = matches!(self.log_source, LogSource::Path(_));
- let graph_fraction = if is_path_history { 0.0 } else { fractions[0] };
+ let graph_fraction = if is_path_history { 0.0 } else { value(0) };
let offset = if is_path_history { 0 } else { 1 };
[
graph_fraction,
- fractions[offset],
- fractions[offset + 1],
- fractions[offset + 2],
- fractions[offset + 3],
+ value(offset),
+ value(offset + 1),
+ value(offset + 2),
+ value(offset + 3),
]
}
@@ -1445,10 +1459,13 @@ impl GitGraph {
}
fn graph_viewport_width(&self, window: &Window, cx: &App) -> Pixels {
- self.column_widths
- .read(cx)
- .preview_column_width(0, window)
- .unwrap_or_else(|| self.graph_canvas_content_width())
+ let container = self.column_widths.read(cx).cached_container_width();
+ let graph_fraction = self.preview_column_fractions(window, cx)[0];
+ if container > px(0.) && graph_fraction > 0.0 {
+ container * graph_fraction
+ } else {
+ self.graph_canvas_content_width()
+ }
}
pub fn new(
@@ -1531,6 +1548,14 @@ impl GitGraph {
)
})
};
+ let column_visibility = TableRow::from_element(
+ false,
+ if matches!(log_source, LogSource::Path(_)) {
+ TABLE_COLUMN_COUNT
+ } else {
+ TABLE_COLUMN_COUNT + 1
+ },
+ );
let mut row_height = Self::row_height(window, cx);
cx.observe_global_in::<settings::SettingsStore>(window, move |this, window, cx| {
@@ -1564,6 +1589,7 @@ impl GitGraph {
context_menu: None,
table_interaction_state,
column_widths,
+ column_visibility,
selected_entry_idx: None,
hovered_entry_idx: None,
graph_canvas_bounds: Rc::new(Cell::new(None)),
@@ -2674,14 +2700,14 @@ impl GitGraph {
menu
})
});
- self.set_context_menu(context_menu, position, index, window, cx);
+ self.set_context_menu(context_menu, position, Some(index), window, cx);
}
fn set_context_menu(
&mut self,
context_menu: Entity<ContextMenu>,
position: Point<Pixels>,
- entry_idx: usize,
+ entry_idx: Option<usize>,
window: &mut Window,
cx: &mut Context<Self>,
) {
@@ -2712,6 +2738,63 @@ impl GitGraph {
cx.notify();
}
+ fn toggle_column_visibility(&mut self, col_idx: usize, cx: &mut Context<Self>) {
+ if let Some(slot) = self.column_visibility.as_mut_slice().get_mut(col_idx) {
+ *slot = !*slot;
+ // Column visibility is persisted per item, so schedule a workspace serialization.
+ cx.emit(ItemEvent::Edit);
+ }
+ }
+
+ fn deploy_header_context_menu(
+ &mut self,
+ position: Point<Pixels>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let is_path_history = matches!(self.log_source, LogSource::Path(_));
+ let columns: &[&str] = if is_path_history {
+ &["Description", "Date", "Author", "Commit"]
+ } else {
+ &["Graph", "Description", "Date", "Author", "Commit"]
+ };
+
+ let filter = self.column_visibility.clone();
+ let visible_count = filter
+ .as_slice()
+ .iter()
+ .filter(|filtered| !**filtered)
+ .count();
+
+ let focus_handle = self.focus_handle.clone();
+ let git_graph = cx.entity();
+ let context_menu = ContextMenu::build(window, cx, |mut context_menu, _window, _cx| {
+ context_menu = context_menu.context(focus_handle).header("Columns");
+ for (col_idx, label) in columns.iter().enumerate() {
+ let is_visible = !filter.get(col_idx).copied().unwrap_or(false);
+ // Disable hiding the last remaining visible column.
+ let can_toggle = !is_visible || visible_count > 1;
+ let git_graph = git_graph.clone();
+ context_menu = context_menu.toggleable_entry_disabled_when(
+ label.to_string(),
+ is_visible,
+ !can_toggle,
+ IconPosition::End,
+ None,
+ move |_window, cx| {
+ git_graph.update(cx, |this, cx| {
+ this.toggle_column_visibility(col_idx, cx);
+ cx.notify();
+ });
+ },
+ );
+ }
+ context_menu
+ });
+
+ self.set_context_menu(context_menu, position, None, window, cx);
+ }
+
fn render_search_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
let color = cx.theme().colors();
let query_focus_handle = self
@@ -3365,7 +3448,7 @@ impl GitGraph {
let hovered_entry_idx = self.hovered_entry_idx;
let selected_entry_idx = self.selected_entry_idx;
- let context_menu_entry_idx = self.context_menu.as_ref().map(|menu| menu.entry_idx);
+ let context_menu_entry_idx = self.context_menu.as_ref().and_then(|menu| menu.entry_idx);
let is_focused = self.focus_handle.is_focused(window);
let graph_canvas_bounds = self.graph_canvas_bounds.clone();
@@ -3892,10 +3975,27 @@ impl Render for GitGraph {
let is_path_history = matches!(self.log_source, LogSource::Path(_));
let header_resize_info =
HeaderResizeInfo::from_redistributable(&self.column_widths, cx);
- let header_context = TableRenderContext::for_column_widths(
- Some(self.column_widths.read(cx).widths_to_render()),
- true,
+
+ let column_filter = self.column_visibility.clone();
+
+ // The graph column (index 0) only exists in the non-path-history layout and is
+ // rendered as a separate canvas outside the table.
+ let graph_visible =
+ is_path_history || !column_filter.get(0usize).copied().unwrap_or(false);
+
+ let table_offset = if is_path_history { 0 } else { 1 };
+ let table_filter = column_filter
+ .as_slice()
+ .get(table_offset..table_offset + TABLE_COLUMN_COUNT)
+ .map(|slice| TableRow::from_vec(slice.to_vec(), TABLE_COLUMN_COUNT))
+ .unwrap_or_else(|| TableRow::from_element(false, TABLE_COLUMN_COUNT));
+ let header_widths = redistribute_hidden_widths(
+ &self.column_widths.read(cx).widths_to_render(),
+ Some(&column_filter),
);
+ let header_context = TableRenderContext::for_column_widths(Some(header_widths), true)
+ .with_column_filter(Some(column_filter));
+
let [
graph_fraction,
description_fraction,
@@ -3907,6 +4007,9 @@ impl Render for GitGraph {
description_fraction + date_fraction + author_fraction + commit_fraction;
let table_width_config = self.table_column_width_config(window, cx);
+ let table_collapsed = table_fraction <= f32::EPSILON;
+ let graph_content_width = self.graph_canvas_content_width();
+
h_flex()
.size_full()
.child(
@@ -3916,47 +4019,69 @@ impl Render for GitGraph {
.size_full()
.flex()
.flex_col()
- .child(render_table_header(
- if !is_path_history {
- TableRow::from_vec(
- vec![
- Label::new("Graph")
- .color(Color::Muted)
- .truncate()
- .into_any_element(),
- Label::new("Description")
- .color(Color::Muted)
- .into_any_element(),
- Label::new("Date").color(Color::Muted).into_any_element(),
- Label::new("Author").color(Color::Muted).into_any_element(),
- Label::new("Commit").color(Color::Muted).into_any_element(),
- ],
- 5,
- )
- } else {
- TableRow::from_vec(
- vec![
- Label::new("Description")
- .color(Color::Muted)
- .into_any_element(),
- Label::new("Date").color(Color::Muted).into_any_element(),
- Label::new("Author").color(Color::Muted).into_any_element(),
- Label::new("Commit").color(Color::Muted).into_any_element(),
- ],
- 4,
+ .child(
+ div()
+ .on_mouse_down(
+ MouseButton::Right,
+ cx.listener(|this, event: &MouseDownEvent, window, cx| {
+ this.deploy_header_context_menu(event.position, window, cx);
+ cx.stop_propagation();
+ }),
)
- },
- header_context,
- Some(header_resize_info),
- Some(self.column_widths.entity_id()),
- cx,
- ))
+ .child(render_table_header(
+ if !is_path_history {
+ TableRow::from_vec(
+ vec![
+ Label::new("Graph")
+ .color(Color::Muted)
+ .truncate()
+ .into_any_element(),
+ Label::new("Description")
+ .color(Color::Muted)
+ .into_any_element(),
+ Label::new("Date")
+ .color(Color::Muted)
+ .into_any_element(),
+ Label::new("Author")
+ .color(Color::Muted)
+ .into_any_element(),
+ Label::new("Commit")
+ .color(Color::Muted)
+ .into_any_element(),
+ ],
+ 5,
+ )
+ } else {
+ TableRow::from_vec(
+ vec![
+ Label::new("Description")
+ .color(Color::Muted)
+ .into_any_element(),
+ Label::new("Date")
+ .color(Color::Muted)
+ .into_any_element(),
+ Label::new("Author")
+ .color(Color::Muted)
+ .into_any_element(),
+ Label::new("Commit")
+ .color(Color::Muted)
+ .into_any_element(),
+ ],
+ 4,
+ )
+ },
+ header_context,
+ Some(header_resize_info),
+ Some(self.column_widths.entity_id()),
+ cx,
+ )),
+ )
.child({
let row_height = Self::row_height(window, cx);
let selected_entry_idx = self.selected_entry_idx;
let hovered_entry_idx = self.hovered_entry_idx;
let context_menu_entry_idx =
- self.context_menu.as_ref().map(|menu| menu.entry_idx);
+ self.context_menu.as_ref().and_then(|menu| menu.entry_idx);
let weak_self = cx.weak_entity();
let focus_handle = self.focus_handle.clone();
let table_focus_handle =
@@ -3991,6 +4116,7 @@ impl Render for GitGraph {
.hide_row_borders()
.hide_row_hover()
.width_config(table_width_config)
+ .column_filter(table_filter)
.map_row(move |(index, row), window, cx| {
let is_selected = selected_entry_idx == Some(index);
let is_hovered = hovered_entry_idx == Some(index);
@@ -4077,10 +4203,18 @@ impl Render for GitGraph {
.child(
h_flex()
.size_full()
- .when(!is_path_history, |this| {
+ .when(!is_path_history && graph_visible, |this| {
this.child(
div()
- .w(DefiniteLength::Fraction(graph_fraction))
+ .map(|this| {
+ if table_collapsed {
+ this.w(graph_content_width)
+ } else {
+ this.w(DefiniteLength::Fraction(
+ graph_fraction,
+ ))
+ }
+ })
.h_full()
.min_w_0()
.overflow_hidden()
@@ -4092,7 +4226,15 @@ impl Render for GitGraph {
.tab_index(2)
.tab_group()
.tab_stop(false)
- .w(DefiniteLength::Fraction(table_fraction))
+ .map(|this| {
+ if table_collapsed {
+ this.flex_1()
+ } else {
+ this.w(DefiniteLength::Fraction(
+ table_fraction,
+ ))
+ }
+ })
.h_full()
.min_w_0()
.child(commits_table),
@@ -4100,10 +4242,12 @@ impl Render for GitGraph {
)
.child(render_redistributable_columns_resize_handles(
&self.column_widths,
+ Some(&self.column_visibility),
window,
cx,
)),
self.column_widths.clone(),
+ Some(self.column_visibility.clone()),
)
}),
)
@@ -4295,6 +4439,7 @@ impl workspace::SerializableItem for GitGraph {
selected_sha,
search_query,
search_case_sensitive,
+ hidden_columns,
)) = db.get_git_graph(item_id, workspace_id).ok().flatten()
else {
return Task::ready(Err(anyhow::anyhow!("No git graph to deserialize")));
@@ -4307,6 +4452,7 @@ impl workspace::SerializableItem for GitGraph {
selected_sha,
search_query,
search_case_sensitive,
+ hidden_columns,
};
let window_handle = window.window_handle();
@@ -4349,6 +4495,16 @@ impl workspace::SerializableItem for GitGraph {
});
git_graph.update(cx, |graph, cx| {
+ if let Some(bits) = state.hidden_columns {
+ let cols = graph.column_visibility.cols();
+ let mask = persistence::deserialize_hidden_columns(bits, cols);
+ // Never restore an all-hidden mask (e.g. from corrupt data); the UI
+ // guarantees at least one column stays visible.
+ if mask.iter().any(|is_hidden| !is_hidden) {
+ graph.column_visibility = TableRow::from_vec(mask, cols);
+ }
+ }
+
graph.search_state.case_sensitive =
state.search_case_sensitive.unwrap_or(false);
@@ -4401,6 +4557,9 @@ impl workspace::SerializableItem for GitGraph {
let log_source_value = persistence::serialize_log_source_value(&self.log_source);
let log_order = Some(persistence::serialize_log_order(&self.log_order));
let search_case_sensitive = Some(self.search_state.case_sensitive);
+ let hidden_columns = Some(persistence::serialize_hidden_columns(
+ self.column_visibility.as_slice(),
+ ));
let db = persistence::GitGraphsDb::global(cx);
Some(cx.background_spawn(async move {
@@ -4414,6 +4573,7 @@ impl workspace::SerializableItem for GitGraph {
selected_sha,
search_query,
search_case_sensitive,
+ hidden_columns,
)
.await
}))
@@ -4469,6 +4629,9 @@ mod persistence {
ALTER TABLE git_graphs ADD COLUMN search_query TEXT;
ALTER TABLE git_graphs ADD COLUMN search_case_sensitive INTEGER;
),
+ sql!(
+ ALTER TABLE git_graphs ADD COLUMN hidden_columns INTEGER;
+ ),
];
}
@@ -4545,6 +4708,23 @@ mod persistence {
}
}
+ /// Packs the per-column visibility mask into a bitmask (bit `i` set means column `i` is
+ /// hidden), so it fits in a single integer database column regardless of column count.
+ pub fn serialize_hidden_columns(hidden: &[bool]) -> i32 {
+ hidden.iter().enumerate().fold(
+ 0,
+ |bits, (idx, &is_hidden)| {
+ if is_hidden { bits | (1 << idx) } else { bits }
+ },
+ )
+ }
+
+ /// Inverse of [`serialize_hidden_columns`]. Bits beyond `cols` are ignored, and missing
+ /// bits default to visible, so a mask saved with a different column count degrades safely.
+ pub fn deserialize_hidden_columns(bits: i32, cols: usize) -> Vec<bool> {
+ (0..cols).map(|idx| bits & (1 << idx) != 0).collect()
+ }
+
#[derive(Debug, Default, Clone)]
pub struct SerializedGitGraphState {
pub log_source_type: Option<i32>,
@@ -4553,6 +4733,7 @@ mod persistence {
pub selected_sha: Option<String>,
pub search_query: Option<String>,
pub search_case_sensitive: Option<bool>,
+ pub hidden_columns: Option<i32>,
}
impl GitGraphsDb {
@@ -4566,14 +4747,16 @@ mod persistence {
log_order: Option<i32>,
selected_sha: Option<String>,
search_query: Option<String>,
- search_case_sensitive: Option<bool>
+ search_case_sensitive: Option<bool>,
+ hidden_columns: Option<i32>
) -> Result<()> {
INSERT OR REPLACE INTO git_graphs(
item_id, workspace_id, repo_working_path,
log_source_type, log_source_value, log_order,
- selected_sha, search_query, search_case_sensitive
+ selected_sha, search_query, search_case_sensitive,
+ hidden_columns
)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
}
}
@@ -4588,7 +4771,8 @@ mod persistence {
Option<i32>,
Option<String>,
Option<String>,
- Option<bool>
+ Option<bool>,
+ Option<i32>
)>> {
SELECT
repo_working_path,
@@ -4597,7 +4781,8 @@ mod persistence {
log_order,
selected_sha,
search_query,
- search_case_sensitive
+ search_case_sensitive,
+ hidden_columns
FROM git_graphs
WHERE item_id = ? AND workspace_id = ?
}
@@ -5886,6 +6071,7 @@ mod tests {
selected_sha: Some(sha.to_string()),
search_query: Some("fix bug".to_string()),
search_case_sensitive: Some(true),
+ hidden_columns: None,
};
assert_eq!(
@@ -5910,6 +6096,7 @@ mod tests {
selected_sha: None,
search_query: None,
search_case_sensitive: None,
+ hidden_columns: None,
};
assert_eq!(
persistence::deserialize_log_source(&all_state),
@@ -5951,6 +6138,34 @@ mod tests {
));
}
+ #[gpui::test]
+ fn test_hidden_columns_bitmask_roundtrip(_cx: &mut TestAppContext) {
+ let mask = [false, true, false, true, false];
+ let bits = persistence::serialize_hidden_columns(&mask);
+ assert_eq!(
+ persistence::deserialize_hidden_columns(bits, mask.len()),
+ mask.to_vec()
+ );
+
+ assert_eq!(persistence::serialize_hidden_columns(&[false; 5]), 0);
+ assert_eq!(
+ persistence::deserialize_hidden_columns(0, 4),
+ vec![false; 4]
+ );
+
+ // A mask saved with more columns than we restore with is truncated safely, and one
+ // saved with fewer columns defaults the extra columns to visible.
+ let bits = persistence::serialize_hidden_columns(&[true, false, true, false, true]);
+ assert_eq!(
+ persistence::deserialize_hidden_columns(bits, 4),
+ vec![true, false, true, false]
+ );
+ assert_eq!(
+ persistence::deserialize_hidden_columns(bits, 6),
+ vec![true, false, true, false, true, false]
+ );
+ }
+
#[gpui::test]
async fn test_git_graph_state_persists_across_serialization_roundtrip(cx: &mut TestAppContext) {
init_test(cx);
@@ -6026,6 +6241,9 @@ mod tests {
.await
.expect("should create workspace id");
let db = cx.read(|cx| persistence::GitGraphsDb::global(cx));
+ // Hide the "Date" column (index 2 in the non-path-history layout).
+ let hidden_columns =
+ persistence::serialize_hidden_columns(&[false, false, true, false, false]);
db.save_git_graph(
item_id,
workspace_id,
@@ -6036,6 +6254,7 @@ mod tests {
selected_sha.clone(),
Some("some query".to_string()),
Some(true),
+ Some(hidden_columns),
)
.await
.expect("save should succeed");
@@ -6089,6 +6308,12 @@ mod tests {
graph.search_state.case_sensitive, true,
"search case sensitivity should be restored"
);
+
+ assert_eq!(
+ graph.column_visibility.as_slice(),
+ &[false, false, true, false, false],
+ "hidden columns should be restored"
+ );
});
restored_graph.read_with(&*cx, |graph, cx| {
diff --git a/crates/ui/src/components/context_menu.rs b/crates/ui/src/components/context_menu.rs
index 4b98199239b..2a3388a406a 100644
--- a/crates/ui/src/components/context_menu.rs
+++ b/crates/ui/src/components/context_menu.rs
@@ -610,9 +610,23 @@ impl ContextMenu {
}
pub fn toggleable_entry(
+ self,
+ label: impl Into<SharedString>,
+ toggled: bool,
+ position: IconPosition,
+ action: Option<Box<dyn Action>>,
+ handler: impl Fn(&mut Window, &mut App) + 'static,
+ ) -> Self {
+ self.toggleable_entry_disabled_when(label, toggled, false, position, action, handler)
+ }
+
+ /// Like [`Self::toggleable_entry`], but the entry is rendered disabled (and its handler is not
+ /// invoked) when `disabled` is `true`.
+ pub fn toggleable_entry_disabled_when(
mut self,
label: impl Into<SharedString>,
toggled: bool,
+ disabled: bool,
position: IconPosition,
action: Option<Box<dyn Action>>,
handler: impl Fn(&mut Window, &mut App) + 'static,
@@ -629,7 +643,7 @@ impl ContextMenu {
icon_size: IconSize::Small,
icon_color: None,
action,
- disabled: false,
+ disabled,
documentation_aside: None,
end_slot_icon: None,
end_slot_title: None,
diff --git a/crates/ui/src/components/data_table.rs b/crates/ui/src/components/data_table.rs
index 609ddef1d81..805c93708ac 100644
--- a/crates/ui/src/components/data_table.rs
+++ b/crates/ui/src/components/data_table.rs
@@ -7,8 +7,8 @@ use crate::{
RESIZE_DIVIDER_WIDTH, RedistributableColumnsState, RegisterComponent, RenderOnce, ScrollAxes,
ScrollableHandle, Scrollbars, SharedString, StatefulInteractiveElement, Styled, StyledExt as _,
StyledTypography, TableResizeBehavior, Window, WithScrollbar, bind_redistributable_columns,
- div, example_group_with_title, h_flex, px, render_column_resize_divider,
- render_redistributable_columns_resize_handles, single_example,
+ div, example_group_with_title, h_flex, px, redistribute_hidden_widths,
+ render_column_resize_divider, render_redistributable_columns_resize_handles, single_example,
table_row::{IntoTableRow as _, TableRow},
v_flex,
};
@@ -368,6 +368,9 @@ pub struct Table {
cols: usize,
disable_base_cell_style: bool,
pinned_cols: usize,
+ /// Optional per-column visibility mask. When set, it overrides any filter derived from the
+ /// column width config. Columns whose entry is `true` are hidden.
+ column_filter: Option<TableRow<bool>>,
}
impl Table {
@@ -387,9 +390,20 @@ impl Table {
disable_base_cell_style: false,
column_width_config: ColumnWidthConfig::auto(),
pinned_cols: 0,
+ column_filter: None,
}
}
+ /// Sets a per-column visibility mask. Columns whose entry is `true` are filtered out (hidden).
+ ///
+ /// This is useful when column visibility is driven by state that isn't part of the column
+ /// width config (for example a `Static`/`Explicit` width config). When set, this overrides
+ /// any filter derived from the column width config.
+ pub fn column_filter(mut self, filter: TableRow<bool>) -> Self {
+ self.column_filter = Some(filter);
+ self
+ }
+
/// Disables based styling of row cell (paddings, text ellipsis, nowrap, etc), keeping width settings
///
/// Doesn't affect base style of header cell.
@@ -646,18 +660,28 @@ pub fn render_table_row(
});
let pinned_cols = table_context.pinned_cols;
+ let column_filter = &table_context.column_filter;
if is_pinned_layout(pinned_cols, cols) {
- let mut items_vec: Vec<AnyElement> = items.map(IntoElement::into_any_element).into_vec();
- let mut widths_vec: Vec<Option<Length>> = column_widths.into_vec();
-
- let scrollable_items: Vec<AnyElement> = items_vec.drain(pinned_cols..).collect();
- let scrollable_widths: Vec<Option<Length>> = widths_vec.drain(pinned_cols..).collect();
+ let items_vec: Vec<AnyElement> = items.map(IntoElement::into_any_element).into_vec();
+ let widths_vec: Vec<Option<Length>> = column_widths.into_vec();
+
+ // Drop filtered columns before splitting into pinned/scrollable sections. The number of
+ // pinned columns that survive filtering determines where the kept cells are split.
+ let pinned_visible = (0..pinned_cols)
+ .filter(|&idx| column_is_visible(column_filter, idx))
+ .count();
+ let mut kept: Vec<(AnyElement, Option<Length>)> = items_vec
+ .into_iter()
+ .zip(widths_vec)
+ .enumerate()
+ .filter(|(idx, _)| column_is_visible(column_filter, *idx))
+ .map(|(_, pair)| pair)
+ .collect();
+ let scrollable: Vec<(AnyElement, Option<Length>)> = kept.drain(pinned_visible..).collect();
let pinned_section = div().flex().flex_row().flex_shrink_0().children(
- items_vec
- .into_iter()
- .zip(widths_vec)
+ kept.into_iter()
.map(|(cell, width)| render_cell(width, cell, &table_context, cx)),
);
@@ -671,9 +695,8 @@ pub fn render_table_row(
.flex()
.child(
div().flex().flex_row().children(
- scrollable_items
+ scrollable
.into_iter()
- .zip(scrollable_widths)
.map(|(cell, width)| render_cell(width, cell, &table_context, cx)),
),
);
@@ -691,7 +714,9 @@ pub fn render_table_row(
.into_vec()
.into_iter()
.zip(column_widths.into_vec())
- .map(|(cell, width)| render_cell(width, cell, &table_context, cx)),
+ .enumerate()
+ .filter(|(idx, _)| column_is_visible(column_filter, *idx))
+ .map(|(_, (cell, width))| render_cell(width, cell, &table_context, cx)),
);
}
@@ -735,52 +760,61 @@ pub fn render_table_header(
let use_ui_font = table_context.use_ui_font;
let resize_info_ref = resize_info.as_ref();
+ let column_filter = &table_context.column_filter;
if is_pinned_layout(pinned_cols, cols) {
- let mut headers_vec: Vec<AnyElement> = headers
+ let headers_vec: Vec<AnyElement> = headers
.into_vec()
.into_iter()
.map(IntoElement::into_any_element)
.collect();
- let mut widths_vec: Vec<Option<Length>> = column_widths.into_vec();
-
- let scrollable_headers: Vec<AnyElement> = headers_vec.drain(pinned_cols..).collect();
- let scrollable_widths: Vec<Option<Length>> = widths_vec.drain(pinned_cols..).collect();
+ let widths_vec: Vec<Option<Length>> = column_widths.into_vec();
+
+ // Keep the original column index alongside each visible header so that resize info
+ // (which is indexed by original column position) stays correct after filtering.
+ let pinned_visible = (0..pinned_cols)
+ .filter(|&idx| column_is_visible(column_filter, idx))
+ .count();
+ let mut kept: Vec<(usize, AnyElement, Option<Length>)> = headers_vec
+ .into_iter()
+ .zip(widths_vec)
+ .enumerate()
+ .filter(|(idx, _)| column_is_visible(column_filter, *idx))
+ .map(|(idx, (h, width))| (idx, h, width))
+ .collect();
+ let scrollable: Vec<(usize, AnyElement, Option<Length>)> =
+ kept.drain(pinned_visible..).collect();
let pinned_section =
- div().flex().flex_row().flex_shrink_0().children(
- headers_vec.into_iter().enumerate().zip(widths_vec).map(
- |((header_idx, h), width)| {
- render_header_cell(
- h,
- width,
- header_idx,
- &shared_element_id,
- resize_info_ref,
- use_ui_font,
- cx,
- )
- },
- ),
- );
-
- let inner = div().flex().flex_row().children(
- scrollable_headers
- .into_iter()
- .enumerate()
- .zip(scrollable_widths)
- .map(|((rel_idx, h), width)| {
+ div()
+ .flex()
+ .flex_row()
+ .flex_shrink_0()
+ .children(kept.into_iter().map(|(header_idx, h, width)| {
render_header_cell(
h,
width,
- pinned_cols + rel_idx,
+ header_idx,
&shared_element_id,
resize_info_ref,
use_ui_font,
cx,
)
- }),
- );
+ }));
+
+ let inner = div().flex().flex_row().children(scrollable.into_iter().map(
+ |(header_idx, h, width)| {
+ render_header_cell(
+ h,
+ width,
+ header_idx,
+ &shared_element_id,
+ resize_info_ref,
+ use_ui_font,
+ cx,
+ )
+ },
+ ));
let mut scrollable_section = div()
.id("table-header-scrollable")
.flex_grow_1()
@@ -805,6 +839,7 @@ pub fn render_table_header(
.into_iter()
.enumerate()
.zip(column_widths.into_vec())
+ .filter(|((idx, _), _)| column_is_visible(column_filter, *idx))
.map(|((header_idx, h), width)| {
render_header_cell(
h.into_any_element(),
@@ -832,6 +867,9 @@ pub struct TableRenderContext {
pub use_ui_font: bool,
pub disable_base_cell_style: bool,
pub pinned_cols: usize,
+ /// Per-column visibility mask. When `Some`, columns whose entry is `true` are filtered
+ /// out (hidden) and not rendered. Indices map to the table's original column positions.
+ pub column_filter: Option<TableRow<bool>>,
/// Scroll handle shared by all scrollable sections in rows and headers.
/// When `pinned_cols > 0`, each row's scrollable section tracks this handle so all rows
/// scroll together without requiring per-scroll re-renders.
@@ -845,11 +883,15 @@ impl TableRenderContext {
show_row_borders: table.show_row_borders,
show_row_hover: table.show_row_hover,
total_row_count: table.rows.len(),
- column_widths: table.column_width_config.widths_to_render(cx),
+ column_widths: table
+ .column_width_config
+ .widths_to_render(cx)
+ .map(|widths| redistribute_hidden_widths(&widths, table.column_filter.as_ref())),
map_row: table.map_row.clone(),
use_ui_font: table.use_ui_font,
disable_base_cell_style: table.disable_base_cell_style,
pinned_cols: table.pinned_cols,
+ column_filter: table.column_filter.clone(),
h_scroll_handle,
}
}
@@ -865,9 +907,23 @@ impl TableRenderContext {
use_ui_font,
disable_base_cell_style: false,
pinned_cols: 0,
+ column_filter: None,
h_scroll_handle: None,
}
}
+
+ /// Sets the per-column visibility mask. Columns whose entry is `true` are hidden.
+ pub fn with_column_filter(mut self, column_filter: Option<TableRow<bool>>) -> Self {
+ self.column_filter = column_filter;
+ self
+ }
+}
+
+/// Returns `true` when the column at `col_idx` should be rendered (i.e. not filtered out).
+fn column_is_visible(filter: &Option<TableRow<bool>>, col_idx: usize) -> bool {
+ filter
+ .as_ref()
+ .map_or(true, |mask| !mask.get(col_idx).copied().unwrap_or(false))
}
/// Builds resize dividers for the given column range, positioned absolutely from `left: 0`.
@@ -1090,6 +1146,7 @@ impl RenderOnce for Table {
None,
Some(render_redistributable_columns_resize_handles(
columns_state,
+ self.column_filter.as_ref(),
window,
cx,
)),
@@ -1127,7 +1184,7 @@ impl RenderOnce for Table {
))
})
.when_some(redistributable_entity, |this, widths| {
- bind_redistributable_columns(this, widths)
+ bind_redistributable_columns(this, widths, self.column_filter.clone())
})
.when_some(resizable_entity, |this, entity| {
let scroll_handle_for_drag = h_scroll_handle.clone();
diff --git a/crates/ui/src/components/data_table/table_row.rs b/crates/ui/src/components/data_table/table_row.rs
index 9ef75e4cbbb..94d9910df33 100644
--- a/crates/ui/src/components/data_table/table_row.rs
+++ b/crates/ui/src/components/data_table/table_row.rs
@@ -74,6 +74,10 @@ impl<T> TableRow<T> {
&self.0
}
+ pub fn as_mut_slice(&mut self) -> &mut [T] {
+ &mut self.0
+ }
+
pub fn into_vec(self) -> Vec<T> {
self.0
}
diff --git a/crates/ui/src/components/data_table/tests.rs b/crates/ui/src/components/data_table/tests.rs
index 509cceca712..652ef47467f 100644
--- a/crates/ui/src/components/data_table/tests.rs
+++ b/crates/ui/src/components/data_table/tests.rs
@@ -319,6 +319,130 @@ mod drag_handle {
);
}
+mod drag_with_hidden_columns {
+ use super::*;
+
+ // Dragging with hidden (filtered) columns: the resize dividers are laid out using the
+ // *redistributed* (visible-only) widths, so `compute_drag_preview` must do its geometry in
+ // that same space and skip hidden columns when propagating the resize to a neighbor.
+
+ /// Mirrors how the renderer turns raw widths into the on-screen layout: hidden columns
+ /// collapse to zero and their space is redistributed across the visible columns.
+ fn redistributed(widths: &[f32], hidden: &[bool]) -> Vec<f32> {
+ let visible_sum: f32 = widths
+ .iter()
+ .zip(hidden)
+ .filter(|(_, is_hidden)| !**is_hidden)
+ .map(|(width, _)| *width)
+ .sum();
+ widths
+ .iter()
+ .zip(hidden)
+ .map(|(width, is_hidden)| {
+ if *is_hidden {
+ 0.0
+ } else {
+ *width / visible_sum
+ }
+ })
+ .collect()
+ }
+
+ #[test]
+ fn drag_without_hidden_columns_is_unchanged() {
+ // Guards the pre-existing behavior: with no hidden mask the drag operates on the raw
+ // widths directly (the visible space and the raw space are the same).
+ let resize_behavior = TableRow::from_vec(vec![TableResizeBehavior::Resizable; 3], 3);
+ let widths = TableRow::from_vec(vec![1.0 / 3.0; 3], 3);
+
+ let result = RedistributableColumnsState::compute_drag_preview(
+ widths,
+ &resize_behavior,
+ None,
+ 1,
+ 0.8,
+ 0.0,
+ );
+
+ let result = result.as_slice();
+ let boundary = result[0] + result[1];
+ assert!(
+ (boundary - 0.8).abs() < 1e-6,
+ "expected the boundary after column 1 to follow the cursor to 0.8: {result:?}",
+ );
+ assert!(
+ (result[0] - 1.0 / 3.0).abs() < 1e-6,
+ "column 0 must not be affected: {result:?}",
+ );
+ }
+
+ #[test]
+ fn drag_boundary_follows_cursor_with_hidden_column() {
+ // Three equal columns; column 0 is hidden. The two visible columns each render at 0.5
+ // of the container. The user grabs the divider between the visible columns (original
+ // index 1) and drags the cursor to 70% of the container. The boundary between the
+ // visible columns should follow the cursor to 0.7.
+ let resize_behavior = TableRow::from_vec(vec![TableResizeBehavior::Resizable; 3], 3);
+ let widths = TableRow::from_vec(vec![1.0 / 3.0; 3], 3);
+ let hidden = [true, false, false];
+ let hidden_mask = TableRow::from_vec(hidden.to_vec(), 3);
+
+ let result = RedistributableColumnsState::compute_drag_preview(
+ widths,
+ &resize_behavior,
+ Some(&hidden_mask),
+ 1,
+ 0.7,
+ 0.0,
+ );
+
+ let rendered = redistributed(result.as_slice(), &hidden);
+ assert!(
+ (rendered[1] - 0.7).abs() < 1e-3,
+ "expected the visible boundary to follow the cursor to 0.7, got {} (raw {:?})",
+ rendered[1],
+ result.as_slice(),
+ );
+ }
+
+ #[test]
+ fn drag_does_not_resize_hidden_neighbor() {
+ // Three equal columns; the middle column (1) is hidden. The only divider the user can
+ // grab sits between visible columns 0 and 2 (original index 0). Dragging it must resize
+ // the next *visible* column (2) and leave the hidden column's width untouched.
+ let resize_behavior = TableRow::from_vec(vec![TableResizeBehavior::Resizable; 3], 3);
+ let widths = TableRow::from_vec(vec![1.0 / 3.0; 3], 3);
+ let hidden = [false, true, false];
+ let hidden_mask = TableRow::from_vec(hidden.to_vec(), 3);
+
+ let result = RedistributableColumnsState::compute_drag_preview(
+ widths,
+ &resize_behavior,
+ Some(&hidden_mask),
+ 0,
+ 0.7,
+ 0.0,
+ );
+
+ let result = result.as_slice();
+ assert!(
+ (result[1] - 1.0 / 3.0).abs() < 1e-6,
+ "hidden column width must be preserved, but it changed: {result:?}",
+ );
+ // The drag moved width from visible column 2 to visible column 0, so the total is
+ // unchanged and the next *visible* column absorbed the resize.
+ let total: f32 = result.iter().sum();
+ assert!(
+ (total - 1.0).abs() < 1e-6,
+ "total must be preserved: {result:?}"
+ );
+ assert!(
+ result[0] > 1.0 / 3.0 && result[2] < 1.0 / 3.0,
+ "expected the resize to be absorbed by the next visible column: {result:?}",
+ );
+ }
+}
+
mod resizable_drag {
use super::*;
@@ -419,3 +543,115 @@ mod pin_layout {
assert!(is_pinned_layout(4, 5));
}
}
+
+mod column_filter {
+ use super::super::column_is_visible;
+ use super::*;
+ use crate::{redistribute_hidden_fractions, redistribute_hidden_widths};
+ use gpui::{DefiniteLength, Length};
+
+ fn frac_row(values: &[f32]) -> TableRow<f32> {
+ TableRow::from_vec(values.to_vec(), values.len())
+ }
+
+ fn hidden_row(values: &[bool]) -> TableRow<bool> {
+ TableRow::from_vec(values.to_vec(), values.len())
+ }
+
+ fn width_row(values: &[f32]) -> TableRow<Length> {
+ TableRow::from_vec(
+ values
+ .iter()
+ .map(|fraction| Length::Definite(DefiniteLength::Fraction(*fraction)))
+ .collect(),
+ values.len(),
+ )
+ }
+
+ fn width_fractions(widths: &TableRow<Length>) -> Vec<f32> {
+ widths
+ .as_slice()
+ .iter()
+ .map(|length| match length {
+ Length::Definite(DefiniteLength::Fraction(fraction)) => *fraction,
+ other => panic!("expected fraction, got {other:?}"),
+ })
+ .collect()
+ }
+
+ #[test]
+ fn column_is_visible_respects_mask() {
+ let filter = Some(hidden_row(&[false, true, false]));
+ assert!(column_is_visible(&filter, 0));
+ assert!(!column_is_visible(&filter, 1));
+ assert!(column_is_visible(&filter, 2));
+ // Indices outside the mask default to visible.
+ assert!(column_is_visible(&filter, 5));
+ }
+
+ #[test]
+ fn column_is_visible_without_filter_is_always_visible() {
+ let filter: Option<TableRow<bool>> = None;
+ assert!(column_is_visible(&filter, 0));
+ assert!(column_is_visible(&filter, 100));
+ }
+
+ #[test]
+ fn redistribute_widths_is_identity_without_hidden_columns() {
+ let widths = width_row(&[0.25, 0.25, 0.25, 0.25]);
+ assert_eq!(
+ width_fractions(&redistribute_hidden_widths(&widths, None)),
+ vec![0.25, 0.25, 0.25, 0.25]
+ );
+
+ let none_hidden = hidden_row(&[false, false, false, false]);
+ assert_eq!(
+ width_fractions(&redistribute_hidden_widths(&widths, Some(&none_hidden))),
+ vec![0.25, 0.25, 0.25, 0.25]
+ );
+ }
+
+ #[test]
+ fn redistribute_widths_scales_visible_columns_to_fill() {
+ let widths = width_row(&[0.25, 0.25, 0.25, 0.25]);
+ let hidden = hidden_row(&[false, true, false, false]);
+ let result = width_fractions(&redistribute_hidden_widths(&widths, Some(&hidden)));
+
+ // The hidden column keeps its stored width rather than being zeroed out (it is simply
+ // not rendered), so its width is restored intact when it is shown again.
+ assert_eq!(result[1], 0.25);
+ // The visible columns expand to fill the container.
+ let visible_sum: f32 = result[0] + result[2] + result[3];
+ assert!(
+ (visible_sum - 1.0).abs() < 1e-6,
+ "visible sum was {visible_sum}"
+ );
+ // Equal initial fractions stay equal after redistribution.
+ assert!((result[0] - result[2]).abs() < 1e-6);
+ assert!((result[0] - result[3]).abs() < 1e-6);
+ }
+
+ #[test]
+ fn redistribute_fractions_scales_visible_columns_to_fill() {
+ let fractions = frac_row(&[0.25, 0.25, 0.25, 0.25]);
+ let hidden = hidden_row(&[false, true, false, false]);
+ let result = redistribute_hidden_fractions(&fractions, Some(&hidden));
+ let result = result.as_slice();
+
+ assert_eq!(result[1], 0.25);
+ let visible_sum: f32 = result[0] + result[2] + result[3];
+ assert!(
+ (visible_sum - 1.0).abs() < 1e-6,
+ "visible sum was {visible_sum}"
+ );
+ }
+
+ #[test]
+ fn redistribute_fractions_is_identity_without_hidden_columns() {
+ let fractions = frac_row(&[0.2, 0.3, 0.5]);
+ assert_eq!(
+ redistribute_hidden_fractions(&fractions, None).as_slice(),
+ &[0.2, 0.3, 0.5]
+ );
+ }
+}
diff --git a/crates/ui/src/components/redistributable_columns.rs b/crates/ui/src/components/redistributable_columns.rs
index cb5da35d565..0fa93c8ba35 100644
--- a/crates/ui/src/components/redistributable_columns.rs
+++ b/crates/ui/src/components/redistributable_columns.rs
@@ -1,11 +1,3 @@
-use std::rc::Rc;
-
-use gpui::{
- AbsoluteLength, AppContext as _, Bounds, DefiniteLength, DragMoveEvent, Empty, Entity,
- EntityId, Length, Stateful, WeakEntity,
-};
-use itertools::intersperse_with;
-
use super::data_table::{
ResizableColumnsState,
table_row::{IntoTableRow as _, TableRow},
@@ -15,6 +7,11 @@ use crate::{
IntoElement, ParentElement, Pixels, StatefulInteractiveElement, Styled, Window, div, h_flex,
px,
};
+use gpui::{
+ AbsoluteLength, AppContext as _, Bounds, DefiniteLength, DragMoveEvent, Empty, Entity,
+ EntityId, Length, Stateful, WeakEntity,
+};
+use std::rc::Rc;
pub(crate) const RESIZE_COLUMN_WIDTH: f32 = 8.0;
pub(crate) const RESIZE_DIVIDER_WIDTH: f32 = 1.0;
@@ -270,6 +267,7 @@ impl RedistributableColumnsState {
fn on_drag_move(
&mut self,
drag_event: &DragMoveEvent<DraggedColumn>,
+ hidden: Option<&TableRow<bool>>,
window: &mut Window,
cx: &mut Context<Self>,
) {
@@ -280,7 +278,6 @@ impl RedistributableColumnsState {
return;
}
- let mut col_position = 0.0;
let rem_size = window.rem_size();
let col_idx = drag_event.drag(cx).col_idx;
@@ -290,28 +287,107 @@ impl RedistributableColumnsState {
rem_size,
);
- let mut widths = self
+ let widths = self
.committed_widths
.map_ref(|length| Self::get_fraction(length, bounds_width, rem_size));
- for length in widths[0..=col_idx].iter() {
+ let drag_fraction = (drag_position.x - bounds.left()) / bounds_width;
+
+ let widths = Self::compute_drag_preview(
+ widths,
+ &self.resize_behavior,
+ hidden,
+ col_idx,
+ drag_fraction,
+ divider_width,
+ );
+
+ self.preview_widths = widths.map(DefiniteLength::Fraction);
+ }
+
+ /// Computes the preview column fractions produced by dragging the divider after `col_idx`
+ /// to `drag_fraction` (the cursor's x position expressed as a fraction of the container
+ /// width). `divider_width` is the resize-divider width as a fraction of the container.
+ ///
+ /// The on-screen layout only contains the visible columns, with the hidden columns' width
+ /// budget redistributed across them (see [`redistribute_hidden_widths`]), so the geometry
+ /// here is done in that visible/redistributed space: the raw `widths` are compacted to the
+ /// visible columns and scaled to match the rendered layout, the drag is applied there (which
+ /// also makes neighbor propagation skip hidden columns), and the result is mapped back to
+ /// the raw widths, leaving hidden columns untouched.
+ ///
+ /// Extracted as a pure function so the drag math can be unit tested, mirroring the
+ /// `drag_column_handle` / `propagate_resize_diff` helpers.
+ pub(crate) fn compute_drag_preview(
+ mut widths: TableRow<f32>,
+ resize_behavior: &TableRow<TableResizeBehavior>,
+ hidden: Option<&TableRow<bool>>,
+ col_idx: usize,
+ drag_fraction: f32,
+ divider_width: f32,
+ ) -> TableRow<f32> {
+ let visible_cols: Vec<usize> = (0..widths.cols())
+ .filter(|idx| !is_column_hidden(hidden, *idx))
+ .collect();
+
+ // Dividers are only rendered after visible columns, so a hidden `col_idx` should be
+ // impossible; bail out rather than resizing the wrong column.
+ let Some(divider_position) = visible_cols.iter().position(|&idx| idx == col_idx) else {
+ return widths;
+ };
+
+ let total_sum: f32 = widths.as_slice().iter().sum();
+ let visible_sum: f32 = visible_cols.iter().map(|&idx| widths[idx]).sum();
+ // The drag only moves width between visible columns, so `visible_sum` (and therefore
+ // this scale) is the same before and after the drag, making the mapping back exact.
+ let scale = if visible_sum > 0.0 {
+ total_sum / visible_sum
+ } else {
+ 1.0
+ };
+
+ let mut rendered_widths = TableRow::from_vec(
+ visible_cols
+ .iter()
+ .map(|&idx| widths[idx] * scale)
+ .collect(),
+ visible_cols.len(),
+ );
+ let rendered_behavior = TableRow::from_vec(
+ visible_cols
+ .iter()
+ .map(|&idx| resize_behavior[idx])
+ .collect(),
+ visible_cols.len(),
+ );
+
+ let mut col_position = 0.0;
+ for length in rendered_widths[0..=divider_position].iter() {
col_position += length + divider_width;
}
let mut total_length_ratio = col_position;
- for length in widths[col_idx + 1..].iter() {
+ for length in rendered_widths[divider_position + 1..].iter() {
total_length_ratio += length;
}
- let cols = self.resize_behavior.cols();
- total_length_ratio += (cols - 1 - col_idx) as f32 * divider_width;
+ let cols = rendered_behavior.cols();
+ total_length_ratio += (cols - 1 - divider_position) as f32 * divider_width;
- let drag_fraction = (drag_position.x - bounds.left()) / bounds_width;
let drag_fraction = drag_fraction * total_length_ratio;
let diff = drag_fraction - col_position - divider_width / 2.0;
- Self::drag_column_handle(diff, col_idx, &mut widths, &self.resize_behavior);
+ Self::drag_column_handle(
+ diff,
+ divider_position,
+ &mut rendered_widths,
+ &rendered_behavior,
+ );
- self.preview_widths = widths.map(DefiniteLength::Fraction);
+ for (visible_position, &idx) in visible_cols.iter().enumerate() {
+ widths[idx] = rendered_widths[visible_position] / scale;
+ }
+
+ widths
}
pub(crate) fn drag_column_handle(
@@ -385,9 +461,99 @@ impl RedistributableColumnsState {
}
}
+/// Returns `true` when the column at `idx` is hidden by `hidden`.
+pub fn is_column_hidden(hidden: Option<&TableRow<bool>>, idx: usize) -> bool {
+ hidden
+ .and_then(|mask| mask.get(idx).copied())
+ .unwrap_or(false)
+}
+
+/// Redistributes the fractional width budget of hidden columns across the visible columns so the
+/// visible columns fill the container instead of leaving a gap. Hidden columns keep their stored
+/// width (they are never rendered, so the value is not shown) and `Absolute` widths are left
+/// untouched. Returns the widths unchanged when no column is hidden.
+pub fn redistribute_hidden_widths(
+ widths: &TableRow<Length>,
+ hidden: Option<&TableRow<bool>>,
+) -> TableRow<Length> {
+ if !(0..widths.cols()).any(|idx| is_column_hidden(hidden, idx)) {
+ return widths.clone();
+ }
+
+ let mut total_fraction_sum = 0.0;
+ let mut visible_fraction_sum = 0.0;
+ for (idx, width) in widths.as_slice().iter().enumerate() {
+ if let Length::Definite(DefiniteLength::Fraction(fraction)) = width {
+ total_fraction_sum += *fraction;
+ if !is_column_hidden(hidden, idx) {
+ visible_fraction_sum += *fraction;
+ }
+ }
+ }
+ let scale = if visible_fraction_sum > 0.0 {
+ total_fraction_sum / visible_fraction_sum
+ } else {
+ 1.0
+ };
+
+ let scaled: Vec<Length> = widths
+ .as_slice()
+ .iter()
+ .enumerate()
+ .map(|(idx, width)| match width {
+ Length::Definite(DefiniteLength::Fraction(fraction))
+ if !is_column_hidden(hidden, idx) =>
+ {
+ Length::Definite(DefiniteLength::Fraction(fraction * scale))
+ }
+ other => *other,
+ })
+ .collect();
+ TableRow::from_vec(scaled, widths.cols())
+}
+
+/// Fraction-valued counterpart of [`redistribute_hidden_widths`].
+pub fn redistribute_hidden_fractions(
+ fractions: &TableRow<f32>,
+ hidden: Option<&TableRow<bool>>,
+) -> TableRow<f32> {
+ if !(0..fractions.cols()).any(|idx| is_column_hidden(hidden, idx)) {
+ return fractions.clone();
+ }
+
+ let total_sum: f32 = fractions.as_slice().iter().sum();
+ let visible_sum: f32 = fractions
+ .as_slice()
+ .iter()
+ .enumerate()
+ .filter(|(idx, _)| !is_column_hidden(hidden, *idx))
+ .map(|(_, fraction)| *fraction)
+ .sum();
+ let scale = if visible_sum > 0.0 {
+ total_sum / visible_sum
+ } else {
+ 1.0
+ };
+
+ let scaled: Vec<f32> = fractions
+ .as_slice()
+ .iter()
+ .enumerate()
+ .map(|(idx, fraction)| {
+ if is_column_hidden(hidden, idx) {
+ *fraction
+ } else {
+ fraction * scale
+ }
+ })
+ .collect();
+ TableRow::from_vec(scaled, fractions.cols())
+}
+
pub fn bind_redistributable_columns(
container: Div,
columns_state: Entity<RedistributableColumnsState>,
+ hidden: Option<TableRow<bool>>,
) -> Div {
container
.on_drag_move::<DraggedColumn>({
@@ -397,7 +563,7 @@ pub fn bind_redistributable_columns(
return;
}
columns_state.update(cx, |columns, cx| {
- columns.on_drag_move(event, window, cx);
+ columns.on_drag_move(event, hidden.as_ref(), window, cx);
});
}
})
@@ -420,65 +586,70 @@ pub fn bind_redistributable_columns(
pub fn render_redistributable_columns_resize_handles(
columns_state: &Entity<RedistributableColumnsState>,
+ hidden: Option<&TableRow<bool>>,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let (column_widths, resize_behavior) = {
let state = columns_state.read(cx);
- (state.widths_to_render(), state.resize_behavior().clone())
+ (
+ redistribute_hidden_widths(&state.widths_to_render(), hidden),
+ state.resize_behavior().clone(),
+ )
};
- let mut column_ix = 0;
- let resize_behavior = Rc::new(resize_behavior);
- let dividers = intersperse_with(
- column_widths
- .as_slice()
- .iter()
- .copied()
- .map(|width| resize_spacer(width).into_any_element()),
- || {
- let current_column_ix = column_ix;
- let resize_behavior = Rc::clone(&resize_behavior);
- let columns_state = columns_state.clone();
- column_ix += 1;
+ // Only the visible columns participate in the layout; filtered columns are skipped entirely
+ // (no spacer, no divider) so we don't draw a stray resize line where a hidden column was.
+ let visible_cols: Vec<usize> = (0..column_widths.cols())
+ .filter(|idx| !is_column_hidden(hidden, *idx))
+ .collect();
+
+ let mut children: Vec<AnyElement> = Vec::with_capacity(visible_cols.len() * 2);
+ for (position, &col_idx) in visible_cols.iter().enumerate() {
+ children.push(resize_spacer(column_widths[col_idx]).into_any_element());
+
+ // A divider is rendered after every visible column except the last, mirroring the
+ // original `intersperse` behavior but in terms of visible columns.
+ let is_last_visible = position + 1 == visible_cols.len();
+ if is_last_visible {
+ continue;
+ }
- {
- let divider = div().id(current_column_ix).relative().top_0();
- let entity_id = columns_state.entity_id();
- let on_reset: Rc<dyn Fn(&mut Window, &mut App)> = {
- let columns_state = columns_state.clone();
- Rc::new(move |window, cx| {
- columns_state.update(cx, |columns, cx| {
- columns.reset_column_to_initial_width(current_column_ix, window);
- cx.notify();
- });
- })
- };
- let on_drag_end: Option<Rc<dyn Fn(&mut App)>> = {
- Some(Rc::new(move |cx| {
- columns_state.update(cx, |state, _| state.commit_preview());
- }))
- };
- render_column_resize_divider(
- divider,
- current_column_ix,
- resize_behavior[current_column_ix].is_resizable(),
- entity_id,
- on_reset,
- on_drag_end,
- window,
- cx,
- )
- }
- },
- );
+ let columns_state = columns_state.clone();
+ let divider = div().id(col_idx).relative().top_0();
+ let entity_id = columns_state.entity_id();
+ let on_reset: Rc<dyn Fn(&mut Window, &mut App)> = {
+ let columns_state = columns_state.clone();
+ Rc::new(move |window, cx| {
+ columns_state.update(cx, |columns, cx| {
+ columns.reset_column_to_initial_width(col_idx, window);
+ cx.notify();
+ });
+ })
+ };
+ let on_drag_end: Option<Rc<dyn Fn(&mut App)>> = {
+ Some(Rc::new(move |cx| {
+ columns_state.update(cx, |state, _| state.commit_preview());
+ }))
+ };
+ children.push(render_column_resize_divider(
+ divider,
+ col_idx,
+ resize_behavior[col_idx].is_resizable(),
+ entity_id,
+ on_reset,
+ on_drag_end,
+ window,
+ cx,
+ ));
+ }
h_flex()
.id("resize-handles")
.absolute()
.inset_0()
.w_full()
- .children(dividers)
+ .children(children)
.into_any_element()
}