use std::any::TypeId;
use accesskit::{Node, Role};
use tracing::{Span, trace_span};
use crate::TextAlign;
use crate::core::{
AccessCtx, ArcStr, ChildrenIds, EventCtx, LayoutCtx, MeasureCtx, NewWidget, NoAction, PaintCtx,
PointerButton, PointerButtonEvent, PointerEvent, PrePaintProps, PropertiesMut, PropertiesRef,
RegisterCtx, TextEvent, Update, UpdateCtx, UsesProperty, Widget, WidgetId, WidgetMut,
WidgetPod, paint_background, paint_border, paint_box_shadow,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Point, Size};
use crate::layout::{LayoutSize, LenReq, Length};
use crate::properties::{CaretColor, ContentColor, LineBreaking, PlaceholderColor, SelectionColor};
use crate::widgets::{Label, TextArea};
pub struct TextInput {
text: WidgetPod<TextArea<true>>,
placeholder: WidgetPod<Label>,
placeholder_text: ArcStr,
text_alignment: TextAlign,
clip: bool,
}
impl TextInput {
pub fn new(text: &str) -> Self {
Self::from_text_area(TextArea::new_editable(text).prepare())
}
pub fn from_text_area(text: NewWidget<TextArea<true>>) -> Self {
Self {
text: text.to_pod(),
placeholder: Label::new("")
.accessibility_hidden(true)
.prepare()
.with_props(LineBreaking::Clip)
.to_pod(),
placeholder_text: "".into(),
text_alignment: TextAlign::default(),
clip: false,
}
}
pub fn with_text_alignment(mut self, text_alignment: TextAlign) -> Self {
self.text_alignment = text_alignment;
self
}
pub fn with_placeholder(mut self, placeholder_text: impl Into<ArcStr>) -> Self {
let placeholder_text = placeholder_text.into();
let label = Label::new(placeholder_text.clone()).with_text_alignment(self.text_alignment);
self.placeholder = label
.accessibility_hidden(true)
.prepare()
.with_props(LineBreaking::Clip)
.to_pod();
self.placeholder_text = placeholder_text;
self
}
pub fn with_clip(mut self, clip: bool) -> Self {
self.clip = clip;
self
}
}
impl TextInput {
pub fn area_pod(&self) -> &WidgetPod<TextArea<true>> {
&self.text
}
}
impl TextInput {
pub fn text_mut<'t>(this: &'t mut WidgetMut<'_, Self>) -> WidgetMut<'t, TextArea<true>> {
this.ctx.get_mut(&mut this.widget.text)
}
pub fn placeholder_mut<'t>(this: &'t mut WidgetMut<'_, Self>) -> WidgetMut<'t, Label> {
this.ctx.get_mut(&mut this.widget.placeholder)
}
pub fn set_placeholder(this: &mut WidgetMut<'_, Self>, placeholder_text: impl Into<ArcStr>) {
let placeholder_text = placeholder_text.into();
this.widget.placeholder_text = placeholder_text.clone();
Label::set_text(&mut Self::placeholder_mut(this), placeholder_text.clone());
TextArea::set_placeholder(&mut Self::text_mut(this), placeholder_text);
}
pub fn set_clip(this: &mut WidgetMut<'_, Self>, clip: bool) {
this.widget.clip = clip;
this.ctx.request_layout();
}
pub fn set_text_alignment(this: &mut WidgetMut<'_, Self>, text_alignment: TextAlign) {
this.widget.text_alignment = text_alignment;
TextArea::set_text_alignment(&mut Self::text_mut(this), text_alignment);
Label::set_text_alignment(&mut Self::placeholder_mut(this), text_alignment);
}
}
impl UsesProperty<CaretColor> for TextInput {}
impl UsesProperty<PlaceholderColor> for TextInput {}
impl UsesProperty<SelectionColor> for TextInput {}
impl Widget for TextInput {
type Action = NoAction;
fn on_pointer_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &PointerEvent,
) {
match event {
PointerEvent::Down(PointerButtonEvent {
button: None | Some(PointerButton::Primary),
..
}) => {
ctx.set_focus(self.text.id());
}
_ => {}
}
}
fn on_text_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &TextEvent,
) {
match event {
TextEvent::WindowFocusChange(focused) => {
if *focused {
ctx.remove_class("#unfocused");
} else {
ctx.add_class("#unfocused");
}
}
_ => {}
}
}
fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
ctx.register_child(&mut self.text);
ctx.register_child(&mut self.placeholder);
}
fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
if property_type == TypeId::of::<CaretColor>() {
ctx.mutate_self_later(|mut input| {
let mut input = input.downcast::<Self>();
let color = *input.get_prop::<CaretColor>();
let mut text_area = Self::text_mut(&mut input);
text_area.insert_prop(color);
});
} else if property_type == TypeId::of::<SelectionColor>() {
ctx.mutate_self_later(|mut input| {
let mut input = input.downcast::<Self>();
let color = *input.get_prop::<SelectionColor>();
let mut text_area = Self::text_mut(&mut input);
text_area.insert_prop(color);
});
} else if property_type == TypeId::of::<PlaceholderColor>() {
ctx.mutate_self_later(|mut input| {
let mut input = input.downcast::<Self>();
let color = input.get_prop::<PlaceholderColor>().color;
let mut label = Self::placeholder_mut(&mut input);
label.insert_prop(ContentColor::new(color));
});
}
}
fn update(&mut self, ctx: &mut UpdateCtx<'_>, _props: &mut PropertiesMut<'_>, event: &Update) {
match event {
Update::WidgetAdded => {
ctx.mutate_self_later(|mut input| {
let mut input = input.downcast::<Self>();
let color = *input.get_prop::<CaretColor>();
let mut text_area = Self::text_mut(&mut input);
text_area.insert_prop(color);
});
ctx.mutate_self_later(|mut input| {
let mut input = input.downcast::<Self>();
let color = *input.get_prop::<SelectionColor>();
let mut text_area = Self::text_mut(&mut input);
text_area.insert_prop(color);
});
ctx.mutate_self_later(|mut input| {
let mut input = input.downcast::<Self>();
let color = input.get_prop::<PlaceholderColor>().color;
let mut label = Self::placeholder_mut(&mut input);
label.insert_prop(ContentColor::new(color));
});
ctx.mutate_self_later(|mut input| {
let mut input = input.downcast::<Self>();
let placeholder_text = input.widget.placeholder_text.clone();
TextArea::set_placeholder(&mut Self::text_mut(&mut input), placeholder_text);
});
}
Update::ChildFocusChanged(_) => {
ctx.request_pre_paint();
}
_ => {}
}
}
fn measure(
&mut self,
ctx: &mut MeasureCtx<'_>,
_props: &PropertiesRef<'_>,
axis: Axis,
len_req: LenReq,
cross_length: Option<Length>,
) -> Length {
match len_req {
LenReq::MaxContent | LenReq::MinContent => {
let auto_length = len_req.into();
let context_size = LayoutSize::maybe(axis.cross(), cross_length);
ctx.compute_length(
&mut self.text,
auto_length,
context_size,
axis,
cross_length,
)
}
LenReq::FitContent(space) => space,
}
}
fn layout(&mut self, ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, size: Size) {
ctx.run_layout(&mut self.text, size);
let child_origin = Point::ORIGIN;
ctx.place_child(&mut self.text, child_origin);
ctx.derive_baselines(&self.text);
let text_is_empty = ctx.get_raw(&mut self.text).0.is_empty();
ctx.set_stashed(&mut self.placeholder, !text_is_empty);
if text_is_empty {
ctx.run_layout(&mut self.placeholder, size);
ctx.place_child(&mut self.placeholder, child_origin);
}
if self.clip {
ctx.set_clip_path(size.to_rect());
} else {
ctx.clear_clip_path();
}
}
fn pre_paint(
&mut self,
ctx: &mut PaintCtx<'_>,
props: &PropertiesRef<'_>,
painter: &mut Painter<'_>,
) {
let bbox = ctx.border_box();
let cache = ctx.property_cache();
let p = PrePaintProps::fetch(props, cache);
paint_box_shadow(painter, bbox, p.box_shadow, p.corner_radius);
paint_background(painter, bbox, p.background, p.border_width, p.corner_radius);
paint_border(
painter,
bbox,
p.border_color,
p.border_width,
p.corner_radius,
);
}
fn paint(
&mut self,
_ctx: &mut PaintCtx<'_>,
_props: &PropertiesRef<'_>,
_painter: &mut Painter<'_>,
) {
}
fn accessibility_role(&self) -> Role {
Role::GenericContainer
}
fn accessibility(
&mut self,
_ctx: &mut AccessCtx<'_>,
_props: &PropertiesRef<'_>,
_node: &mut Node,
) {
}
fn children_ids(&self) -> ChildrenIds {
ChildrenIds::from_slice(&[self.text.id(), self.placeholder.id()])
}
fn make_trace_span(&self, id: WidgetId) -> Span {
trace_span!("TextInput", id = id.trace())
}
fn get_debug_text(&self) -> Option<String> {
self.clip.then(|| "(clip)".into())
}
}
#[cfg(test)]
mod tests {
use masonry_testing::TestHarnessParams;
use super::*;
use crate::core::{StyleProperty, TextEvent, WidgetTag};
use crate::dpi::LogicalSize;
use crate::testing::{TestHarness, assert_render_snapshot};
use crate::theme::test_property_set;
use crate::util::Duration;
use crate::widgets::TextArea;
const HARNESS_PARAMS: TestHarnessParams = {
let mut params = TestHarnessParams::DEFAULT;
params.window_size = LogicalSize::new(150, 40);
params.root_padding = 15;
params
};
#[test]
fn text_input_outline() {
let text_area_tag = WidgetTag::named("text_area");
let text_input = NewWidget::new(TextInput::from_text_area(
TextArea::new_editable("TextInput contents")
.with_style(StyleProperty::FontSize(14.0))
.prepare()
.with_tag(text_area_tag),
));
let mut harness = TestHarness::create_with(test_property_set(), text_input, HARNESS_PARAMS);
assert_render_snapshot!(harness, "text_input_outline");
harness.edit_root_widget(|mut text_input| {
let mut text_area = TextInput::text_mut(&mut text_input);
TextArea::select_text(&mut text_area, "contents");
});
harness.focus_on(text_area_tag);
assert_render_snapshot!(harness, "text_input_selection");
harness.process_text_event(TextEvent::WindowFocusChange(false));
assert_render_snapshot!(harness, "text_input_selection_unfocused");
harness.process_text_event(TextEvent::WindowFocusChange(true));
harness.advance_time(Duration::from_millis(500));
assert_render_snapshot!(harness, "text_input_cursor_blink");
}
#[test]
fn placeholder() {
let text_input = NewWidget::new(
TextInput::from_text_area(
TextArea::new_editable("")
.with_style(StyleProperty::FontSize(14.0))
.prepare(),
)
.with_placeholder("HELLO WORLD"),
);
let mut harness = TestHarness::create_with(test_property_set(), text_input, HARNESS_PARAMS);
assert_render_snapshot!(harness, "text_input_placeholder");
}
#[test]
fn placeholder_is_exposed_on_text_area_accessibility_node() {
let text_input = NewWidget::new(TextInput::new("").with_placeholder("Search"));
let text_area_id = text_input.widget.area_pod().id();
let placeholder_id = text_input.widget.placeholder.id();
let mut harness = TestHarness::create_with(test_property_set(), text_input, HARNESS_PARAMS);
let text_area_tag = harness.make_dyn_tag_for_widget(text_area_id);
let placeholder_tag = harness.make_dyn_tag_for_widget(placeholder_id);
let text_input_node = harness.access_node(harness.root_tag()).unwrap();
assert_eq!(text_input_node.data().placeholder(), None);
assert_eq!(text_input_node.child_ids().count(), 2);
let placeholder_node = harness.access_node(placeholder_tag).unwrap();
assert!(placeholder_node.is_hidden());
let text_area_node = harness.access_node(text_area_tag).unwrap();
assert_eq!(text_area_node.data().placeholder(), Some("Search"));
harness.edit_root_widget(|mut text_input| {
TextInput::set_placeholder(&mut text_input, "Filter");
});
let _ = harness.redraw();
let text_area_node = harness.access_node(text_area_tag).unwrap();
assert_eq!(text_area_node.data().placeholder(), Some("Filter"));
}
#[test]
fn text_input_clips() {
let text_input = NewWidget::new(
TextInput::from_text_area(
TextArea::new_editable("TextInput contents which should be clipped")
.with_style(StyleProperty::FontSize(14.0))
.with_word_wrap(false)
.prepare(),
)
.with_clip(true),
);
let mut harness = TestHarness::create_with(test_property_set(), text_input, HARNESS_PARAMS);
assert_render_snapshot!(harness, "text_input_clip");
}
}