Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added OptionFormatter TextBox Formatter #2193

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ Laura Gallo
Tim Murison
Manmeet Singh
Simon Fell
Sean Cohan
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ You can find its changes [documented below](#070---2021-01-01).

### Added

- OptionFormatter TextBox Formatter ([#2193] by [@meettitan])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately the links don't get automatically generated. Please define both [#2193] and [@meettitan] at the bottom of the file.

- Strikethrough rich text attribute ([#1953] by [@jenra-uwu])
- System fonts loaded so that SVG images render text ([#1850] by [@DrGabble])
- Add `scroll()` method in WidgetExt ([#1600] by [@totsteps])
Expand Down
54 changes: 54 additions & 0 deletions druid/src/text/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,57 @@ impl<T: std::fmt::Display> Default for ParseFormatter<T> {
ParseFormatter::new()
}
}

/// A naive [`Formatter`] for optional types that implement [`FromStr`].
///
/// Maps empty strings to None
/// Some types that impl [`FromStr`], such as integer values, do not allow empty strings as valid values.
/// In these cases, a user cannot remove all text from the text box.
/// To allow users to remove all text, an option can be used to account for empty strings.
///
/// [`Formatter`]: Formatter
/// [`FromStr`]: std::str::FromStr
/// ```
/// use druid::text::OptionFormatter;
/// use druid::{Data, Lens, Widget, WidgetExt};
/// use druid::widget::TextBox;
/// #[derive(Data, Clone, Lens)]
/// struct State {
/// float: Option<f64>
/// }
///
/// fn optional_float_text_box() -> impl Widget<State> {
/// TextBox::new().with_formatter(OptionFormatter).lens(State::float)
/// }
/// ```
pub struct OptionFormatter;

impl<T> Formatter<Option<T>> for OptionFormatter
where
T: std::fmt::Display + FromStr,
<T as FromStr>::Err: std::error::Error + 'static,
{
fn format(&self, value: &Option<T>) -> String {
match value {
None => String::new(),
Some(value) => value.to_string(),
}
}

fn validate_partial_input(&self, input: &str, _sel: &Selection) -> Validation {
if input.is_empty() {
return Validation::success();
}
match input.parse::<T>() {
Ok(_) => Validation::success(),
Err(e) => Validation::failure(e),
}
}

fn value(&self, input: &str) -> Result<Option<T>, ValidationError> {
if input.is_empty() {
return Ok(None);
}
Some(input.parse::<T>().map_err(ValidationError::new)).transpose()
}
}
4 changes: 3 additions & 1 deletion druid/src/text/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ pub use self::attribute::{Attribute, AttributeSpans, Link};
pub use self::backspace::offset_for_delete_backwards;
pub use self::editable_text::{EditableText, EditableTextCursor, StringCursor};
pub use self::font_descriptor::FontDescriptor;
pub use self::format_priv::{Formatter, ParseFormatter, Validation, ValidationError};
pub use self::format_priv::{
Formatter, OptionFormatter, ParseFormatter, Validation, ValidationError,
};
pub use self::layout::{LayoutMetrics, TextLayout};
pub use self::movement::movement;
pub use input_component::{EditSession, TextComponent};
Expand Down