[yew-devel] [PATCH yew-widget-toolkit v2] widget: data table: prevent duplicate yew keys for rows

Dominik Csapak d.csapak at proxmox.com
Fri May 9 09:31:03 CEST 2025


Yews diff algorithm assumes that elements in a list have unique keys, so
it can properly diff the new and old list, but our Store/Datastore does
not guarantee that records have unique keys.

For the data table rows, we used the record keys as yew keys, so this is
a problem when keys in the store are duplicated.

To prevent an application wide panic, modify keys for DataTableRows that
are to be displayed and have duplicated keys.

In debug mode, log a prominent warning, so it's easier to detect.

This is more in depth prevention of crashes/problem like in bug #6382.

Signed-off-by: Dominik Csapak <d.csapak at proxmox.com>
---
changes from v1:
* rewrite commit message a bit to be clearer.
* remove the 'fix' tag in the commit subject. Though it would fix the
  immediate crash, the proper fix is [0] and this is just another layer
  of defense against such errors

0: https://lore.proxmox.com/yew-devel/20250509071627.331064-1-d.csapak@proxmox.com/T/#u

 src/widget/data_table/data_table.rs | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)

diff --git a/src/widget/data_table/data_table.rs b/src/widget/data_table/data_table.rs
index a8fda7b..ab49d0d 100644
--- a/src/widget/data_table/data_table.rs
+++ b/src/widget/data_table/data_table.rs
@@ -919,14 +919,26 @@ impl<S: DataStore> PwtDataTable<S> {
             }
         }
 
+        // keep track of keys that are displayed, to avoid duplicates
+        let mut key_set = HashSet::new();
+
         for (filtered_pos, item) in props.store.filtered_data_range(start..end) {
-            let record_key = props.store.extract_key(&*item.record());
+            let mut record_key = props.store.extract_key(&*item.record());
 
             let mut selected = false;
             if let Some(selection) = &props.selection {
                 selected = selection.contains(&record_key);
             }
 
+            if key_set.contains(&record_key) {
+                #[cfg(debug_assertions)]
+                log::error!("duplicate key found: {record_key}");
+                // avoid duplicate key by adding the row num to the key
+                record_key = Key::from(format!("{filtered_pos}-{record_key}"))
+            }
+
+            key_set.insert(record_key.clone());
+
             let active = cursor
                 .map(|cursor| cursor == filtered_pos)
                 // if no cursor, mark first row active
-- 
2.39.5





More information about the yew-devel mailing list