plushie 0.7.1

Desktop GUI framework for Rust
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Integration tests exercising the full MVU cycle through
//! TestSession. Each test defines a small app and verifies
//! behavior through the public API.

use plushie::prelude::*;
use plushie::test::TestSession;
use serde_json::json;

// ---------------------------------------------------------------------------
// Counter app
// ---------------------------------------------------------------------------

struct Counter {
    count: i32,
}

impl App for Counter {
    type Model = Self;

    fn init() -> (Self, Command) {
        (Counter { count: 0 }, Command::none())
    }

    fn update(model: &mut Self, event: Event) -> Command {
        match event.widget_match() {
            Some(Click("inc")) => model.count += 1,
            Some(Click("dec")) => model.count -= 1,
            Some(Click("reset")) => model.count = 0,
            _ => {}
        }
        Command::none()
    }

    fn view(model: &Self, _widgets: &mut WidgetRegistrar) -> ViewList {
        window("main")
            .title("Counter")
            .child(
                column()
                    .spacing(8.0)
                    .padding(16)
                    .child(text(&format!("{}", model.count)).id("display"))
                    .child(row().spacing(4.0).children([
                        button("inc", "+"),
                        button("dec", "-"),
                        button("reset", "Reset"),
                    ])),
            )
            .into()
    }
}

#[test]
fn counter_starts_at_zero() {
    let session = TestSession::<Counter>::start();
    assert_eq!(session.model().count, 0);
}

#[test]
fn counter_increments_on_click() {
    let mut session = TestSession::<Counter>::start();
    session.click("inc");
    assert_eq!(session.model().count, 1);
}

#[test]
fn counter_decrements_on_click() {
    let mut session = TestSession::<Counter>::start();
    session.click("dec");
    assert_eq!(session.model().count, -1);
}

#[test]
fn counter_multiple_clicks() {
    let mut session = TestSession::<Counter>::start();
    session.click("inc");
    session.click("inc");
    session.click("inc");
    session.click("dec");
    assert_eq!(session.model().count, 2);
}

#[test]
fn counter_reset() {
    let mut session = TestSession::<Counter>::start();
    session.click("inc");
    session.click("inc");
    session.click("reset");
    assert_eq!(session.model().count, 0);
}

#[test]
fn counter_view_reflects_model() {
    let mut session = TestSession::<Counter>::start();
    session.assert_text("display", "0");
    session.click("inc");
    session.assert_text("display", "1");
    session.click("inc");
    session.assert_text("display", "2");
}

#[test]
fn counter_buttons_exist() {
    let session = TestSession::<Counter>::start();
    session.assert_exists("inc");
    session.assert_exists("dec");
    session.assert_exists("reset");
}

// ---------------------------------------------------------------------------
// Form app (text input + toggle + slider)
// ---------------------------------------------------------------------------

struct Form {
    name: String,
    agreed: bool,
    volume: f64,
}

impl App for Form {
    type Model = Self;

    fn init() -> (Self, Command) {
        (
            Form {
                name: String::new(),
                agreed: false,
                volume: 50.0,
            },
            Command::none(),
        )
    }

    fn update(model: &mut Self, event: Event) -> Command {
        match event.widget_match() {
            Some(Input("name", text)) => model.name = text.to_string(),
            Some(Toggle("agree", on)) => model.agreed = on,
            Some(Slide("volume", vol)) => model.volume = vol,
            Some(Submit("name", text)) => {
                model.name = text.to_string();
            }
            _ => {}
        }
        Command::none()
    }

    fn view(model: &Self, _widgets: &mut WidgetRegistrar) -> ViewList {
        window("main")
            .child(
                column()
                    .spacing(8.0)
                    .child(text_input("name", &model.name).placeholder("Your name"))
                    .child(checkbox("agree", model.agreed).label("I agree"))
                    .child(slider("volume", (0.0, 100.0), model.volume as f32))
                    .child(text(&format!("Name: {}", model.name)).id("name_display"))
                    .child(text(&format!("Agreed: {}", model.agreed)).id("agreed_display")),
            )
            .into()
    }
}

