勾选任务
上一章的任务行还只是静态文字。这一章引入响应式状态(#[model]),让点击行、切换勾选图标与更新顶部完成数在同一帧完成。
1. 最小演示:#[model] 与 ${...} 绑定
先看一个最纯粹的状态开关:结构体打上 #[model],需要被界面观察的字段打上 #[observe]。宏会自动生成同名读取方法(如 state.checked() 和 state.taps())。
只要在 ui! 的 ${...} 里调用这些读取方法,控件就会自动订阅字段变化;在 on Tap 里直接修改模型,画面即刻刷新:
319#[model]
320#[derive(Default)]
321pub struct MiniSwitch {
322 #[observe]
323 pub checked: bool,
324 #[observe]
325 pub taps: u32,
326}
327
328#[model]
329impl MiniSwitch {
330 pub fn flip(&mut self) {
331 self.checked = !self.checked;
332 self.taps = self.taps.saturating_add(1);
333 }
334}
335
336#[compose]
337fn mini_state_scene(state: model!(MiniSwitch)) {
338 ui! {
339 Column (
340 grow: 1.0,
341 padding: Padding::all(20),
342 justify: JustifyContent::SpaceBetween,
343 text_color: ColorToken::OnSurface
344 ) {
345 Text (
346 text: ${ format_args!("Status: {} ({} taps)", if state.checked() { "Done" } else { "Open" }, state.taps()) },
347 capacity: 36,
348 height: 26,
349 font_size: 16
350 )
351 Button (
352 text: ${ if state.checked() { "✓ Completed — tap to undo" } else { "Tap to mark complete" } },
353 height: 44,
354 border_radius: 10,
355 normal_color: ${ if state.checked() { ColorToken::Primary } else { ColorToken::SurfaceVariant } },
356 pressed_color: ColorToken::Outline,
357 text_color: ${ if state.checked() { ColorToken::OnPrimary } else { ColorToken::OnSurface } }
358 ) on Tap { state.flip(); }
359 }
360 };
361}
正在加载预览…
2. 带入任务清单:行勾选与顶部统计同步
现在把同样的机制放进任务清单里。在 model.rs 里定义 Task(带 #[observe] pub done: bool)与聚合根模型 Tasks(持有 items: model!(owned ModelList<Task>) 并提供派生查询 completed() / total());然后在 interface.rs 里把每一行包进 Button ... on Tap { task.toggle(); }:
CHAPTER 02 · MODEL & SUBSCRIBER UMLTasks ⇄ Task 模型聚合关系与 ${...} 响应式依赖拓扑图
点击某一行触发 `on Tap { task.toggle(); }`,翻转该行对应 `Task` 实例上的 `#[observe] pub done: bool` 字段。
pub fn toggle(&mut self) { self.done = !self.done; }Mutates only the clicked Task item⋯model.rs:7
7#[model(persistence)]
8#[derive(Default)]
+9pub struct Task {
+10 #[persist]
+11 pub title: String,
+12 #[observe]
+13 #[persist]
+14 pub done: bool,
+15}
+16
+17#[model]
+18impl Task {
+19 pub fn toggle(&mut self) {
+20 self.done = !self.done;
+21 }
+22}
⋯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 {
+74 #[observe]
+75 pub fn completed(&self) -> usize {
+76 self.items.iter().filter(|task| task.done()).count()
+77 }
+78
+79 #[observe]
+80 pub fn total(&self) -> usize {
+81 self.items.len()
+82 }
⋯model.rs:98
98}
⋯interface.rs:51
51#[compose]
52fn task_row(
53 tasks: model!(Tasks),
54 task: model!(Task),
55 draft: model!(TextDocument),
56 key: ModelItemId,
57 chapter: Chapter,
58) -> Entity {
59 let title = task.read(|task| task.title.clone());
60 ui! {
61 Column (visible: ${ tasks.filter().includes(task.done()) }, height: 49, shrink: 0.0) {
62 Row (height: 48, align: AlignItems::Center) {
+63 Button (
+64 grow: 1.0,
+65 min_width: 0,
+66 height: 44,
+67 clip_children: true,
+68 normal_color: ColorToken::Surface,
+69 pressed_color: ColorToken::SurfaceVariant,
+70 class: ${
+71 (
+72 chapter.has_presets().then_some("task"),
+73 (chapter.has_presets() && task.done()).then_some("task.complete"),
+74 )
+75 }
+76 ) {
+77 Row (grow: 1.0, min_width: 0, align: AlignItems::Center, column_gap: 12) {
+78 Column (
+79 width: 20,
+80 height: 20,
+81 shrink: 0.0,
+82 border_width: 1,
+83 border_radius: 6,
+84 align: AlignItems::Center,
+85 justify: JustifyContent::Center,
+86 bg_color: ${ if task.done() { ColorToken::Primary } else { ColorToken::Surface } },
+87 border_color: ${ if task.done() { ColorToken::Primary } else { ColorToken::OnSurfaceVariant } }
+88 ) {
+89 Icon (
+90 visible: ${ task.done() },
+91 path: ICON_CHECK,
+92 width: 14,
+93 height: 14,
+94 color: ColorToken::OnPrimary
+95 )
+96 }
+97 Text (
+98 text: title,
+99 grow: 1.0,
+100 min_width: 0,
+101 height: 22,
+102 paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
+103 )
+104 }
+105 } on Tap { task.toggle(); }
106 if chapter.has_list() {
107 Button (
108 "Remove",
109 width: 54,
110 height: 44,
111 font_size: 12,
112 normal_color: ColorToken::Surface,
113 pressed_color: ColorToken::SurfaceVariant,
114 text_color: ColorToken::OnSurfaceVariant
115 ) on Tap(edit_tasks::callback(Edit::Remove(key), tasks, draft))
116 }
117 }
118 View (height: 1, bg_color: ColorToken::Outline)
119 }
120 }
121}
⋯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 ) {
254 Column (
255 height: if chapter.has_motion() { 102 } else { 92 },
256 padding: Padding::all(14),
257 row_gap: 6,
258 shrink: 0.0,
259 bg_color: ColorToken::Secondary,
260 border_radius: 12
261 ) {
262 Text ("Task list", font_size: 30, height: 39, text_color: ColorToken::OnSecondary)
+263 Text (
+264 text: ${ format_args!("{} of {} complete", tasks.completed(), tasks.total()) },
+265 capacity: 32,
+266 font_size: 13,
+267 height: 19,
+268 text_color: ColorToken::OnSecondary
+269 )
270 if chapter.has_motion() {
271 View (height: 4, bg_color: ColorToken::OnSurfaceVariant, border_radius: 2) [
272 Progress(start),
273 ProgressTarget(start),
274 ]
275 }
276 }
⋯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 );
正在加载预览…
这一步做了什么
- 单一数据源,派生计数:顶部的
format_args!("{} of {} complete", tasks.completed(), tasks.total())直接遍历列表统计已完成的任务数。我们不需要维护第二个计数器变量,所以勾选状态与顶部数字永远不会错位。 - 必须调 getter 方法:在
${...}里一定要写task.done()而不是裸字段task.done——只有经过生成的 getter,响应式作用域才能记录下“这个控件依赖这个字段”。
在本机运行
sh
cargo run -p mirui-first-app --features desktop --example desktop -- 2