Skip to content
Development

Add, remove, and filter ​

Dynamic lists have two classic pitfalls: unbounded heap growth on embedded targets, and index-based keys that delete or scramble the wrong row when items are filtered.

1. Minimal demo: ModelList, TextInput, and walk ​

ModelList::bounded(N) provides a fixed-capacity reactive collection and assigns each item a stable ModelItemId.

In this minimal demo, TextInput binds a TextDocument draft, tapping + Add (or pressing Return) pushes a new item, and walk ${ notes.items().entries() } with entry by entry.0 keys each row by its ModelItemId:

CONCEPT
recipes.rs119 lines
363#[model]
364#[derive(Default)]
365pub struct NoteItem {
366 pub label: String,
367}
368
369#[model]
370impl NoteItem {}
371
372#[model]
373pub struct MiniNotes {
374 pub items: model!(owned ModelList<NoteItem>),
375 seq: u32,
376}
377
378impl Default for MiniNotes {
379 fn default() -> Self {
380 let mut items = ModelList::bounded(6);
381 let _ = items.try_push(NoteItem {
382 label: "Wire SPI display".into(),
383 });
384 let _ = items.try_push(NoteItem {
385 label: "Mount root view".into(),
386 });
387 Self {
388 items: items.into(),
389 seq: 3,
390 }
391 }
392}
393
394#[model]
395impl MiniNotes {
396 pub fn add(&mut self, text: Option<String>) {
397 let label = text.unwrap_or_else(|| format!("Item #{}", self.seq));
398 if self.items.try_push(NoteItem { label }).is_ok() {
399 self.seq = self.seq.saturating_add(1);
400 }
401 }
402
403 pub fn remove(&mut self, id: ModelItemId) {
404 let _ = self.items.remove(id);
405 }
406}
407
408#[event]
409fn add_note(notes: model!(MiniNotes), draft: model!(TextDocument)) {
410 let text = draft.read(|s| {
411 let t = s.trim();
412 (!t.is_empty()).then(|| t.chars().take(28).collect::<String>())
413 });
414 notes.add(text);
415 let _ = draft.set_text("");
416}
417
418#[event]
419fn remove_note(id: ModelItemId, notes: model!(MiniNotes)) {
420 notes.remove(id);
421}
422
423#[compose]
424fn note_row(notes: model!(MiniNotes), id: ModelItemId, item: model!(NoteItem)) -> Entity {
425 let title = item.read(|n| n.label.clone());
426 ui! {
427 Row (
428 height: 34,
429 padding: Padding::all(6),
430 align: AlignItems::Center,
431 justify: JustifyContent::SpaceBetween,
432 bg_color: ColorToken::SurfaceVariant,
433 border_radius: 7
434 ) {
435 Text (text: title, grow: 1.0, height: 20, font_size: 13)
436 Button (
437 "×",
438 width: 28,
439 height: 26,
440 border_radius: 6,
441 normal_color: ColorToken::Surface,
442 pressed_color: ColorToken::Outline,
443 text_color: ColorToken::OnSurfaceVariant
444 ) on Tap(remove_note::callback(id, notes))
445 }
446 }
447}
448
449#[compose]
450fn mini_list_scene(notes: model!(MiniNotes), draft: model!(TextDocument)) {
451 ui! {
452 Column (grow: 1.0, padding: Padding::all(16), row_gap: 8, text_color: ColorToken::OnSurface) {
453 Row (height: 36, column_gap: 8) {
454 TextInput (
455 grow: 1.0,
456 height: 36,
457 padding: Padding::all(8),
458 bg_color: ColorToken::SurfaceVariant,
459 border_radius: 8
460 ) [
461 TextEditing::new(draft.clone()),
462 Placeholder("Type an item..."),
463 ] on TextEditing::Submitted(add_note::callback(notes, draft))
464 Button (
465 "+ Add",
466 width: 64,
467 height: 36,
468 border_radius: 8,
469 normal_color: ColorToken::Primary,
470 pressed_color: ColorToken::Secondary,
471 text_color: ColorToken::OnPrimary
472 ) on Tap(add_note::callback(notes, draft))
473 }
474 Column (grow: 1.0, row_gap: 6, clip_children: true) {
475 walk ${ notes.items().entries() } with entry by entry.0 {
476 note_row (notes, entry.0, entry.1)
477 }
478 }
479 }
480 };
481}
Loading preview…

Type a short note and press Return (or tap + Add), then remove any row in the middle with ×.


2. In the task list: adding, removing, and filtering tasks ​

Now we wire TextInput, Remove buttons, and the All / Open / Done filter bar into the task list.

Inspect the focused changes across model.rs and interface.rs (marked with +): filtering never removes items from ModelList—it simply binds each row's visible property to tasks.filter().includes(task.done()), while the header tally continues to report the full list:

CHAPTER 03 · KEYED LIST & DRAFT UMLTextDocument draft, Edit event & keyed ModelItemId reconciliation

While typing in `TextInput`, keystrokes mutate the isolated `draft: TextDocument` model—the task list itself is not touched or re-laid out on every keystroke.