#[test]
fn form_text_input() {
    let mut session = TestSession::<Form>::start();
    session.type_text("name", "Alice");
    assert_eq!(session.model().name, "Alice");
    session.assert_text("name_display", "Name: Alice");
}

#[test]
fn form_toggle() {
    let mut session = TestSession::<Form>::start();
    assert!(!session.model().agreed);
    session.set_toggle("agree", true);
    assert!(session.model().agreed);
    session.assert_text("agreed_display", "Agreed: true");
}

#[test]
fn form_toggle_auto_flips_current_value() {
    let mut session = TestSession::<Form>::start();
    // Initial: agreed=false; auto-flip should turn it on.
    session.toggle("agree");
    assert!(session.model().agreed);
    // And then flip back off.
    session.toggle("agree");
    assert!(!session.model().agreed);
}

#[test]
fn form_submit_reads_current_value_when_no_arg() {
    let mut session = TestSession::<Form>::start();
    session.type_text("name", "Alice");
    session.submit("name");
    assert_eq!(session.model().name, "Alice");
}

#[test]
fn form_slider() {
    let mut session = TestSession::<Form>::start();
    session.slide("volume", 75.0);
    assert!((session.model().volume - 75.0).abs() < f64::EPSILON);
}

#[test]
fn form_submit() {
    let mut session = TestSession::<Form>::start();
    session.submit_with("name", "Bob");
    assert_eq!(session.model().name, "Bob");
}

// ---------------------------------------------------------------------------
// Todo app (dynamic list with scoped events)
// ---------------------------------------------------------------------------

struct TodoItem {
    id: String,
    text: String,
    done: bool,
}

struct TodoApp {
    items: Vec<TodoItem>,
    next_id: usize,
    input: String,
}

impl App for TodoApp {
    type Model = Self;

    fn init() -> (Self, Command) {
        (
            TodoApp {
                items: vec![
                    TodoItem {
                        id: "1".into(),
                        text: "Buy milk".into(),
                        done: false,
                    },
                    TodoItem {
                        id: "2".into(),
                        text: "Write tests".into(),
                        done: true,
                    },
                ],
                next_id: 3,
                input: String::new(),
            },
            Command::none(),
        )
    }

    fn update(model: &mut Self, event: Event) -> Command {
        match event.widget_match() {
            Some(Input("new_todo", text)) => {
                model.input = text.to_string();
            }
            Some(Submit("new_todo", text)) => {
                let id = model.next_id.to_string();
                model.next_id += 1;
                model.items.push(TodoItem {
                    id,
                    text: text.to_string(),
                    done: false,
                });
                model.input.clear();
            }
            Some(Toggle("done", _)) => {
                if let Some(item_id) = event.scope().and_then(|s| s.first())
                    && let Some(item) = model.items.iter_mut().find(|i| i.id == *item_id)
                {
                    item.done = !item.done;
                }
            }
            Some(Click("delete")) => {
                if let Some(item_id) = event.scope().and_then(|s| s.first()) {
                    model.items.retain(|i| i.id != *item_id);
                }
            }
            _ => {}
        }
        Command::none()
    }

    fn view(model: &Self, _widgets: &mut WidgetRegistrar) -> ViewList {
        window("main")
            .title("Todos")
            .child(
                column()
                    .spacing(8.0)
                    .padding(16)
                    .child(text_input("new_todo", &model.input).placeholder("Add todo..."))
                    .child(
                        column()
                            .id("list")
                            .spacing(4.0)
                            .children(model.items.iter().map(|item| {
                                row()
                                    .id(&item.id)
                                    .spacing(8.0)
                                    .child(checkbox("done", item.done).label(&item.text))
                                    .child(button("delete", "X"))
                            })),
                    ),
            )
            .into()
    }
}

#[test]
fn todo_starts_with_items() {
    let session = TestSession::<TodoApp>::start();
    assert_eq!(session.model().items.len(), 2);
}

