-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathdata-list-view.rs
245 lines (216 loc) · 6.8 KB
/
data-list-view.rs
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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! Data list example (indirect representation)
//!
//! This is a variant of `data-list` using the [`ListView`] widget to create a
//! dynamic view over a lazy, indirect data structure. Maximum data length is
//! thus only limited by the data types used (specifically the `i32` type used
//! to calculate the maximum scroll offset).
use kas::prelude::*;
use kas::view::{DataAccessor, Driver, ListView};
use kas::widgets::{column, *};
use std::collections::HashMap;
use std::ops::Range;
#[derive(Debug)]
struct SelectEntry(usize);
#[derive(Clone, Debug)]
enum Control {
None,
SetLen(usize),
DecrLen,
IncrLen,
Reverse,
Select(usize, String),
Update(usize, String),
}
#[derive(Debug)]
struct Data {
len: usize,
active: usize,
dir: Direction,
active_string: String,
strings: HashMap<usize, String>,
}
impl Data {
fn new(len: usize) -> Self {
Data {
len,
active: 0,
dir: Direction::Down,
active_string: String::from("Entry 1"),
strings: HashMap::new(),
}
}
fn get_string(&self, index: usize) -> String {
self.strings
.get(&index)
.cloned()
.unwrap_or_else(|| format!("Entry #{}", index + 1))
}
fn handle(&mut self, control: Control) {
let len = match control {
Control::None => return,
Control::SetLen(len) => len,
Control::DecrLen => self.len.saturating_sub(1),
Control::IncrLen => self.len.saturating_add(1),
Control::Reverse => {
self.dir = self.dir.reversed();
return;
}
Control::Select(index, text) => {
self.active = index;
self.active_string = text;
return;
}
Control::Update(index, text) => {
if index == self.active {
self.active_string = text.clone();
}
self.strings.insert(index, text);
return;
}
};
self.len = len;
if self.active >= len && len > 0 {
self.active = len - 1;
self.active_string = self.get_string(self.active);
}
}
}
type Item = (usize, String); // (active index, entry's text)
#[derive(Debug)]
struct ListEntryGuard(usize);
impl EditGuard for ListEntryGuard {
type Data = Item;
fn update(edit: &mut EditField<Self>, cx: &mut ConfigCx, data: &Item) {
if !edit.has_edit_focus() {
edit.set_string(cx, data.1.to_string());
}
}
fn activate(edit: &mut EditField<Self>, cx: &mut EventCx, _: &Item) -> IsUsed {
cx.push(SelectEntry(edit.guard.0));
Used
}
fn edit(edit: &mut EditField<Self>, cx: &mut EventCx, _: &Item) {
cx.push(Control::Update(edit.guard.0, edit.clone_string()));
}
}
impl_scope! {
// The list entry
#[widget{
layout = column! [
row! [self.label, self.radio],
self.edit,
];
}]
struct ListEntry {
core: widget_core!(),
#[widget(&())]
label: Label<String>,
#[widget]
radio: RadioButton<Item>,
#[widget]
edit: EditBox<ListEntryGuard>,
}
impl Events for Self {
type Data = Item;
fn handle_messages(&mut self, cx: &mut EventCx, data: &Item) {
if let Some(SelectEntry(n)) = cx.try_pop() {
if data.0 != n {
cx.push(Control::Select(n, self.edit.clone_string()));
}
}
}
}
}
#[derive(Default)]
struct MyAccessor {
start: usize,
len: usize,
items: Vec<Item>,
}
impl DataAccessor<usize> for MyAccessor {
type Data = Data;
type Key = usize;
type Item = Item;
fn len(&self, data: &Self::Data) -> usize {
data.len
}
fn prepare_range(&mut self, _: &mut ConfigCx, _: Id, data: &Self::Data, range: Range<usize>) {
let update_range;
if range.len() == self.len {
if range.start == self.start {
return;
} else if range.start > self.start {
update_range = (self.start + self.len)..range.end;
} else {
update_range = range.start..self.start;
}
} else {
self.len = range.len();
self.items.resize(self.len, Item::default());
update_range = range.clone();
}
self.start = range.start;
for index in update_range {
self.items[index % self.len] = (data.active, data.get_string(index));
}
}
fn key(&self, _: &Self::Data, index: usize) -> Option<Self::Key> {
Some(index)
}
fn item(&self, _: &Self::Data, key: &Self::Key) -> Option<&Item> {
Some(&self.items[key % self.len])
}
}
struct MyDriver;
impl Driver<usize, Item> for MyDriver {
type Widget = ListEntry;
fn make(&mut self, key: &usize) -> Self::Widget {
let n = *key;
ListEntry {
core: Default::default(),
label: Label::new(format!("Entry number {}", n + 1)),
radio: RadioButton::new_msg(
"display this entry",
move |_, data: &Item| data.0 == n,
move || SelectEntry(n),
),
edit: EditBox::new(ListEntryGuard(n)),
}
}
}
fn main() -> kas::runner::Result<()> {
env_logger::init();
let controls = row![
"Number of rows:",
EditBox::parser(|n| *n, Control::SetLen),
row![
// This button is just a click target; it doesn't do anything!
Button::label_msg("Set", Control::None),
Button::label_msg("−", Control::DecrLen),
Button::label_msg("+", Control::IncrLen),
Button::label_msg("↓↑", Control::Reverse),
]
.map_any(),
];
let data = Data::new(5);
let list = ListView::new(MyAccessor::default(), MyDriver).on_update(|cx, list, data: &Data| {
list.set_direction(cx, data.dir);
});
let tree = column![
"Demonstration of dynamic widget creation / deletion",
controls.map(|data: &Data| &data.len),
"Contents of selected entry:",
Text::new(|_, data: &Data| data.active_string.clone()),
Separator::new(),
ScrollBars::new(list).with_fixed_bars(false, true),
];
let ui = tree
.with_state(data)
.on_message(|_, data, control| data.handle(control));
let window = Window::new(ui, "Dynamic widget demo");
kas::runner::Default::new(())?.with(window).run()
}