TextInput(...) [TextEditing::new(draft.clone()), Placeholder("New task")]Decouples IME/caret churn from business list
03 / 07
model.rs · interface.rs · lib.rs Added in this step146 lines
⋯model.rs:24
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Filter {
26 All,
27 Open,
28 Done,
29}
30
31impl Filter {
32 pub fn includes(self, done: bool) -> bool {
33 match self {
34 Self::All => true,
35 Self::Open => !done,
36 Self::Done => done,
37 }
38 }
39}
⋯model.rs:41
41#[model(persistence(key = "first_app_tasks"))]
42pub struct Tasks {
43 #[persist]
44 pub items: model!(owned ModelList<Task>),
45 #[observe]
46 pub(crate) filter: Filter,
47 #[persist]
48 sequence: u32,
49}
⋯model.rs:72
72#[model]
73impl Tasks {
⋯model.rs:84
84 pub fn set_filter(&mut self, filter: Filter) {
85 self.filter = filter;
86 }
87
88 pub fn add(&mut self, title: Option<String>) {
89 let title = title.unwrap_or_else(|| format!("Task {}", self.sequence));
90 if self.items.try_push(Task { title, done: false }).is_ok() {
91 self.sequence = self.sequence.saturating_add(1);
92 }
93 }
94
95 pub fn remove(&mut self, key: ModelItemId) {
96 let _ = self.items.remove(key);
97 }
98}
⋯interface.rs:19
19#[event]
20fn edit_tasks(edit: Edit, tasks: model!(Tasks), draft: model!(TextDocument)) {
21 match edit {
22 Edit::Add => {
23 if tasks.total() == TASK_LIMIT {
24 return;
25 }
26 let title = draft.read(|text| {
27 let value = text.trim();
28 (!value.is_empty()).then(|| value.chars().take(40).collect::<String>())
29 });
30 tasks.add(title);
31 let _ = draft.set_text("");
32 }
33 Edit::Remove(key) => tasks.remove(key),
34 }
35}
⋯interface.rs:209
209#[compose]
210fn add_task(tasks: model!(Tasks), draft: model!(TextDocument)) -> Entity {
211 ui! {
212 Row (height: 42, shrink: 0.0, column_gap: 8) {
213 TextInput (
214 grow: 1.0,
215 min_width: 0,
216 height: 42,
217 padding: Padding::all(10),
218 bg_color: ColorToken::SurfaceVariant,
219 border_radius: 9
220 ) [
221 TextEditing::new(draft.clone()),
222 Placeholder("New task"),
223 ] on TextEditing::Submitted(edit_tasks::callback(Edit::Add, tasks, draft))
224 Button (
225 text: ${ if tasks.total() == TASK_LIMIT { "List full" } else { "+ Add" } },
226 width: 70,
227 height: 42,
228 border_radius: 9,
229 normal_color: ColorToken::OnSurface,
230 pressed_color: ColorToken::Primary,
231 text_color: ColorToken::Surface
232 ) on Tap(edit_tasks::callback(Edit::Add, tasks, draft))
233 }
234 }
235}
⋯interface.rs:237
237#[compose]
238pub(crate) fn task_list(
239 tasks: model!(Tasks),
240 draft: model!(TextDocument),
241 chapter: Chapter,
242 reduced: bool,
243) {
244 let start = progress_ratio(tasks.completed(), tasks.total());
245 ui! {
246 Column (
247 grow: 1.0,
248 min_height: 0,
249 padding: Padding::all(18),
250 row_gap: 9,
251 text_color: ColorToken::OnSurface,
252 font_size: 14
253 ) {
⋯interface.rs:280
280 Column (grow: 1.0, min_height: 0, clip_children: true) [
281 ScrollOffset::default(),
282 ScrollConfig::default(),
283 ] {
284 walk ${ tasks.items().entries() } with row by row.0 {
285 task_row (
286 tasks,
287 row.1,
288 draft,
289 row.0,
290 chapter
291 )
292 }
293 if chapter.has_list() {
294 Text (
295 visible: ${
296 match tasks.filter() {
297 Filter::All => tasks.total() == 0,
298 Filter::Open => tasks.completed() == tasks.total(),
299 Filter::Done => tasks.completed() == 0,
300 }
301 },
302 text: ${
303 match tasks.filter() {
304 Filter::All => "Add a task to get started.",
305 Filter::Open => "No open tasks.",
306 Filter::Done => "No completed tasks.",
307 }
308 },
309 height: 44,
310 text_color: ColorToken::OnSurfaceVariant
311 )
312 }
313 }
⋯interface.rs:317
317 }
318 };
319}
⋯lib.rs:85
85 let tasks = app.add_model(Tasks::default()).finish();
⋯lib.rs:93
93 let draft = app.add_model(TextDocument::new()).finish();
94 app.compose(
95 root,
96 interface::task_list(tasks.clone(), draft, chapter, reduced),
97 );
Loading preview…

Type a title in the bottom field (or tap + Add), flip between Open and Done, then remove a task—every remaining row keeps its identity and state.

What changed in this step ​

  1. Addressing by ModelItemId instead of index: When completed rows are hidden under Open, the first visible row on screen may be the second item in storage. Passing ModelItemId to Edit::Remove(key) ensures deletion always hits the exact item you tapped.
  2. Decoupled text draft: Cursor movement and text selection live inside TextDocument. Tasks is only mutated when edit_tasks fires on Return or + Add.

Run on your machine ​

sh
cargo run -p mirui-first-app --features desktop --example desktop -- 3