#[test]
fn todo_add_item_via_submit() {
    let mut session = TestSession::<TodoApp>::start();
    session.submit_with("new_todo", "Learn Rust");
    assert_eq!(session.model().items.len(), 3);
    assert_eq!(session.model().items[2].text, "Learn Rust");
}

#[test]
fn todo_text_input_updates_model() {
    let mut session = TestSession::<TodoApp>::start();
    session.type_text("new_todo", "Draft");
    assert_eq!(session.model().input, "Draft");
}

// ---------------------------------------------------------------------------
// Command inspection
// ---------------------------------------------------------------------------

struct CommandApp {
    last_action: String,
}

impl App for CommandApp {
    type Model = Self;

    fn init() -> (Self, Command) {
        (
            CommandApp {
                last_action: String::new(),
            },
            Command::none(),
        )
    }

    fn update(model: &mut Self, event: Event) -> Command {
        match event.widget_match() {
            Some(Click("focus_email")) => {
                model.last_action = "focus".into();
                Command::focus("email")
            }
            Some(Click("quit")) => {
                model.last_action = "quit".into();
                Command::exit()
            }
            _ => Command::none(),
        }
    }

    fn view(_model: &Self, _widgets: &mut WidgetRegistrar) -> ViewList {
        window("main")
            .child(
                column()
                    .child(button("focus_email", "Focus Email"))
                    .child(button("quit", "Quit")),
            )
            .into()
    }
}

#[test]
fn command_app_updates_model_on_interaction() {
    let mut session = TestSession::<CommandApp>::start();
    session.click("focus_email");
    assert_eq!(session.model().last_action, "focus");
}

// ---------------------------------------------------------------------------
// Mixed event types via full Event match
// ---------------------------------------------------------------------------

struct MixedEventApp {
    clicks: usize,
    inputs: Vec<String>,
    selections: Vec<String>,
}

impl App for MixedEventApp {
    type Model = Self;

    fn init() -> (Self, Command) {
        (
            MixedEventApp {
                clicks: 0,
                inputs: vec![],
                selections: vec![],
            },
            Command::none(),
        )
    }

    fn update(model: &mut Self, event: Event) -> Command {
        if let Event::Widget(w) = &event {
            match (&w.event_type, w.scoped_id.id.as_str()) {
                (EventType::Click, _) => model.clicks += 1,
                (EventType::Input, _) => {
                    if let Some(text) = w.value_string() {
                        model.inputs.push(text);
                    }
                }
                (EventType::Select, _) => {
                    if let Some(val) = w.value_string() {
                        model.selections.push(val);
                    }
                }
                _ => {}
            }
        }
        Command::none()
    }

    fn view(_model: &Self, _widgets: &mut WidgetRegistrar) -> ViewList {
        window("main")
            .child(
                column()
                    .child(button("btn", "Click"))
                    .child(text_input("inp", ""))
                    .child(pick_list("sel", &["A", "B", "C"], None)),
            )
            .into()
    }
}

#[test]
fn mixed_events_via_full_match() {
    let mut session = TestSession::<MixedEventApp>::start();
    session.click("btn");
    session.click("btn");
    session.type_text("inp", "hello");
    session.select("sel", "B");

    assert_eq!(session.model().clicks, 2);
    assert_eq!(session.model().inputs, vec!["hello"]);
    assert_eq!(session.model().selections, vec!["B"]);
}

// ---------------------------------------------------------------------------
// View tree assertions
// ---------------------------------------------------------------------------

#[test]
fn assert_exists_finds_widget() {
    let session = TestSession::<Counter>::start();
    session.assert_exists("inc");
}

#[test]
#[should_panic(expected = "expected widget nonexistent to exist")]
fn assert_exists_panics_for_missing_widget() {
    let session = TestSession::<Counter>::start();
    session.assert_exists("nonexistent");
}

#[test]
fn assert_not_exists_for_missing_widget() {
    let session = TestSession::<Counter>::start();
    session.assert_not_exists("nonexistent");
}

