Skip to content

Commit

Permalink
Add example on how to use egui_dnd without storing unique ids, by usi…
Browse files Browse the repository at this point in the history
…ng the items index as id
  • Loading branch information
lucasmerlin committed Jul 10, 2024
1 parent ae9b5ed commit 8d505ba
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 3 deletions.
74 changes: 74 additions & 0 deletions crates/egui_dnd/examples/index_as_id.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use eframe::egui;
use egui::{CentralPanel, Id};
use egui_dnd::{dnd, DragDropItem};

#[derive(Clone, Hash)]
struct Item {
name: String,
}

impl Item {
fn new(name: &str) -> Self {
Self {
name: name.to_string(),
}
}
}

// In order to use the index as id we need to implement DragDropItem for a wrapper struct
struct EnumeratedItem<T> {
item: T,
index: usize,
}

impl<T> DragDropItem for EnumeratedItem<T> {
fn id(&self) -> Id {
Id::new(self.index)
}
}

pub fn main() -> eframe::Result<()> {
let mut items = vec![
Item::new("alfred"),
Item::new("bernhard"),
Item::new("christian"),
Item::new("alfred"),
];

eframe::run_simple_native(
"DnD Simple Example",
Default::default(),
move |ctx, _frame| {
CentralPanel::default().show(ctx, |ui| {
let response = dnd(ui, "dnd_example")
// Since egui_dnd's animations rely on the ids not
// changing after the drag finished we need to disable animations
.with_animation_time(0.0)
.show(
items
.iter_mut()
.enumerate()
.map(|(i, item)| EnumeratedItem { item, index: i }),
|ui, item, handle, state| {
ui.horizontal(|ui| {
handle.ui(ui, |ui| {
if state.dragged {
ui.label("dragging");
} else {
ui.label("drag");
}
});
ui.label(&item.item.name);
});
},
);

// Since the item id may not change while a drag is ongoing we need to wait
// until the drag is finished before updating the items
if response.is_drag_finished() {
response.update_vec(&mut items);
}
});
},
)
}
6 changes: 3 additions & 3 deletions crates/egui_dnd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,10 @@ impl<'a> Dnd<'a> {
}

/// Display the drag and drop UI.
/// `items` should be an iterator over items that should be sorted.
/// `items` should be an iterator over items that should be sortable.
///
/// The items won't be sorted automatically, but you can use [Dnd::show_vec] or [DragDropResponse::update_vec] to do so.
/// If your items aren't in a vec, you have to sort them yourself.
/// The items won't be updated automatically, but you can use [Dnd::show_vec] or [DragDropResponse::update_vec] to do so.
/// If your items aren't in a vec, you have to update the order yourself.
///
/// `item_ui` is called for each item. Display your item there.
/// `item_ui` gets a [Handle] that can be used to display the drag handle.
Expand Down

0 comments on commit 8d505ba

Please sign in to comment.