Skip to main content

stateful_form/
stateful_form.rs

1use std::{cell::RefCell, rc::Rc};
2
3use sui::{InvalidationKind, InvalidationRequest, InvalidationTarget, prelude::*};
4
5#[derive(Debug)]
6struct FormState {
7    name: String,
8    password: String,
9    scheduled_for: String,
10    submissions: u32,
11}
12
13impl Default for FormState {
14    fn default() -> Self {
15        Self {
16            name: String::new(),
17            password: String::new(),
18            scheduled_for: "2026-07-18 10:00".to_string(),
19            submissions: 0,
20        }
21    }
22}
23
24impl FormState {
25    fn can_submit(&self) -> bool {
26        !self.name.trim().is_empty()
27            && self.password.chars().count() >= 8
28            && !self.scheduled_for.trim().is_empty()
29    }
30
31    fn status(&self) -> String {
32        if self.submissions == 0 {
33            format!(
34                "Draft for {} · {} password characters · scheduled {}",
35                display_name(&self.name),
36                self.password.chars().count(),
37                self.scheduled_for
38            )
39        } else {
40            format!(
41                "Saved {} time(s) for {} at {}",
42                self.submissions,
43                display_name(&self.name),
44                self.scheduled_for
45            )
46        }
47    }
48}
49
50fn display_name(name: &str) -> &str {
51    if name.trim().is_empty() {
52        "an unnamed user"
53    } else {
54        name.trim()
55    }
56}
57
58fn refresh_window(ctx: &mut EventCtx) {
59    let target = InvalidationTarget::Window(ctx.window_id());
60    for kind in [
61        InvalidationKind::Measure,
62        InvalidationKind::Paint,
63        InvalidationKind::Semantics,
64    ] {
65        ctx.request(InvalidationRequest::new(target, kind));
66    }
67}
68
69fn main() -> Result<()> {
70    let theme = DefaultTheme::dark();
71    let state = Rc::new(RefCell::new(FormState::default()));
72
73    let name_state = Rc::clone(&state);
74    let name = TextInput::new("Display name")
75        .placeholder("Ada Lovelace")
76        .min_width(360.0)
77        .theme(theme)
78        .on_change_with_ctx(move |ctx, value| {
79            name_state.borrow_mut().name = value;
80            refresh_window(ctx);
81        });
82
83    let password_state = Rc::clone(&state);
84    let password = PasswordInput::new("Password")
85        .placeholder("At least eight characters")
86        .min_width(360.0)
87        .theme(theme)
88        .on_change_with_ctx(move |ctx, value| {
89            password_state.borrow_mut().password = value;
90            refresh_window(ctx);
91        });
92
93    let initial_schedule = state.borrow().scheduled_for.clone();
94    let schedule_state = Rc::clone(&state);
95    let scheduled_for = DateTimeInput::new("Scheduled for")
96        .value(initial_schedule)
97        .min_width(360.0)
98        .theme(theme)
99        .on_change_with_ctx(move |ctx, value| {
100            schedule_state.borrow_mut().scheduled_for = value;
101            refresh_window(ctx);
102        });
103
104    let status_state = Rc::clone(&state);
105    let status = Label::new("Draft")
106        .text_when(move || status_state.borrow().status())
107        .theme(theme)
108        .color(theme.palette.text_muted);
109
110    let enabled_state = Rc::clone(&state);
111    let submit_state = Rc::clone(&state);
112    let submit = Button::new("Save profile")
113        .theme(theme)
114        .enabled_when(move || enabled_state.borrow().can_submit())
115        .on_press_with_ctx(move |ctx| {
116            submit_state.borrow_mut().submissions += 1;
117            refresh_window(ctx);
118        });
119
120    let form = Stack::vertical()
121        .gap(12.0)
122        .alignment(Alignment::Start)
123        .with_child(
124            Label::new("Create a profile")
125                .theme(theme)
126                .font_size(26.0)
127                .line_height(32.0)
128                .color(theme.palette.text),
129        )
130        .with_child(
131            Label::new("Enter a name, password, and local appointment time.")
132                .theme(theme)
133                .color(theme.palette.text_muted),
134        )
135        .with_child(name)
136        .with_child(password)
137        .with_child(scheduled_for)
138        .with_child(submit)
139        .with_child(status);
140
141    let card = Surface::panel(form).theme(theme).padding(Insets::all(20.0));
142    let root = Surface::window(card)
143        .theme(theme)
144        .padding(Insets::all(24.0))
145        .fill();
146
147    App::new()
148        .window(Window::new("Stateful SUI Form").root(root))
149        .run()
150}