1use crate::capabilities::foundation::theme::use_theme;
2use gpui::{prelude::FluentBuilder as _, *};
3use std::collections::HashMap;
4use std::rc::Rc;
5
6#[derive(Clone, Debug, PartialEq)]
13pub enum CellEditor {
14 Text,
16 Number,
18 Checkbox,
20 Custom,
27}
28
29#[derive(Clone, Debug, PartialEq)]
30pub struct CellPosition {
31 pub row: usize,
32 pub col: usize,
33}
34
35#[derive(Clone, Debug, PartialEq)]
36pub enum GridSortDirection {
37 Ascending,
38 Descending,
39 None,
40}
41
42pub struct GridColumnDef<T: 'static> {
43 pub id: SharedString,
44 pub header: SharedString,
45 pub width: Pixels,
46 pub min_width: Option<Pixels>,
47 pub max_width: Option<Pixels>,
48 pub resizable: bool,
49 pub sortable: bool,
50 pub editable: bool,
51 pub editor: CellEditor,
52 pub cell_renderer: Rc<dyn Fn(&T, usize) -> AnyElement>,
53 pub value_getter: Rc<dyn Fn(&T) -> String>,
54 pub value_setter: Option<Rc<dyn Fn(&mut T, &str)>>,
55}
56
57impl<T: 'static> GridColumnDef<T> {
58 pub fn new<S: Into<SharedString>>(
59 id: S,
60 header: S,
61 renderer: impl Fn(&T, usize) -> AnyElement + 'static,
62 getter: impl Fn(&T) -> String + 'static,
63 ) -> Self {
64 Self {
65 id: id.into(),
66 header: header.into(),
67 width: px(150.0),
68 min_width: None,
69 max_width: None,
70 resizable: true,
71 sortable: false,
72 editable: false,
73 editor: CellEditor::Text,
74 cell_renderer: Rc::new(renderer),
75 value_getter: Rc::new(getter),
76 value_setter: None,
77 }
78 }
79
80 pub fn width(mut self, width: Pixels) -> Self {
81 self.width = width;
82 self
83 }
84
85 pub fn min_width(mut self, width: Pixels) -> Self {
86 self.min_width = Some(width);
87 self
88 }
89
90 pub fn max_width(mut self, width: Pixels) -> Self {
91 self.max_width = Some(width);
92 self
93 }
94
95 pub fn resizable(mut self, resizable: bool) -> Self {
96 self.resizable = resizable;
97 self
98 }
99
100 pub fn sortable(mut self, sortable: bool) -> Self {
101 self.sortable = sortable;
102 self
103 }
104
105 pub fn editable(mut self, editable: bool) -> Self {
106 self.editable = editable;
107 self
108 }
109
110 pub fn editor(mut self, editor: CellEditor) -> Self {
111 self.editor = editor;
112 self
113 }
114
115 pub fn value_setter(mut self, setter: impl Fn(&mut T, &str) + 'static) -> Self {
116 self.value_setter = Some(Rc::new(setter));
117 self
118 }
119
120 fn clamp_width(&self, width: Pixels) -> Pixels {
121 let min_width = self.min_width.unwrap_or(px(50.0)).max(px(0.0));
122 let max_width = self.max_width.map(|max| max.max(min_width));
123 max_width.map_or(width.max(min_width), |max| width.max(min_width).min(max))
124 }
125}
126
127pub struct DataGridState<T: 'static> {
128 data: Vec<T>,
129 columns: Vec<GridColumnDef<T>>,
130 editing_cell: Option<CellPosition>,
131 edit_value: String,
132 column_widths: HashMap<SharedString, Pixels>,
133 sort_column: Option<SharedString>,
134 sort_direction: GridSortDirection,
135 focus_handle: Option<FocusHandle>,
136 resizing_column: Option<usize>,
137 resize_start_x: f32,
138 resize_start_width: Pixels,
139}
140
141impl<T: 'static> DataGridState<T> {
142 pub fn new(data: Vec<T>, columns: Vec<GridColumnDef<T>>) -> Self {
143 let column_widths = columns
144 .iter()
145 .map(|col| (col.id.clone(), col.clamp_width(col.width)))
146 .collect();
147 Self {
148 data,
149 columns,
150 editing_cell: None,
151 edit_value: String::new(),
152 column_widths,
153 sort_column: None,
154 sort_direction: GridSortDirection::None,
155 focus_handle: None,
156 resizing_column: None,
157 resize_start_x: 0.0,
158 resize_start_width: px(0.0),
159 }
160 }
161
162 pub fn data(&self) -> &[T] {
163 &self.data
164 }
165
166 pub fn update_data(&mut self, update: impl FnOnce(&mut Vec<T>)) {
168 self.cancel_edit();
169 update(&mut self.data);
170 self.resort_data();
171 }
172
173 #[deprecated(note = "use update_data to preserve grid invariants")]
178 pub fn data_mut(&mut self) -> &mut Vec<T> {
179 &mut self.data
180 }
181
182 pub fn start_editing(&mut self, pos: CellPosition) {
183 if pos.col >= self.columns.len() || pos.row >= self.data.len() {
184 return;
185 }
186 if !self.columns[pos.col].editable {
187 return;
188 }
189 self.edit_value = (self.columns[pos.col].value_getter)(&self.data[pos.row]);
190 self.editing_cell = Some(pos);
191 }
192
193 pub fn commit_edit(&mut self) {
194 if let Some(pos) = self.editing_cell.take() {
195 if let Some(col) = self.columns.get(pos.col) {
196 if let Some(ref setter) = col.value_setter {
197 if let Some(row) = self.data.get_mut(pos.row) {
198 setter(row, &self.edit_value);
199 }
200 }
201 }
202 self.edit_value.clear();
203 }
204 }
205
206 pub fn cancel_edit(&mut self) {
207 self.editing_cell = None;
208 self.edit_value.clear();
209 }
210
211 fn handle_edit_key(&mut self, key: &str, key_char: Option<&str>) {
212 let Some(position) = self.editing_cell.as_ref() else {
213 return;
214 };
215 let Some(editor) = self
216 .columns
217 .get(position.col)
218 .map(|column| column.editor.clone())
219 else {
220 return;
221 };
222
223 match editor {
224 CellEditor::Checkbox => {
225 if key == "space" {
226 self.edit_value = if Self::is_truthy(&self.edit_value) {
227 "false"
228 } else {
229 "true"
230 }
231 .into();
232 }
233 }
234 CellEditor::Number => {
235 if key == "backspace" {
236 self.edit_value.pop();
237 return;
238 }
239 let Some(character) = key_char else {
240 return;
241 };
242 let is_digit = character.chars().all(|ch| ch.is_ascii_digit());
243 let is_minus = character == "-"
244 && self.edit_value.is_empty()
245 && !self.edit_value.contains('-');
246 let is_decimal = character == "." && !self.edit_value.contains('.');
247 if is_digit || is_minus || is_decimal {
248 self.edit_value.push_str(character);
249 }
250 }
251 CellEditor::Text | CellEditor::Custom => {
252 if key == "backspace" {
253 self.edit_value.pop();
254 } else if let Some(character) = key_char {
255 self.edit_value.push_str(character);
256 }
257 }
258 }
259 }
260
261 fn is_truthy(value: &str) -> bool {
262 matches!(
263 value.trim().to_ascii_lowercase().as_str(),
264 "true" | "1" | "yes" | "on"
265 )
266 }
267
268 pub fn move_edit_next(&mut self) {
269 let current = match self.editing_cell.take() {
270 Some(pos) => pos,
271 None => return,
272 };
273 if let Some(col) = self.columns.get(current.col) {
274 if let Some(ref setter) = col.value_setter {
275 if let Some(row) = self.data.get_mut(current.row) {
276 setter(row, &self.edit_value);
277 }
278 }
279 }
280 self.edit_value.clear();
281
282 let num_cols = self.columns.len();
283 let num_rows = self.data.len();
284 let mut row = current.row;
285 let mut col = current.col + 1;
286 while row < num_rows {
287 while col < num_cols {
288 if self.columns[col].editable {
289 self.start_editing(CellPosition { row, col });
290 return;
291 }
292 col += 1;
293 }
294 col = 0;
295 row += 1;
296 }
297 }
298
299 fn resort_data(&mut self) {
300 let Some(sort_column) = self.sort_column.clone() else {
301 return;
302 };
303 let Some(col_idx) = self
304 .columns
305 .iter()
306 .position(|column| column.id == sort_column)
307 else {
308 self.sort_column = None;
309 self.sort_direction = GridSortDirection::None;
310 return;
311 };
312 if self.sort_direction == GridSortDirection::None {
313 return;
314 }
315
316 let getter = self.columns[col_idx].value_getter.clone();
317 let ascending = self.sort_direction == GridSortDirection::Ascending;
318 self.data.sort_by(|a, b| {
319 let va = getter(a);
320 let vb = getter(b);
321 let ordering = match (va.parse::<f64>(), vb.parse::<f64>()) {
322 (Ok(number_a), Ok(number_b)) => number_a
323 .partial_cmp(&number_b)
324 .unwrap_or(std::cmp::Ordering::Equal),
325 _ => va.cmp(&vb),
326 };
327 if ascending {
328 ordering
329 } else {
330 ordering.reverse()
331 }
332 });
333 }
334
335 pub fn sort_by_column(&mut self, col_id: &str) {
336 let col_id_shared: SharedString = SharedString::from(col_id.to_string());
337 let Some(col_idx) = self.columns.iter().position(|c| c.id == col_id_shared) else {
338 return;
339 };
340 if !self.columns[col_idx].sortable {
341 return;
342 }
343 if self.editing_cell.is_some() {
346 self.commit_edit();
347 }
348
349 if self.sort_column.as_ref() == Some(&col_id_shared) {
350 self.sort_direction = match self.sort_direction {
351 GridSortDirection::Ascending => GridSortDirection::Descending,
352 GridSortDirection::Descending => GridSortDirection::None,
353 GridSortDirection::None => GridSortDirection::Ascending,
354 };
355 } else {
356 self.sort_column = Some(col_id_shared.clone());
357 self.sort_direction = GridSortDirection::Ascending;
358 }
359
360 if self.sort_direction == GridSortDirection::None {
361 self.sort_column = None;
362 return;
363 }
364
365 self.resort_data();
366 }
367
368 pub fn resize_column(&mut self, col_id: &str, width: Pixels) {
369 let col_id = SharedString::from(col_id.to_string());
370 let Some(column) = self.columns.iter().find(|column| column.id == col_id) else {
371 return;
372 };
373 self.column_widths.insert(col_id, column.clamp_width(width));
374 }
375
376 pub fn set_data(&mut self, data: Vec<T>) {
377 self.data = data;
378 self.editing_cell = None;
379 self.edit_value.clear();
380 self.resort_data();
381 }
382}
383
384pub struct DataGrid<T: 'static> {
385 state: Entity<DataGridState<T>>,
386 striped: bool,
387 bordered: bool,
388 compact: bool,
389 style: StyleRefinement,
390}
391
392impl<T: 'static> DataGrid<T> {
393 pub fn new(state: Entity<DataGridState<T>>) -> Self {
394 Self {
395 state,
396 striped: false,
397 bordered: true,
398 compact: false,
399 style: StyleRefinement::default(),
400 }
401 }
402
403 pub fn striped(mut self, striped: bool) -> Self {
404 self.striped = striped;
405 self
406 }
407
408 pub fn bordered(mut self, bordered: bool) -> Self {
409 self.bordered = bordered;
410 self
411 }
412
413 pub fn compact(mut self, compact: bool) -> Self {
414 self.compact = compact;
415 self
416 }
417}
418
419impl<T: 'static> Styled for DataGrid<T> {
420 fn style(&mut self) -> &mut StyleRefinement {
421 &mut self.style
422 }
423}
424
425struct ColSnapshot {
426 id: SharedString,
427 header: SharedString,
428 width: Pixels,
429 resizable: bool,
430 sortable: bool,
431 editable: bool,
432}
433
434impl<T: 'static> RenderOnce for DataGrid<T> {
435 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
436 let theme = use_theme(cx);
437 let state_entity = self.state.clone();
438 let striped = self.striped;
439 let bordered = self.bordered;
440 let compact = self.compact;
441 let user_style = self.style;
442
443 let (cell_px, cell_py) = if compact {
444 (px(10.0), px(6.0))
445 } else {
446 (px(16.0), px(12.0))
447 };
448
449 let focus_handle = state_entity.update(cx, |s, scx| {
450 if s.focus_handle.is_none() {
451 s.focus_handle = Some(scx.focus_handle());
452 }
453 s.focus_handle.clone().unwrap()
454 });
455
456 let state = state_entity.read(cx);
457 let num_rows = state.data.len();
458 let num_cols = state.columns.len();
459 let editing = state.editing_cell.clone();
460 let edit_val = state.edit_value.clone();
461 let sort_col = state.sort_column.clone();
462 let sort_dir = state.sort_direction.clone();
463
464 let col_infos: Vec<ColSnapshot> = state
465 .columns
466 .iter()
467 .map(|c| ColSnapshot {
468 id: c.id.clone(),
469 header: c.header.clone(),
470 width: state.column_widths.get(&c.id).copied().unwrap_or(c.width),
471 resizable: c.resizable,
472 sortable: c.sortable,
473 editable: c.editable,
474 })
475 .collect();
476
477 let mut all_cells: Vec<Vec<AnyElement>> = Vec::with_capacity(num_rows);
478 for row_idx in 0..num_rows {
479 let mut row_cells: Vec<AnyElement> = Vec::with_capacity(num_cols);
480 for col_idx in 0..num_cols {
481 let is_editing = editing
482 .as_ref()
483 .is_some_and(|p| p.row == row_idx && p.col == col_idx);
484 if is_editing {
485 let editor = &state.columns[col_idx].editor;
486 let edit_display = match editor {
487 CellEditor::Checkbox => {
488 if DataGridState::<T>::is_truthy(&edit_val) {
489 "☑"
490 } else {
491 "☐"
492 }
493 }
494 CellEditor::Text | CellEditor::Number | CellEditor::Custom => "",
495 };
496 let value = if edit_display.is_empty() {
497 format!("{}|", edit_val)
498 } else {
499 edit_display.to_string()
500 };
501 row_cells.push(
502 div()
503 .flex()
504 .items_center()
505 .size_full()
506 .text_size(px(13.0))
507 .text_color(theme.tokens.foreground)
508 .child(value)
509 .into_any_element(),
510 );
511 } else {
512 let content =
513 (state.columns[col_idx].cell_renderer)(&state.data[row_idx], row_idx);
514 row_cells.push(content);
515 }
516 }
517 all_cells.push(row_cells);
518 }
519
520 let total_width: f32 = col_infos.iter().map(|c| -> f32 { c.width.into() }).sum();
521 let total_width_px = px(total_width);
522
523 let header_cells: Vec<AnyElement> = col_infos
524 .iter()
525 .enumerate()
526 .map(|(col_idx, info)| {
527 let is_sorted = sort_col.as_ref() == Some(&info.id);
528 let sort_indicator = if is_sorted {
529 match sort_dir {
530 GridSortDirection::Ascending => "\u{25B2}",
531 GridSortDirection::Descending => "\u{25BC}",
532 GridSortDirection::None => "",
533 }
534 } else {
535 ""
536 };
537
538 let header_content = div()
539 .flex()
540 .items_center()
541 .gap(px(6.0))
542 .child(info.header.clone())
543 .when(!sort_indicator.is_empty(), |el| {
544 el.child(div().text_size(px(10.0)).child(sort_indicator))
545 });
546
547 let base = div()
548 .flex()
549 .items_center()
550 .justify_between()
551 .relative()
552 .w(info.width)
553 .px(cell_px)
554 .py(cell_py)
555 .text_size(px(13.0))
556 .font_weight(FontWeight::SEMIBOLD)
557 .text_color(theme.tokens.muted_foreground)
558 .bg(theme.tokens.muted.opacity(0.5))
559 .when(bordered, |el| {
560 el.border_b_1()
561 .border_r_1()
562 .border_color(theme.tokens.border)
563 })
564 .child(header_content);
565
566 let base = base.id(ElementId::NamedInteger("grid-hdr".into(), col_idx as u64));
567
568 let with_sort = if info.sortable {
569 let col_id = info.id.clone();
570 let st = state_entity.clone();
571 base.cursor(CursorStyle::PointingHand)
572 .hover(|s| s.bg(theme.tokens.muted.opacity(0.7)))
573 .on_mouse_down(MouseButton::Left, move |_, _, cx| {
574 st.update(cx, |s, scx| {
575 s.sort_by_column(&col_id);
576 scx.notify();
577 });
578 })
579 } else {
580 base
581 };
582
583 let with_resize = if info.resizable {
584 let col_width = info.width;
585 let st = state_entity.clone();
586 with_sort.child(
587 div()
588 .id(ElementId::NamedInteger("grid-rsz".into(), col_idx as u64))
589 .absolute()
590 .right(px(0.0))
591 .top(px(0.0))
592 .w(px(4.0))
593 .h_full()
594 .cursor(CursorStyle::ResizeLeftRight)
595 .hover(|s| s.bg(theme.tokens.primary.opacity(0.5)))
596 .on_mouse_down(
597 MouseButton::Left,
598 move |event: &MouseDownEvent, _, cx| {
599 cx.stop_propagation();
600 st.update(cx, |s, scx| {
601 s.resizing_column = Some(col_idx);
602 s.resize_start_x = event.position.x.into();
603 s.resize_start_width = col_width;
604 scx.notify();
605 });
606 },
607 ),
608 )
609 } else {
610 with_sort
611 };
612
613 with_resize.into_any_element()
614 })
615 .collect();
616
617 let header_row = div()
618 .flex()
619 .w(total_width_px)
620 .min_w(total_width_px)
621 .children(header_cells);
622
623 let body_rows: Vec<AnyElement> = all_cells
624 .into_iter()
625 .enumerate()
626 .map(|(row_idx, cell_contents)| {
627 let row_bg = if striped && row_idx % 2 == 1 {
628 theme.tokens.muted.opacity(0.3)
629 } else {
630 theme.tokens.background
631 };
632
633 let cells: Vec<AnyElement> = cell_contents
634 .into_iter()
635 .enumerate()
636 .map(|(col_idx, content)| {
637 let width = col_infos[col_idx].width;
638 let is_editing = editing
639 .as_ref()
640 .is_some_and(|p| p.row == row_idx && p.col == col_idx);
641 let is_editable = col_infos[col_idx].editable;
642
643 let mut cell = div()
644 .id(ElementId::NamedInteger(
645 "grid-cell".into(),
646 (row_idx * 10000 + col_idx) as u64,
647 ))
648 .flex()
649 .items_center()
650 .w(width)
651 .px(cell_px)
652 .py(cell_py)
653 .text_size(px(13.0))
654 .text_color(theme.tokens.foreground)
655 .overflow_hidden()
656 .text_ellipsis()
657 .when(bordered, |el| {
658 el.border_b_1()
659 .border_r_1()
660 .border_color(theme.tokens.border.opacity(0.5))
661 });
662
663 if is_editing {
664 cell = cell
665 .bg(theme.tokens.background)
666 .border_2()
667 .border_color(theme.tokens.ring);
668 }
669
670 if is_editable && !is_editing {
671 let st = state_entity.clone();
672 cell = cell.cursor(CursorStyle::IBeam).on_mouse_down(
673 MouseButton::Left,
674 move |event: &MouseDownEvent, window, cx| {
675 if event.click_count < 2 {
676 return;
677 }
678 let fh = st.update(cx, |s, scx| {
679 if s.editing_cell.is_some() {
680 s.commit_edit();
681 }
682 s.start_editing(CellPosition {
683 row: row_idx,
684 col: col_idx,
685 });
686 scx.notify();
687 s.focus_handle.clone()
688 });
689 if let Some(handle) = fh {
690 window.focus(&handle);
691 }
692 },
693 );
694 }
695
696 cell.child(content).into_any_element()
697 })
698 .collect();
699
700 div()
701 .flex()
702 .w(total_width_px)
703 .min_w(total_width_px)
704 .bg(row_bg)
705 .hover(|s| s.bg(theme.tokens.accent.opacity(0.1)))
706 .children(cells)
707 .into_any_element()
708 })
709 .collect();
710
711 let body = div()
712 .id("data-grid-body")
713 .flex_1()
714 .overflow_y_scroll()
715 .flex()
716 .flex_col()
717 .children(body_rows);
718
719 let state_for_keys = state_entity.clone();
720 let state_for_move = state_entity.clone();
721 let state_for_up = state_entity.clone();
722
723 div()
724 .id("data-grid-container")
725 .track_focus(&focus_handle)
726 .flex()
727 .flex_col()
728 .w_full()
729 .border_1()
730 .border_color(theme.tokens.border)
731 .rounded(theme.tokens.radius_lg)
732 .overflow_hidden()
733 .bg(theme.tokens.card)
734 .shadow_sm()
735 .on_key_down(move |event: &KeyDownEvent, _, cx| {
736 state_for_keys.update(cx, |s, scx| {
737 if s.editing_cell.is_none() {
738 return;
739 }
740 let key = event.keystroke.key.as_str();
741 if key == "enter" {
742 s.commit_edit();
743 } else if key == "escape" {
744 s.cancel_edit();
745 } else if key == "tab" {
746 s.move_edit_next();
747 } else {
748 s.handle_edit_key(
749 key,
750 event
751 .keystroke
752 .key_char
753 .as_ref()
754 .map(|character| character.as_ref()),
755 );
756 }
757 scx.notify();
758 });
759 })
760 .on_mouse_move(move |event: &MouseMoveEvent, _, cx| {
761 state_for_move.update(cx, |s, scx| {
762 if let Some(col_idx) = s.resizing_column {
763 let current_x: f32 = event.position.x.into();
764 let delta = current_x - s.resize_start_x;
765 let start_w: f32 = s.resize_start_width.into();
766 let new_width = px((start_w + delta).max(0.0));
767 let clamped = s.columns[col_idx].clamp_width(new_width);
768 let col_id = s.columns[col_idx].id.clone();
769 s.column_widths.insert(col_id, clamped);
770 scx.notify();
771 }
772 });
773 })
774 .on_mouse_up(MouseButton::Left, move |_, _, cx| {
775 state_for_up.update(cx, |s, scx| {
776 if s.resizing_column.is_some() {
777 s.resizing_column = None;
778 scx.notify();
779 }
780 });
781 })
782 .child(header_row)
783 .child(body)
784 .map(|mut el| {
785 el.style().refine(&user_style);
786 el
787 })
788 }
789}
790
791#[cfg(test)]
792mod tests {
793 use super::*;
794
795 #[derive(Clone)]
796 struct Row {
797 value: i32,
798 }
799
800 fn value_column() -> GridColumnDef<Row> {
801 GridColumnDef::new(
802 "value",
803 "Value",
804 |row: &Row, _| div().child(row.value.to_string()).into_any_element(),
805 |row: &Row| row.value.to_string(),
806 )
807 .sortable(true)
808 .editable(true)
809 .value_setter(|row, value| {
810 row.value = value.parse().expect("test value should be numeric");
811 })
812 }
813
814 #[::core::prelude::v1::test]
815 fn sorting_commits_edit_before_reordering_rows() {
816 let mut state = DataGridState::new(
817 vec![Row { value: 2 }, Row { value: 1 }],
818 vec![value_column()],
819 );
820 state.start_editing(CellPosition { row: 0, col: 0 });
821 state.edit_value = "0".into();
822
823 state.sort_by_column("value");
824
825 assert!(state.editing_cell.is_none());
826 assert_eq!(
827 state.data.iter().map(|row| row.value).collect::<Vec<_>>(),
828 [0, 1]
829 );
830 }
831
832 #[::core::prelude::v1::test]
833 fn replacing_data_reapplies_the_active_sort() {
834 let mut state = DataGridState::new(
835 vec![Row { value: 2 }, Row { value: 1 }],
836 vec![value_column()],
837 );
838 state.sort_by_column("value");
839 state.set_data(vec![Row { value: 10 }, Row { value: 3 }]);
840
841 assert_eq!(
842 state.data.iter().map(|row| row.value).collect::<Vec<_>>(),
843 [3, 10]
844 );
845 }
846
847 #[::core::prelude::v1::test]
848 fn update_data_reapplies_sort_and_cancels_editing() {
849 let mut state = DataGridState::new(
850 vec![Row { value: 2 }, Row { value: 1 }],
851 vec![value_column()],
852 );
853 state.sort_by_column("value");
854 state.start_editing(CellPosition { row: 0, col: 0 });
855
856 state.update_data(|rows| rows.push(Row { value: 0 }));
857
858 assert!(state.editing_cell.is_none());
859 assert_eq!(
860 state.data.iter().map(|row| row.value).collect::<Vec<_>>(),
861 [0, 1, 2]
862 );
863 }
864
865 #[::core::prelude::v1::test]
866 fn resize_column_respects_consistent_width_bounds() {
867 let column = value_column().min_width(px(120.0)).max_width(px(80.0));
868 let mut state = DataGridState::new(vec![Row { value: 1 }], vec![column]);
869
870 state.resize_column("value", px(20.0));
871 assert_eq!(state.column_widths[&SharedString::from("value")], px(120.0));
872
873 state.resize_column("value", px(240.0));
874 assert_eq!(state.column_widths[&SharedString::from("value")], px(120.0));
877 }
878
879 #[::core::prelude::v1::test]
880 fn number_editor_rejects_invalid_characters() {
881 let column = value_column().editor(CellEditor::Number);
882 let mut state = DataGridState::new(vec![Row { value: 1 }], vec![column]);
883 state.start_editing(CellPosition { row: 0, col: 0 });
884 state.edit_value.clear();
885
886 state.handle_edit_key("", Some("1"));
887 state.handle_edit_key("", Some("."));
888 state.handle_edit_key("", Some("2"));
889 state.handle_edit_key("", Some("."));
890 state.handle_edit_key("", Some("x"));
891
892 assert_eq!(state.edit_value, "1.2");
893 }
894
895 #[::core::prelude::v1::test]
896 fn checkbox_editor_toggles_boolean_value_with_space() {
897 let column = value_column().editor(CellEditor::Checkbox);
898 let mut state = DataGridState::new(vec![Row { value: 1 }], vec![column]);
899 state.start_editing(CellPosition { row: 0, col: 0 });
900 state.edit_value = "false".into();
901
902 state.handle_edit_key("space", None);
903 assert_eq!(state.edit_value, "true");
904
905 state.handle_edit_key("space", None);
906 assert_eq!(state.edit_value, "false");
907 }
908
909 #[::core::prelude::v1::test]
910 fn custom_editor_uses_text_editing_and_commits_value() {
911 let column = value_column().editor(CellEditor::Custom);
912 let mut state = DataGridState::new(vec![Row { value: 1 }], vec![column]);
913 state.start_editing(CellPosition { row: 0, col: 0 });
914
915 state.handle_edit_key("backspace", None);
916 state.handle_edit_key("", Some("4"));
917 state.handle_edit_key("", Some("2"));
918
919 assert_eq!(state.edit_value, "42");
920 state.commit_edit();
921
922 assert_eq!(state.data[0].value, 42);
923 assert!(state.editing_cell.is_none());
924 assert!(state.edit_value.is_empty());
925 }
926
927 #[::core::prelude::v1::test]
928 fn custom_editor_cancels_text_edits_without_mutating_the_row() {
929 let column = value_column().editor(CellEditor::Custom);
930 let mut state = DataGridState::new(vec![Row { value: 1 }], vec![column]);
931 state.start_editing(CellPosition { row: 0, col: 0 });
932
933 state.handle_edit_key("backspace", None);
934 state.handle_edit_key("", Some("9"));
935 assert_eq!(state.edit_value, "9");
936
937 state.cancel_edit();
938
939 assert_eq!(state.data[0].value, 1);
940 assert!(state.editing_cell.is_none());
941 assert!(state.edit_value.is_empty());
942 }
943}