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::dynamic("Draft", move || status_state.borrow().status())
106        .theme(theme)
107        .color(theme.palette.text_muted);
108
109    let enabled_state = Rc::clone(&state);
110    let submit_state = Rc::clone(&state);
111    let submit = Button::new("Save profile")
112        .theme(theme)
113        .enabled_when(move || enabled_state.borrow().can_submit())
114        .on_press_with_ctx(move |ctx| {
115            submit_state.borrow_mut().submissions += 1;
116            refresh_window(ctx);
117        });
118
119    let form = Stack::vertical()
120        .spacing(12.0)
121        .alignment(Alignment::Start)
122        .with_child(
123            Label::new("Create a profile")
124                .theme(theme)
125                .font_size(26.0)
126                .line_height(32.0)
127                .color(theme.palette.text),
128        )
129        .with_child(
130            Label::new("Enter a name, password, and local appointment time.")
131                .theme(theme)
132                .color(theme.palette.text_muted),
133        )
134        .with_child(name)
135        .with_child(password)
136        .with_child(scheduled_for)
137        .with_child(submit)
138        .with_child(status);
139
140    let card = Surface::panel(form).theme(theme).padding(Insets::all(20.0));
141    let root = Surface::window(card)
142        .theme(theme)
143        .padding(Insets::all(24.0))
144        .fill();
145
146    App::new()
147        .window(Window::new("Stateful SUI Form").root(root))
148        .run()
149}