Skip to main content

waft_winui/controls/
password_box.rs

1//! WinUI PasswordBox template and behavior, using Waft’s native editing engine.
2
3use super::text_control::TextControl;
4use crate::Brush;
5use std::{fmt, rc::Rc};
6use waft_embedder::Color;
7use waft_foundation::{App, Handle};
8use waft_services::TextInputFormatterRef;
9use waft_widgets::*;
10
11use super::text_box::{TextBox, TextChangedCallback};
12
13/// WinUI PasswordRevealMode; Peek reveals only while the eye button or Alt+F8 is held.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub enum PasswordRevealMode {
16    /// Permit press-to-reveal after a new password was entered during this focus session.
17    #[default]
18    Peek,
19    /// Always conceal the password and hide the reveal button.
20    Hidden,
21    /// Always display the password and hide the reveal button.
22    Visible,
23}
24
25/// The WinUI PasswordBox control with its default Fluent template.
26#[derive(Clone)]
27pub struct PasswordBox {
28    /// Owns the text, selection and composing range; the caller retains and disposes it.
29    pub controller: TextEditingControllerRef,
30
31    /// An optional caller-owned focus node; otherwise the control creates one.
32    pub focus_node: Option<FocusNodeRef>,
33
34    /// Content above the editor, with the source header margin.
35    pub header: Option<WidgetRef>,
36
37    /// Supporting content below the editor.
38    pub description: Option<WidgetRef>,
39
40    /// Text displayed while the controller is empty.
41    pub placeholder_text: String,
42
43    /// Whether the editor accepts pointer and keyboard input.
44    pub is_enabled: bool,
45
46    /// The editor font size and basis of the helper-button width threshold; the theme's `ControlContentThemeFontSize` when `None`.
47    pub font_size: Option<f64>,
48
49    /// Editor padding in left, top, right, bottom order; the theme's `TextControlThemePadding` when `None`.
50    pub padding: Option<[f64; 4]>,
51
52    /// The template border and helper-button corner radius.
53    pub corner_radius: Option<f64>,
54
55    /// Overrides the normal editor foreground; visual states use their source theme resources.
56    pub foreground: Option<Color>,
57
58    /// Overrides the normal editor background.
59    pub background: Option<Brush>,
60
61    /// Overrides the normal editor border brush.
62    pub border_brush: Option<Brush>,
63
64    /// Overrides the selection fill while the editor has focus.
65    pub selection_highlight_color: Option<Color>,
66
67    /// Limits user edits through the native length formatter; programmatic assignments remain unrestricted.
68    pub max_length: Option<i32>,
69
70    /// Native formatters applied to user edits, following Flutter composition and undo behavior.
71    pub input_formatters: Vec<TextInputFormatterRef>,
72
73    /// Requests initial keyboard focus through the native editor.
74    pub autofocus: bool,
75
76    /// Overrides the desktop text-command menu.
77    pub context_menu_builder: Option<EditableTextContextMenuBuilder>,
78
79    /// Controls whether the password can be temporarily revealed, stays hidden, or stays visible.
80    pub password_reveal_mode: PasswordRevealMode,
81
82    /// The character displayed for each concealed password character.
83    pub password_char: char,
84
85    /// Receives user password edits; listen to the controller for programmatic assignments.
86    pub password_changed: Option<TextChangedCallback>,
87
88    /// Identity retained across parent rebuilds.
89    pub key: Option<KeyRef>,
90}
91
92impl PasswordBox {
93    /// Creates an editor using a caller-owned native editing controller.
94    pub fn new(controller: TextEditingControllerRef) -> Self {
95        Self {
96            controller,
97            focus_node: None,
98            header: None,
99            description: None,
100            placeholder_text: String::new(),
101            is_enabled: true,
102            font_size: None,
103            padding: None,
104            corner_radius: None,
105            foreground: None,
106            background: None,
107            border_brush: None,
108            selection_highlight_color: None,
109            max_length: None,
110            input_formatters: Vec::new(),
111            autofocus: false,
112            context_menu_builder: None,
113            password_reveal_mode: PasswordRevealMode::Peek,
114            password_char: '●',
115            password_changed: None,
116            key: None,
117        }
118    }
119
120    /// Sets FocusNode.
121    pub fn focus_node(mut self, value: FocusNodeRef) -> Self {
122        self.focus_node = Some(value);
123        self
124    }
125
126    /// Sets Header.
127    #[cfg_attr(debug_assertions, track_caller)]
128    pub fn header<K>(mut self, value: impl IntoWidget<K>) -> Self {
129        self.header = Some(value.into_widget());
130        self
131    }
132
133    /// Sets Description.
134    #[cfg_attr(debug_assertions, track_caller)]
135    pub fn description<K>(mut self, value: impl IntoWidget<K>) -> Self {
136        self.description = Some(value.into_widget());
137        self
138    }
139
140    /// Sets PlaceholderText.
141    pub fn placeholder_text(mut self, value: impl Into<String>) -> Self {
142        self.placeholder_text = value.into();
143        self
144    }
145
146    /// Sets IsEnabled.
147    pub fn is_enabled(mut self, value: bool) -> Self {
148        self.is_enabled = value;
149        self
150    }
151
152    /// Sets FontSize.
153    pub fn font_size(mut self, value: f64) -> Self {
154        self.font_size = Some(value);
155        self
156    }
157
158    /// Sets Padding.
159    pub fn padding(mut self, value: [f64; 4]) -> Self {
160        self.padding = Some(value);
161        self
162    }
163
164    /// Sets CornerRadius.
165    pub fn corner_radius(mut self, value: f64) -> Self {
166        self.corner_radius = Some(value);
167        self
168    }
169
170    /// Sets Foreground.
171    pub fn foreground(mut self, value: Color) -> Self {
172        self.foreground = Some(value);
173        self
174    }
175
176    /// Sets Background.
177    pub fn background(mut self, value: Brush) -> Self {
178        self.background = Some(value);
179        self
180    }
181
182    /// Sets BorderBrush.
183    pub fn border_brush(mut self, value: Brush) -> Self {
184        self.border_brush = Some(value);
185        self
186    }
187
188    /// Sets SelectionHighlightColor.
189    pub fn selection_highlight_color(mut self, value: Color) -> Self {
190        self.selection_highlight_color = Some(value);
191        self
192    }
193
194    /// Sets MaxLength.
195    pub fn max_length(mut self, value: i32) -> Self {
196        assert!(value >= 0, "MaxLength must be non-negative");
197        self.max_length = Some(value);
198        self
199    }
200
201    /// Sets InputFormatters.
202    pub fn input_formatters(mut self, value: Vec<TextInputFormatterRef>) -> Self {
203        self.input_formatters = value;
204        self
205    }
206
207    /// Sets Autofocus.
208    pub fn autofocus(mut self, value: bool) -> Self {
209        self.autofocus = value;
210        self
211    }
212
213    /// Sets ContextMenuBuilder.
214    pub fn context_menu_builder(
215        mut self,
216        value: impl Fn(&mut App, BuildContext, Handle<EditableTextState>) -> WidgetRef + 'static,
217    ) -> Self {
218        self.context_menu_builder = Some(Rc::new(value));
219        self
220    }
221
222    /// Sets PasswordRevealMode.
223    pub fn password_reveal_mode(mut self, value: PasswordRevealMode) -> Self {
224        self.password_reveal_mode = value;
225        self
226    }
227
228    /// Sets PasswordChar.
229    pub fn password_char(mut self, value: char) -> Self {
230        assert!(
231            value != '\0' && value.len_utf16() == 1,
232            "PasswordChar must be one non-null UTF-16 character"
233        );
234        self.password_char = value;
235        self
236    }
237
238    /// Sets PasswordChanged.
239    pub fn password_changed(mut self, value: impl Fn(&mut App, String) + 'static) -> Self {
240        self.password_changed = Some(Rc::new(value));
241        self
242    }
243
244    /// Sets widget identity.
245    pub fn key(mut self, key: KeyRef) -> Self {
246        self.key = Some(key);
247        self
248    }
249}
250
251impl fmt::Debug for PasswordBox {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        f.debug_struct("PasswordBox")
254            .field("is_enabled", &self.is_enabled)
255            .finish_non_exhaustive()
256    }
257}
258
259impl StatelessWidget for PasswordBox {
260    fn key(&self) -> Option<&KeyRef> {
261        self.key.as_ref()
262    }
263
264    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
265        let mut editor = TextBox::new(self.controller.clone());
266        editor.focus_node = self.focus_node.clone();
267        editor.header = self.header.clone();
268        editor.description = self.description.clone();
269        editor.placeholder_text = self.placeholder_text.clone();
270        editor.is_enabled = self.is_enabled;
271        editor.font_size = self.font_size;
272        editor.padding = self.padding;
273        editor.corner_radius = self.corner_radius;
274        editor.foreground = self.foreground;
275        editor.background = self.background;
276        editor.border_brush = self.border_brush;
277        editor.selection_highlight_color = self.selection_highlight_color;
278        editor.max_length = self.max_length;
279        editor.input_formatters = self.input_formatters.clone();
280        editor.autofocus = self.autofocus;
281        editor.context_menu_builder = self.context_menu_builder.clone();
282        editor.text_changed = self.password_changed.clone();
283
284        TextControl::new(
285            editor,
286            Some((self.password_reveal_mode, self.password_char)),
287        )
288        .into_widget()
289    }
290}