egui_selectable_table/row_modification.rs
1use ahash::{HashMap, HashSet, HashSetExt};
2use std::hash::Hash;
3
4#[cfg(feature = "rayon")]
5use rayon::prelude::*;
6
7use crate::{ColumnOperations, ColumnOrdering, SelectableRow, SelectableTable, SortOrder};
8
9impl<Row, F, Conf> SelectableTable<Row, F, Conf>
10where
11 Row: Clone + Send + Sync,
12 F: Eq
13 + Hash
14 + Clone
15 + Ord
16 + Send
17 + Sync
18 + Default
19 + ColumnOperations<Row, F, Conf>
20 + ColumnOrdering<Row>,
21 Conf: Default,
22{
23 /// Modify or add rows to the table. Changes are not immediately reflected in the UI.
24 /// You must call [`recreate_rows`](#method.recreate_rows) or [`recreate_rows_no_unselect`](#method.recreate_rows_no_unselect) to apply these changes visually.
25 ///
26 /// If modifying existing and visible row, consider using [`modify_shown_row`](#method.modify_shown_row)
27 /// alongside modifying through this function which will effectively mirror [`recreate_rows`](#method.recreate_rows)
28 /// without doing an expensive call.
29 ///
30 /// Bulk additions of rows is possible through this function with a single call to
31 /// [`add_modify_row`](#method.add_modify_row) at the end.
32 ///
33 /// # Parameters:
34 /// - A closure that provides a mutable reference to the rows and optionally returns a new row.
35 /// If a row is returned, it will be added to the table.
36 ///
37 /// # Auto Reload:
38 /// - Use [`auto_reload`](#method.auto_reload) to automatically refresh the UI after a specified
39 /// number of row modifications or additions.
40 ///
41 /// # Returns
42 /// * `Option<i64>` - The row id that is used internally for the new row
43 ///
44 /// # Example:
45 /// ```rust,ignore
46 /// let new_row_id = table.add_modify_row(|rows| {
47 /// let my_row = rows.get_mut(row_id).unwrap();
48 /// // modify your row as necessary
49 ///
50 /// let new_row = MyRow {
51 /// // Define your row values
52 /// };
53 /// Some(new_row) // Optionally add a new row
54 /// });
55 /// ```
56 pub fn add_modify_row<Fn>(&mut self, table: Fn) -> Option<i64>
57 where
58 Fn: FnOnce(&mut HashMap<i64, SelectableRow<Row, F>>) -> Option<Row>,
59 {
60 let new_row = table(&mut self.rows);
61
62 let mut to_return = None;
63
64 if let Some(row) = new_row {
65 let selected_columns = HashSet::new();
66 let new_row = SelectableRow {
67 row_data: row,
68 id: self.last_id_used,
69 selected_columns,
70 };
71 to_return = Some(self.last_id_used);
72 self.rows.insert(new_row.id, new_row);
73 self.last_id_used += 1;
74 }
75
76 let reload = self.auto_reload.increment_count();
77
78 if reload {
79 self.recreate_rows();
80 }
81 to_return
82 }
83
84 /// Modify a single row by its ID
85 ///
86 /// Changes go to the source-of-truth row storage. Call [`recreate_rows`](SelectableTable::recreate_rows)
87 /// afterwards to reflect the change in the UI, or rely on `auto_reload`.
88 ///
89 /// # Example:
90 /// ```rust,ignore
91 /// table.update_row(42, |row| { row.name = "new name".into(); });
92 /// ```
93 pub fn update_row(&mut self, id: i64, f: impl FnOnce(&mut Row)) {
94 self.add_modify_row(|rows| {
95 if let Some(row) = rows.get_mut(&id) {
96 f(&mut row.row_data);
97 }
98 None
99 });
100 }
101
102 /// Modify only the rows currently displayed in the UI.
103 ///
104 /// This provides direct access to the currently formatted rows for lightweight updates.
105 ///
106 /// # Important:
107 /// - This does **not** require calling [`recreate_rows`](SelectableTable::recreate_rows) to reflect changes in the UI.
108 /// - **Do not delete rows** from inside this closure.
109 /// - Changes **evaporate** on the next [`recreate_rows`](SelectableTable::recreate_rows) call.
110 /// To persist changes, also call [`update_row`](Self::update_row) or [`add_modify_row`](Self::add_modify_row).
111 /// - Does not contribute toward `auto_reload` count.
112 ///
113 /// # When to use:
114 /// - When you need a modification visible immediately without an expensive recreate.
115 ///
116 /// # Example:
117 /// ```rust,ignore
118 /// table.patch_visible_row(|formatted_rows, indexed_ids| {
119 /// let row_id = 0;
120 /// let target_index = indexed_ids.get(&row_id).unwrap();
121 /// let row = formatted_rows.get_mut(*target_index).unwrap();
122 /// row.row_data.name = "updated".into();
123 /// });
124 /// ```
125 pub fn patch_visible_row<Fn>(&mut self, mut f: Fn)
126 where
127 Fn: FnMut(&mut Vec<SelectableRow<Row, F>>, &HashMap<i64, usize>),
128 {
129 f(&mut self.formatted_rows, &self.indexed_ids);
130 }
131
132 /// Modify only the rows currently displayed in the UI.
133 ///
134 /// This provides direct access to the currently formatted rows for lightweight updates.
135 ///
136 /// # Important:
137 /// - This does **not** require calling [`recreate_rows`](#method.recreate_rows) to reflect changes in the UI.
138 /// - **Do not delete rows** from inside this closure — doing so will **cause a panic** and break internal assumptions.
139 /// To safely delete a row, use [`add_modify_row`](#method.add_modify_row) and then call [`recreate_rows`](#method.recreate_rows) or [`recreate_rows_no_unselect`](#method.recreate_rows_no_unselect).
140 /// - Can be used to update a row and show it immediately without having to do an expensive [`recreate_rows`](#method.recreate_rows).
141 /// You can then immediately call [`add_modify_row`](#method.add_modify_row) to do the same
142 /// update so later calls to [`recreate_rows`](#method.recreate_rows) or
143 /// [`recreate_rows_no_unselect`](#method.recreate_rows_no_unselect) does not revert the changes.
144 /// - Does not contribute toward [`auto_reload`](#method.auto_reload) count.
145 ///
146 /// # Parameters:
147 /// - A closure that provides a mutable reference to the currently formatted rows and an index map.
148 ///
149 /// # When to use:
150 /// - Use when you need to modify a data that is currently displayed without having to call
151 /// [`recreate_rows`](#method.recreate_rows).
152 /// - When you need to make a temporary change to the data displayed in the UI. To persist any
153 /// changes, use [`add_modify_row`](#method.add_modify_row).
154 ///
155 /// # How to use:
156 /// 1. Get the row ID you want to modify.
157 /// 2. Use the index map to get the index of the row in the formatted rows.
158 /// 3. Use the index to get a mutable reference to the row.
159 /// 4. Safely modify the row contents.
160 /// 5. In the next frame load, the modified data is visible immediately without any additional
161 /// calls.
162 ///
163 /// # Example:
164 /// ```rust,ignore
165 /// table.modify_shown_row(|formatted_rows, indexed_ids| {
166 /// let row_id = 0;
167 /// let target_index = indexed_ids.get(&row_id).unwrap();
168 /// let row = formatted_rows.get_mut(*target_index).unwrap();
169 /// // Safely modify row contents here
170 /// });
171 /// ```
172 #[deprecated = "use `patch_visible_row` instead"]
173 pub fn modify_shown_row<Fn>(&mut self, mut rows: Fn)
174 where
175 Fn: FnMut(&mut Vec<SelectableRow<Row, F>>, &HashMap<i64, usize>),
176 {
177 rows(&mut self.formatted_rows, &self.indexed_ids);
178 }
179
180 /// Adds a new row to the bottom of the table without applying any sorting logic.
181 ///
182 /// This method inserts the row as-is at the end of the table, assigns it a unique ID, and
183 /// returns it as a `SelectableRow`. This does **not**
184 /// require calling [`recreate_rows`](#method.recreate_rows) for the row to appear in the UI.
185 ///
186 /// # Important:
187 /// - This method does not contribute toward [`auto_reload`](#method.auto_reload) count.
188 /// - Later calls to [`recreate_rows`](#method.recreate_rows) or
189 /// [`recreate_rows_no_unselect`](#method.recreate_rows_no_unselect) will sort the row again.
190 ///
191 /// # Parameters:
192 /// - `row`: The data to insert into the table.
193 ///
194 /// # Returns:
195 /// - `SelectableRow<Row, F>`: The newly added row wrapped in a `SelectableRow`.
196 ///
197 /// # Example:
198 /// ```rust,ignore
199 /// let row = Row::new(vec![cell1, cell2, cell3]);
200 /// let added_row = table.add_unsorted_row(row);
201 /// ```
202 pub fn add_unsorted_row(&mut self, row: Row) -> SelectableRow<Row, F> {
203 let selected_columns = HashSet::new();
204 let new_row = SelectableRow {
205 row_data: row,
206 id: self.last_id_used,
207 selected_columns,
208 };
209
210 self.formatted_rows.push(new_row.clone());
211 self.indexed_ids
212 .insert(new_row.id, self.formatted_rows.len() - 1);
213 self.rows.insert(new_row.id, new_row.clone());
214 self.last_id_used += 1;
215 new_row
216 }
217
218 /// Sort the rows to the current sorting order and column and save them for later reuse
219 pub(crate) fn sort_rows(&mut self) {
220 let mut row_data: Vec<SelectableRow<Row, F>> = self.clone_rows();
221 self.sort_and_index(&mut row_data);
222 self.formatted_rows = row_data;
223 }
224
225 /// Whether the given number of rows is large enough to use rayon
226 #[cfg(feature = "rayon")]
227 pub(crate) const fn use_rayon(&self, len: usize) -> bool {
228 len > self.rayon_threshold
229 }
230
231 fn clone_rows(&self) -> Vec<SelectableRow<Row, F>> {
232 #[cfg(feature = "rayon")]
233 if self.use_rayon(self.rows.len()) {
234 return self.rows.par_iter().map(|(_, v)| v.clone()).collect();
235 }
236 self.rows.values().cloned().collect()
237 }
238
239 /// Sorts `row_data` by the current sort settings and rebuilds `indexed_ids` from it
240 pub(crate) fn sort_and_index(&mut self, row_data: &mut [SelectableRow<Row, F>]) {
241 let sorted_by = &self.sorted_by;
242 let sort_order = self.sort_order;
243 let compare = |a: &SelectableRow<Row, F>, b: &SelectableRow<Row, F>| {
244 let ordering = sorted_by.order_by(&a.row_data, &b.row_data);
245 match sort_order {
246 SortOrder::Ascending => ordering,
247 SortOrder::Descending => ordering.reverse(),
248 }
249 };
250
251 #[cfg(feature = "rayon")]
252 if self.use_rayon(row_data.len()) {
253 row_data.par_sort_by(compare);
254 self.indexed_ids = row_data
255 .par_iter()
256 .enumerate()
257 .map(|(index, row)| (row.id, index))
258 .collect();
259 return;
260 }
261
262 row_data.sort_by(compare);
263
264 self.indexed_ids = row_data
265 .iter()
266 .enumerate()
267 .map(|(index, row)| (row.id, index))
268 .collect();
269 }
270}