#[test]
#[should_panic(expected = "expected widget inc to NOT exist")]
fn assert_not_exists_panics_for_existing_widget() {
    let session = TestSession::<Counter>::start();
    session.assert_not_exists("inc");
}

#[test]
fn prop_reads_widget_property() {
    let session = TestSession::<Form>::start();
    let placeholder = session.prop_str("name", "placeholder");
    assert_eq!(placeholder.as_deref(), Some("Your name"));
}

// ---------------------------------------------------------------------------
// Streaming command
// ---------------------------------------------------------------------------

#[derive(Default)]
struct Importer {
    chunks: Vec<String>,
    done: bool,
}

impl App for Importer {
    type Model = Self;

    fn init() -> (Self, Command) {
        (
            Importer::default(),
            Command::stream("import", |emitter| async move {
                emitter.emit(json!("alpha"));
                emitter.emit(json!("beta"));
                emitter.emit(json!("gamma"));
                Ok(json!({"count": 3}))
            }),
        )
    }

    fn update(model: &mut Self, event: Event) -> Command {
        match event {
            Event::Stream(s) if s.tag == "import" => {
                if let Some(chunk) = s.value.as_str() {
                    model.chunks.push(chunk.to_string());
                }
            }
            Event::Async(a) if a.tag == "import" => {
                model.done = a.result.is_ok();
            }
            _ => {}
        }
        Command::none()
    }

    fn view(_model: &Self, _widgets: &mut WidgetRegistrar) -> ViewList {
        window("main").child(text("importer")).into()
    }
}

#[test]
fn stream_delivers_intermediate_emits_and_final_result() {
    let session = TestSession::<Importer>::start();
    assert_eq!(
        session.model().chunks,
        vec!["alpha".to_string(), "beta".to_string(), "gamma".to_string()]
    );
    assert!(session.model().done);
}

// ---------------------------------------------------------------------------
// Dispatch depth guard
// ---------------------------------------------------------------------------
//
// An update that keeps returning `Command::dispatch(event)` would loop
// forever without a guard. The runtime caps the synchronous chain so
// the test session emits a `DispatchLoopExceeded` diagnostic and drops
// the offending command rather than overflowing the call stack.

struct LoopApp {
    ticks: u32,
}

impl App for LoopApp {
    type Model = Self;

    fn init() -> (Self, Command) {
        (LoopApp { ticks: 0 }, Command::none())
    }

    fn update(model: &mut Self, event: Event) -> Command {
        if let Event::Timer(t) = &event
            && t.tag == "tick"
        {
            model.ticks += 1;
            // Re-dispatch unconditionally; the runtime guard is what
            // stops the chain.
            return Command::dispatch(Event::Timer(plushie::event::TimerEvent {
                tag: "tick".into(),
                timestamp: 0,
            }));
        }
        Command::none()
    }

    fn view(_model: &Self, _widgets: &mut WidgetRegistrar) -> ViewList {
        window("main").child(text("loop")).into()
    }
}

// ---------------------------------------------------------------------------
// Full MVU cycle: init -> command -> async event -> update -> subscribe ->
// timer event -> view reflects state. Pins the load-bearing happy path.
// ---------------------------------------------------------------------------

#[derive(Default)]
struct LifecycleApp {
    /// Set when the async fetch task fired by `init` resolves.
    fetched: Option<String>,
    /// Set when the `tick` subscription delivers a timer event.
    ticks: u32,
    /// Toggled to enable the timer subscription only after the
    /// async fetch completes; pins that subscriptions track model
    /// changes through the same update cycle that consumes commands.
    ticking: bool,
}

impl App for LifecycleApp {
    type Model = Self;

    fn init() -> (Self, Command) {
        // init returns a Command::task, mirroring real apps that
        // kick off a fetch on startup. The result lands as
        // Event::Async(..).
        (
            Self::default(),
            Command::task("startup_fetch", || async { Ok(json!({"greeting": "hi"})) }),
        )
    }

