forked from kang-sw/egui-data-table
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdemo.rs
More file actions
504 lines (431 loc) · 15.5 KB
/
demo.rs
File metadata and controls
504 lines (431 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use std::{borrow::Cow, iter::repeat_with};
use egui::{Response, Sense, Widget};
use egui::scroll_area::ScrollBarVisibility;
use egui_data_table::{
viewer::{default_hotkeys, CellWriteContext, DecodeErrorBehavior, RowCodec, UiActionContext},
RowViewer,
};
use log::info;
/* ----------------------------------------- Data Scheme ---------------------------------------- */
struct Viewer {
filter: String,
row_protection: bool,
hotkeys: Vec<(egui::KeyboardShortcut, egui_data_table::UiAction)>,
}
#[derive(Debug, Clone)]
struct Row(String, i32, bool, Grade, bool);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Grade {
A,
B,
C,
F,
}
/* -------------------------------------------- Codec ------------------------------------------- */
struct Codec;
impl RowCodec<Row> for Codec {
type DeserializeError = &'static str;
fn encode_column(&mut self, src_row: &Row, column: usize, dst: &mut String) {
match column {
0 => dst.push_str(&src_row.0),
1 => dst.push_str(&src_row.1.to_string()),
2 => dst.push_str(&src_row.2.to_string()),
3 => dst.push_str(match src_row.3 {
Grade::A => "A",
Grade::B => "B",
Grade::C => "C",
Grade::F => "F",
}),
4 => dst.push_str(&src_row.4.to_string()),
_ => unreachable!(),
}
}
fn decode_column(
&mut self,
src_data: &str,
column: usize,
dst_row: &mut Row,
) -> Result<(), DecodeErrorBehavior> {
match column {
0 => dst_row.0.replace_range(.., src_data),
1 => dst_row.1 = src_data.parse().map_err(|_| DecodeErrorBehavior::SkipRow)?,
2 => dst_row.2 = src_data.parse().map_err(|_| DecodeErrorBehavior::SkipRow)?,
3 => {
dst_row.3 = match src_data {
"A" => Grade::A,
"B" => Grade::B,
"C" => Grade::C,
"F" => Grade::F,
_ => return Err(DecodeErrorBehavior::SkipRow),
}
}
4 => dst_row.4 = src_data.parse().map_err(|_| DecodeErrorBehavior::SkipRow)?,
_ => unreachable!(),
}
Ok(())
}
fn create_empty_decoded_row(&mut self) -> Row {
Row("".to_string(), 0, false, Grade::F, false)
}
}
/* ------------------------------------ Viewer Implementation ----------------------------------- */
impl RowViewer<Row> for Viewer {
fn on_highlight_cell(&mut self, row: &Row, column: usize) {
println!("cell highlighted: row: {:?}, column: {}", row, column);
}
fn try_create_codec(&mut self, _: bool) -> Option<impl RowCodec<Row>> {
Some(Codec)
}
fn num_columns(&mut self) -> usize {
5
}
fn column_name(&mut self, column: usize) -> Cow<'static, str> {
[
"Name (Click to sort)",
"Age",
"Is Student (Not sortable)",
"Grade",
"Row locked",
][column]
.into()
}
fn is_sortable_column(&mut self, column: usize) -> bool {
[true, true, false, true, true][column]
}
fn is_editable_cell(&mut self, _column: usize, _row: usize, row_value: &Row) -> bool {
let locked = row_value.4;
// allow editing of the locked flag, but prevent editing other columns when locked.
match _column {
4 => true,
_ => !locked,
}
}
fn compare_cell(&self, row_l: &Row, row_r: &Row, column: usize) -> std::cmp::Ordering {
match column {
0 => row_l.0.cmp(&row_r.0),
1 => row_l.1.cmp(&row_r.1),
2 => unreachable!(),
3 => row_l.3.cmp(&row_r.3),
4 => row_l.4.cmp(&row_r.4),
_ => unreachable!(),
}
}
fn new_empty_row(&mut self) -> Row {
Row("".to_string(), 0, false, Grade::F, false)
}
fn set_cell_value(&mut self, src: &Row, dst: &mut Row, column: usize) {
match column {
0 => dst.0.clone_from(&src.0),
1 => dst.1 = src.1,
2 => dst.2 = src.2,
3 => dst.3 = src.3,
4 => dst.4 = src.4,
_ => unreachable!(),
}
}
fn confirm_cell_write_by_ui(
&mut self,
current: &Row,
_next: &Row,
_column: usize,
_context: CellWriteContext,
) -> bool {
if !self.row_protection {
return true;
}
!current.2
}
fn confirm_row_deletion_by_ui(&mut self, row: &Row) -> bool {
if !self.row_protection {
return true;
}
!row.2
}
fn show_cell_view(&mut self, ui: &mut egui::Ui, row: &Row, column: usize) {
let _ = match column {
0 => ui.label(&row.0),
1 => ui.label(row.1.to_string()),
2 => ui.checkbox(&mut { row.2 }, ""),
3 => ui.label(match row.3 {
Grade::A => "A",
Grade::B => "B",
Grade::C => "C",
Grade::F => "F",
}),
4 => ui.checkbox(&mut { row.4 }, ""),
_ => unreachable!(),
};
}
fn on_cell_view_response(
&mut self,
_row: &Row,
_column: usize,
resp: &egui::Response,
) -> Option<Box<Row>> {
resp.dnd_release_payload::<String>()
.map(|x| Box::new(Row((*x).clone(), 9999, false, Grade::A, false)))
}
fn show_cell_editor(
&mut self,
ui: &mut egui::Ui,
row: &mut Row,
column: usize,
) -> Option<Response> {
match column {
0 => {
egui::TextEdit::multiline(&mut row.0)
.desired_rows(1)
.code_editor()
.show(ui)
.response
}
1 => ui.add(egui::DragValue::new(&mut row.1).speed(1.0)),
2 => ui.checkbox(&mut row.2, ""),
3 => {
let grade = &mut row.3;
ui.horizontal_wrapped(|ui| {
ui.radio_value(grade, Grade::A, "A")
| ui.radio_value(grade, Grade::B, "B")
| ui.radio_value(grade, Grade::C, "C")
| ui.radio_value(grade, Grade::F, "F")
})
.inner
}
4 => ui.checkbox(&mut row.4, ""),
_ => unreachable!(),
}
.into()
}
fn row_filter_hash(&mut self) -> &impl std::hash::Hash {
&self.filter
}
fn filter_row(&mut self, row: &Row) -> bool {
row.0.contains(&self.filter)
}
fn hotkeys(
&mut self,
context: &UiActionContext,
) -> Vec<(egui::KeyboardShortcut, egui_data_table::UiAction)> {
let hotkeys = default_hotkeys(context);
self.hotkeys.clone_from(&hotkeys);
hotkeys
}
fn persist_ui_state(&self) -> bool {
true
}
fn on_highlight_change(&mut self, highlighted: &[&Row], unhighlighted: &[&Row]) {
info!("highlight {:?}", highlighted);
info!("unhighlight {:?}", unhighlighted);
}
fn on_row_updated(&mut self, row_index: usize, new_row: &Row, old_row: &Row) {
println!("row updated. row_id: {}, new_row: {:?}, old_row: {:?}", row_index, new_row, old_row);
}
fn on_row_inserted(&mut self, row_index: usize, row: &Row) {
println!("row inserted. row_id: {}, values: {:?}", row_index, row);
}
fn on_row_removed(&mut self, row_index: usize, row: &Row) {
println!("row removed. row_id: {}, values: {:?}", row_index, row);
}
}
/* ------------------------------------------ View Loop ----------------------------------------- */
struct DemoApp {
table: egui_data_table::DataTable<Row>,
viewer: Viewer,
style_override: egui_data_table::Style,
scroll_bar_always_visible: bool,
}
impl Default for DemoApp {
fn default() -> Self {
Self {
table: {
let mut rng = fastrand::Rng::new();
let mut name_gen = names::Generator::with_naming(names::Name::Numbered);
repeat_with(move || {
Row(
name_gen.next().unwrap(),
rng.i32(4..31),
rng.bool(),
match rng.i32(0..=3) {
0 => Grade::A,
1 => Grade::B,
2 => Grade::C,
_ => Grade::F,
},
false,
)
})
}
.take(100000)
.collect(),
viewer: Viewer {
filter: String::new(),
hotkeys: Vec::new(),
row_protection: false,
},
style_override: Default::default(),
scroll_bar_always_visible: false,
}
}
}
impl eframe::App for DemoApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
fn is_send<T: Send>(_: &T) {}
fn is_sync<T: Sync>(_: &T) {}
is_send(&self.table);
is_sync(&self.table);
egui::TopBottomPanel::top("MenuBar").show(ctx, |ui| {
egui::MenuBar::new().ui(ui, |ui| {
ui.hyperlink_to(
" kang-sw/egui-data-table",
"https://github.com/kang-sw/egui-data-table",
);
ui.hyperlink_to(
"(source)",
"https://github.com/kang-sw/egui-data-table/blob/master/examples/demo.rs",
);
ui.separator();
egui::widgets::global_theme_preference_buttons(ui);
ui.separator();
ui.label("Name Filter");
ui.text_edit_singleline(&mut self.viewer.filter);
ui.add(egui::Button::new("Drag me and drop on any cell").sense(Sense::drag()))
.on_hover_text(
"Dropping this will replace the cell \
content with some predefined value.",
)
.dnd_set_drag_payload(String::from("Hallo~"));
ui.menu_button("🎌 Flags", |ui| {
ui.checkbox(&mut self.viewer.row_protection, "Row Protection")
.on_hover_text(
"If checked, any rows `Is Student` marked \
won't be deleted or overwritten by UI actions.",
);
ui.checkbox(
&mut self.style_override.single_click_edit_mode,
"Single Click Edit",
)
.on_hover_text("If checked, cells will be edited with a single click.");
ui.checkbox(
&mut self.style_override.auto_shrink.x,
"Auto-shrink X",
);
ui.checkbox(
&mut self.style_override.auto_shrink.y,
"Auto-shrink Y",
);
ui.checkbox(
&mut self.scroll_bar_always_visible,
"Scrollbar always visible",
);
if ui.button("Shuffle Rows").clicked() {
fastrand::shuffle(&mut self.table);
}
})
})
});
egui::TopBottomPanel::bottom("bottom_panel").show(ctx, |ui| {
egui::Sides::new().show(ui, |_ui| {
}, |ui|{
let mut has_modifications = self.table.has_user_modification();
ui.add_enabled(false, egui::Checkbox::new(&mut has_modifications, "Has modifications"));
ui.add_enabled_ui(has_modifications, |ui| {
if ui.button("Clear").clicked() {
self.table.clear_user_modification_flag();
}
});
});
});
egui::SidePanel::left("Hotkeys")
.default_width(500.)
.show(ctx, |ui| {
ui.vertical_centered_justified(|ui| {
ui.heading("Hotkeys");
ui.separator();
ui.add_space(0.);
for (k, a) in &self.viewer.hotkeys {
egui::Button::new(format!("{a:?}"))
.shortcut_text(ctx.format_shortcut(k))
.wrap_mode(egui::TextWrapMode::Wrap)
.sense(Sense::hover())
.ui(ui);
}
});
});
egui::CentralPanel::default().show(ctx, |ui| {
match self.scroll_bar_always_visible {
true => {
ui.style_mut().spacing.scroll = egui::style::ScrollStyle::solid();
self.style_override.scroll_bar_visibility = ScrollBarVisibility::AlwaysVisible;
},
false => {
ui.style_mut().spacing.scroll = egui::style::ScrollStyle::floating();
self.style_override.scroll_bar_visibility = ScrollBarVisibility::VisibleWhenNeeded;
}
};
ui.add(
egui_data_table::Renderer::new(&mut self.table, &mut self.viewer)
.with_style(self.style_override),
)
});
}
}
/* --------------------------------------- App Entrypoint --------------------------------------- */
#[cfg(not(target_arch = "wasm32"))]
fn main() {
use eframe::App;
env_logger::init();
eframe::run_simple_native(
"Spreadsheet Demo",
eframe::NativeOptions {
centered: true,
..Default::default()
},
{
let mut app = DemoApp::default();
move |ctx, frame| {
app.update(ctx, frame);
}
},
)
.unwrap();
}
// When compiling to web using trunk:
#[cfg(target_arch = "wasm32")]
fn main() {
use eframe::wasm_bindgen::JsCast as _;
// Redirect `log` message to `console.log` and friends:
eframe::WebLogger::init(log::LevelFilter::Debug).ok();
let web_options = eframe::WebOptions::default();
wasm_bindgen_futures::spawn_local(async {
let document = web_sys::window()
.expect("No window")
.document()
.expect("No document");
let canvas = document
.get_element_by_id("the_canvas_id")
.expect("Failed to find the_canvas_id")
.dyn_into::<web_sys::HtmlCanvasElement>()
.expect("the_canvas_id was not a HtmlCanvasElement");
let start_result = eframe::WebRunner::new()
.start(
canvas,
web_options,
Box::new(|_cc| Ok(Box::new(DemoApp::default()))),
)
.await;
// Remove the loading text and spinner:
if let Some(loading_text) = document.get_element_by_id("loading_text") {
match start_result {
Ok(_) => {
loading_text.remove();
}
Err(e) => {
loading_text.set_inner_html(
"<p> The app has crashed. See the developer console for details. </p>",
);
panic!("Failed to start eframe: {e:?}");
}
}
}
});
}