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
// 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
//! A row or column with wrapping
use crate::List;
use kas::Collection;
use kas::layout::{FlowSetter, FlowSolver, FlowStorage, RulesSetter, RulesSolver};
use kas::prelude::*;
use std::ops::{Index, IndexMut};
#[impl_self]
mod Flow {
/// Rows or columns of content with line-splitting
///
/// This widget is a variant of [`List`], arranging a linear [`Collection`]
/// of children into multiple rows or columns with automatic splitting.
/// Unlike [`Grid`](crate::Grid), items are not aligned across lines.
///
/// When the collection uses [`Vec`], various methods to insert/remove
/// elements are available.
///
/// ## Layout details
///
/// Currently only horizontal lines (rows) which wrap down to the next line
/// are supported.
///
/// Width requirements depend on the desired numbers of columns; see
/// [`Self::set_num_columns`].
///
/// Items within each line are stretched (if any has non-zero [`Stretch`]
/// priority) in accordance with [`SizeRules::solve_widths`]. It is not
/// currently possible to adjust this (except by tweaking the stretchiness
/// of items).
///
/// ## Performance
///
/// Sizing, drawing and event handling are all `O(n)` where `n` is the number of children.
///
/// ## Example
///
/// ```
/// use kas::collection;
/// # use kas_widgets::{CheckBox, Flow};
///
/// let list = Flow::right(collection![
/// "A checkbox",
/// CheckBox::new(|_, state: &bool| *state),
/// ]);
/// ```
#[autoimpl(Default where C: Default, D: Default)]
#[derive_widget]
pub struct Flow<C: Collection, D: Directional> {
#[widget]
list: List<C, D>,
layout: FlowStorage,
secondary_is_reversed: bool,
min_cols: i32,
ideal_cols: i32,
}
impl Layout for Self {
fn size_rules(&mut self, cx: &mut SizeCx, axis: AxisInfo) -> SizeRules {
let mut solver = FlowSolver::new(
axis,
self.list.direction.as_direction(),
self.secondary_is_reversed,
self.list.widgets.len(),
&mut self.layout,
);
solver.set_num_columns(self.min_cols, self.ideal_cols);
for n in 0..self.list.widgets.len() {
if let Some(child) = self.list.widgets.get_mut_tile(n) {
solver.for_child(&mut self.layout, n, |axis| child.size_rules(cx, axis));
}
}
solver.finish(&mut self.layout)
}
fn set_rect(&mut self, cx: &mut SizeCx, rect: Rect, hints: AlignHints) {
self.list.core.set_rect(rect);
let mut setter = FlowSetter::new(
rect,
self.list.direction.as_direction(),
self.secondary_is_reversed,
self.list.widgets.len(),
&mut self.layout,
);
for n in 0..self.list.widgets.len() {
if let Some(child) = self.list.widgets.get_mut_tile(n) {
child.set_rect(cx, setter.child_rect(&mut self.layout, n), hints);
}
}
}
fn draw(&self, mut draw: DrawCx) {
// TODO(opt): use position solver as with List widget
for child in self.list.widgets.iter_tile(..) {
child.draw(draw.re());
}
}
}
impl Tile for Self {
fn try_probe(&self, coord: Coord) -> Option<Id> {
if !self.rect().contains(coord) {
return None;
}
for child in self.list.widgets.iter_tile(..) {
if let Some(id) = child.try_probe(coord) {
return Some(id);
}
}
Some(self.id())
}
}
impl Self
where
D: Default,
{
/// Construct a new instance with default-constructed direction
///
/// This constructor is available where the direction is determined by the
/// type: for `D: Directional + Default`. The wrap direction is down or right.
///
/// # Examples
///
/// Where widgets have the same type and the length is fixed, an array
/// may be used:
/// ```
/// use kas_widgets::{Label, Row};
/// let _ = Row::new([Label::new("left"), Label::new("right")]);
/// ```
///
/// To support run-time insertion/deletion, use [`Vec`]:
/// ```
/// use kas_widgets::{AdaptWidget, Button, Row};
///
/// #[derive(Clone, Debug)]
/// enum Msg {
/// Add,
/// Remove,
/// }
///
/// let _ = Row::new(vec![Button::label_msg("Add", Msg::Add)])
/// .on_messages(|cx, row, data| {
/// if let Some(msg) = cx.try_pop() {
/// match msg {
/// Msg::Add => {
/// let button = if row.len() % 2 == 0 {
/// Button::label_msg("Add", Msg::Add)
/// } else {
/// Button::label_msg("Remove", Msg::Remove)
/// };
/// row.push(cx, data, button);
/// }
/// Msg::Remove => {
/// let _ = row.pop(cx);
/// }
/// }
/// }
/// });
/// ```
#[inline]
pub fn new(widgets: C) -> Self {
Self::new_dir(widgets, D::default())
}
}
impl<C: Collection> Flow<C, kas::dir::Left> {
/// Construct a new instance with fixed direction
///
/// Lines flow from right-to-left, wrapping down.
#[inline]
pub fn left(widgets: C) -> Self {
Self::new(widgets)
}
}
impl<C: Collection> Flow<C, kas::dir::Right> {
/// Construct a new instance with fixed direction
///
/// Lines flow from left-to-right, wrapping down.
#[inline]
pub fn right(widgets: C) -> Self {
Self::new(widgets)
}
}
impl Self {
/// Construct a new instance with explicit direction
#[inline]
pub fn new_dir(widgets: C, direction: D) -> Self {
assert!(
direction.is_horizontal(),
"column flow is not (yet) supported"
);
Flow {
list: List::new_dir(widgets, direction),
layout: Default::default(),
secondary_is_reversed: false,
min_cols: 1,
ideal_cols: 3,
}
}
/// Set the (minimum, ideal) numbers of columns
///
/// This affects the final [`SizeRules`] for the horizontal axis.
///
/// By default, the values `1, 3` are used.
#[inline]
pub fn set_num_columns(&mut self, min: i32, ideal: i32) {
self.min_cols = min;
self.ideal_cols = ideal;
}
/// Set the (minimum, ideal) numbers of columns (inline)
///
/// This affects the final [`SizeRules`] for the horizontal axis.
///
/// By default, the values `1, 3` are used.
#[inline]
pub fn with_num_columns(mut self, min: i32, ideal: i32) -> Self {
self.set_num_columns(min, ideal);
self
}
/// True if there are no child widgets
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
/// Returns the number of child widgets
pub fn len(&self) -> usize {
self.list.len()
}
}
impl<W: Widget, D: Directional> Flow<Vec<W>, D> {
/// Returns a reference to the child, if any
pub fn get(&self, index: usize) -> Option<&W> {
self.list.get(index)
}
/// Returns a mutable reference to the child, if any
pub fn get_mut(&mut self, index: usize) -> Option<&mut W> {
self.list.get_mut(index)
}
/// Remove all child widgets
pub fn clear(&mut self) {
self.list.clear();
}
/// Append a child widget
///
/// The new child is configured immediately. Triggers a resize.
///
/// Returns the new element's index.
pub fn push(&mut self, cx: &mut ConfigCx, data: &W::Data, widget: W) -> usize {
self.list.push(cx, data, widget)
}
/// Remove the last child widget (if any) and return
///
/// Triggers a resize.
pub fn pop(&mut self, cx: &mut ConfigCx) -> Option<W> {
self.list.pop(cx)
}
/// Inserts a child widget position `index`
///
/// Panics if `index > len`.
///
/// The new child is configured immediately. Triggers a resize.
pub fn insert(&mut self, cx: &mut ConfigCx, data: &W::Data, index: usize, widget: W) {
self.list.insert(cx, data, index, widget);
}
/// Removes the child widget at position `index`
///
/// Panics if `index` is out of bounds.
///
/// Triggers a resize.
pub fn remove(&mut self, cx: &mut ConfigCx, index: usize) -> W {
self.list.remove(cx, index)
}
/// Removes all children at positions ≥ `len`
///
/// Does nothing if `self.len() < len`.
///
/// Triggers a resize.
pub fn truncate(&mut self, cx: &mut ConfigCx, len: usize) {
self.list.truncate(cx, len);
}
/// Replace the child at `index`
///
/// Panics if `index` is out of bounds.
///
/// The new child is configured immediately. Triggers a resize.
pub fn replace(&mut self, cx: &mut ConfigCx, data: &W::Data, index: usize, widget: W) -> W {
self.list.replace(cx, data, index, widget)
}
/// Append child widgets from an iterator
///
/// New children are configured immediately. Triggers a resize.
pub fn extend<T>(&mut self, cx: &mut ConfigCx, data: &W::Data, iter: T)
where
T: IntoIterator<Item = W>,
{
self.list.extend(cx, data, iter);
}
/// Resize, using the given closure to construct new widgets
///
/// New children are configured immediately. Triggers a resize.
pub fn resize_with<F>(&mut self, cx: &mut ConfigCx, data: &W::Data, len: usize, f: F)
where
F: Fn(usize) -> W,
{
self.list.resize_with(cx, data, len, f);
}
/// Iterate over childern
pub fn iter(&self) -> impl Iterator<Item = &W> {
self.list.iter()
}
/// Mutably iterate over childern
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut W> {
self.list.iter_mut()
}
}
impl<W: Widget, D: Directional> Index<usize> for Flow<Vec<W>, D> {
type Output = W;
fn index(&self, index: usize) -> &Self::Output {
self.list.index(index)
}
}
impl<W: Widget, D: Directional> IndexMut<usize> for Flow<Vec<W>, D> {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.list.index_mut(index)
}
}
}