    fn update(model: &mut Self, event: Event) -> Command {
        if let Some(a) = event.as_async()
            && a.tag == "startup_fetch"
            && let Ok(value) = &a.result
            && let Some(g) = value.get("greeting").and_then(|v| v.as_str())
        {
            model.fetched = Some(g.to_string());
            // Flip the timer subscription on now that the fetch has
            // landed; the next subscription diff picks it up.
            model.ticking = true;
        }
        if let Event::Timer(t) = &event
            && t.tag == "tick"
        {
            model.ticks += 1;
        }
        Command::none()
    }

    fn subscribe(model: &Self) -> Vec<Subscription> {
        if model.ticking {
            vec![Subscription::every(
                std::time::Duration::from_millis(16),
                "tick",
            )]
        } else {
            Vec::new()
        }
    }

    fn view(model: &Self, _widgets: &mut WidgetRegistrar) -> ViewList {
        let header = match &model.fetched {
            Some(g) => g.clone(),
            None => "loading".into(),
        };
        window("main")
            .child(
                column()
                    .spacing(8.0)
                    .child(text(&header).id("header"))
                    .child(text(&format!("ticks: {}", model.ticks)).id("counter")),
            )
            .into()
    }
}

#[test]
fn lifecycle_init_async_subscribe_timer_view() {
    use plushie::runtime_internals::SubOp;

    let mut session = TestSession::<LifecycleApp>::start();

    // After init: the async task ran inline (TestSession drains
    // pending_async at startup), so the fetch resolved and
    // `fetched` is populated. `ticking` is now true.
    assert_eq!(session.model().fetched.as_deref(), Some("hi"));
    assert!(session.model().ticking);

    // The initial view was built before run_pending_async fired
    // the async result through update. Force a re-render so the
    // tree reflects the resolved model (mirrors the renderer's
    // own diff-after-event cycle).
    session.rerender();
    session.assert_text("header", "hi");
    session.assert_text("counter", "ticks: 0");

    // Subscriptions are diff'd on every dispatch, but `start` itself
    // doesn't run a diff. Drive a no-op dispatch to flush the
    // subscription manager and pick up the new "tick" sub.
    session.advance_subscriptions();
    let started_tick = session
        .last_subscription_ops()
        .iter()
        .any(|op| matches!(op, SubOp::StartTimer { tag, .. } if tag == "tick"));
    assert!(
        started_tick,
        "expected a Subscribe op for the `tick` subscription after the fetch settled, got: {:?}",
        session.last_subscription_ops(),
    );

    // Simulate the renderer firing the timer subscription.
    session.dispatch(Event::Timer(plushie::event::TimerEvent {
        tag: "tick".into(),
        timestamp: 16,
    }));
    session.dispatch(Event::Timer(plushie::event::TimerEvent {
        tag: "tick".into(),
        timestamp: 32,
    }));

    // The model and the view both show the accumulated ticks.
    assert_eq!(session.model().ticks, 2);
    session.assert_text("counter", "ticks: 2");
}

#[test]
fn dispatch_depth_limit_stops_pathological_update_loop() {
    let mut session = TestSession::<LoopApp>::start().allow_diagnostics();
    session.dispatch(Event::Timer(plushie::event::TimerEvent {
        tag: "tick".into(),
        timestamp: 0,
    }));

    // The first tick runs, then the SendAfter chain re-entering
    // `update` gets clamped by the dispatch depth guard. The app must
    // see one update call per chain step up to (but not past) the cap.
    let ticks = session.model().ticks;
    assert!(ticks > 0, "expected at least one tick");
    assert!(
        ticks <= plushie::runtime_config::DISPATCH_DEPTH_LIMIT as u32 + 1,
        "update ran {ticks} times; expected at most {}",
        plushie::runtime_config::DISPATCH_DEPTH_LIMIT as u32 + 1
    );

    let diags = session.typed_diagnostics();
    assert!(
        diags
            .iter()
            .any(|d| matches!(d, plushie_core::Diagnostic::DispatchLoopExceeded { .. })),
        "expected DispatchLoopExceeded diagnostic; got {diags:?}"
    );
}