use cranpose_foundation::text::{TextFieldLineLimits, TextFieldState, TextRange};
use cranpose_foundation::{
Constraints, DelegatableNode, DrawModifierNode, DrawScope, InvalidationKind,
LayoutModifierNode, Measurable, ModifierNode, ModifierNodeContext, ModifierNodeElement,
NodeCapabilities, NodeState, PointerEvent, PointerEventKind, PointerInputNode,
SemanticsConfiguration, SemanticsNode, Size,
};
use cranpose_ui_graphics::{Brush, Color};
use std::cell::{Cell, RefCell};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
const DEFAULT_CURSOR_COLOR: Color = Color(1.0, 1.0, 1.0, 1.0);
const DEFAULT_SELECTION_COLOR: Color = Color(0.0, 0.5, 1.0, 0.3);
const DOUBLE_CLICK_MS: u128 = 500;
const DEFAULT_LINE_HEIGHT: f32 = 20.0;
const CURSOR_WIDTH: f32 = 2.0;
pub(crate) fn compute_horizontal_scroll_offset(
current_offset: f32,
cursor_x: f32,
text_width: f32,
viewport_width: f32,
) -> f32 {
if viewport_width <= 0.0 {
return 0.0;
}
let max_offset = (text_width + CURSOR_WIDTH - viewport_width).max(0.0);
let mut offset = current_offset.clamp(0.0, max_offset);
let visible_end = offset + viewport_width - CURSOR_WIDTH;
if cursor_x > visible_end {
offset = cursor_x - viewport_width + CURSOR_WIDTH;
} else if cursor_x < offset {
offset = cursor_x;
}
offset.clamp(0.0, max_offset)
}
pub(crate) fn intersect_rect(
rect: cranpose_ui_graphics::Rect,
bounds: cranpose_ui_graphics::Rect,
) -> Option<cranpose_ui_graphics::Rect> {
let x0 = rect.x.max(bounds.x);
let y0 = rect.y.max(bounds.y);
let x1 = (rect.x + rect.width).min(bounds.x + bounds.width);
let y1 = (rect.y + rect.height).min(bounds.y + bounds.height);
(x1 > x0 && y1 > y0).then_some(cranpose_ui_graphics::Rect {
x: x0,
y: y0,
width: x1 - x0,
height: y1 - y0,
})
}
pub type TextPanResolver = Rc<dyn Fn(f32) -> f32>;
#[derive(Clone)]
pub(crate) struct TextFieldRefs {
pub is_focused: Rc<RefCell<bool>>,
pub content_offset: Rc<Cell<f32>>,
pub content_y_offset: Rc<Cell<f32>>,
pub drag_anchor: Rc<Cell<Option<usize>>>,
pub last_click_time: Rc<Cell<Option<web_time::Instant>>>,
pub click_count: Rc<Cell<u8>>,
pub node_id: Rc<Cell<Option<cranpose_core::NodeId>>>,
pub scroll_offset: Rc<Cell<f32>>,
}
impl TextFieldRefs {
pub fn new() -> Self {
Self {
is_focused: Rc::new(RefCell::new(false)),
content_offset: Rc::new(Cell::new(0.0_f32)),
content_y_offset: Rc::new(Cell::new(0.0_f32)),
drag_anchor: Rc::new(Cell::new(None::<usize>)),
last_click_time: Rc::new(Cell::new(None::<web_time::Instant>)),
click_count: Rc::new(Cell::new(0_u8)),
node_id: Rc::new(Cell::new(None::<cranpose_core::NodeId>)),
scroll_offset: Rc::new(Cell::new(0.0_f32)),
}
}
}
use crate::text::TextStyle;
pub struct TextFieldModifierNode {
state: TextFieldState,
refs: TextFieldRefs,
style: TextStyle, cursor_brush: Brush,
selection_brush: Brush,
line_limits: TextFieldLineLimits,
cached_text: String,
cached_selection: TextRange,
node_state: NodeState,
measured_size: Rc<Cell<Size>>,
measured_line_height: Rc<Cell<f32>>,
cached_handler: Rc<dyn Fn(PointerEvent)>,
cached_pan_resolver: TextPanResolver,
}
impl std::fmt::Debug for TextFieldModifierNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TextFieldModifierNode")
.field("text", &self.state.text())
.field("style", &self.style)
.field("is_focused", &*self.refs.is_focused.borrow())
.finish()
}
}
use crate::text_field_handler::TextFieldHandler;
impl TextFieldModifierNode {
pub fn new(state: TextFieldState, style: TextStyle) -> Self {
let value = state.value();
let refs = TextFieldRefs::new();
let line_limits = TextFieldLineLimits::default();
let cached_handler =
Self::create_handler(state.clone(), refs.clone(), line_limits, style.clone());
let cached_pan_resolver =
Self::create_pan_resolver(state.clone(), refs.clone(), line_limits, style.clone());
Self {
state,
refs,
style,
cursor_brush: Brush::solid(DEFAULT_CURSOR_COLOR),
selection_brush: Brush::solid(DEFAULT_SELECTION_COLOR),
line_limits,
cached_text: value.text,
cached_selection: value.selection,
node_state: NodeState::new(),
measured_size: Rc::new(Cell::new(Size {
width: 0.0,
height: 0.0,
})),
measured_line_height: Rc::new(Cell::new(DEFAULT_LINE_HEIGHT)),
cached_handler,
cached_pan_resolver,
}
}
pub fn with_line_limits(mut self, line_limits: TextFieldLineLimits) -> Self {
self.line_limits = line_limits;
self.cached_pan_resolver = Self::create_pan_resolver(
self.state.clone(),
self.refs.clone(),
line_limits,
self.style.clone(),
);
self
}
fn create_pan_resolver(
state: TextFieldState,
refs: TextFieldRefs,
line_limits: TextFieldLineLimits,
style: TextStyle,
) -> TextPanResolver {
Rc::new(move |viewport_width: f32| {
if !line_limits.is_single_line() {
refs.scroll_offset.set(0.0);
return 0.0;
}
let text = state.text();
let pos = state.selection().start.min(text.len());
let text_width = crate::text::measure_text(
&crate::text::AnnotatedString::from(text.as_str()),
&style,
)
.width;
let cursor_x = crate::text::measure_text(
&crate::text::AnnotatedString::from(&text[..pos]),
&style,
)
.width;
let offset = compute_horizontal_scroll_offset(
refs.scroll_offset.get(),
cursor_x,
text_width,
viewport_width,
);
refs.scroll_offset.set(offset);
offset
})
}
pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
self.line_limits
.is_single_line()
.then(|| self.cached_pan_resolver.clone())
}
pub fn scroll_offset(&self) -> f32 {
self.refs.scroll_offset.get()
}
pub fn line_limits(&self) -> TextFieldLineLimits {
self.line_limits
}
fn create_handler(
state: TextFieldState,
refs: TextFieldRefs,
line_limits: TextFieldLineLimits,
style: TextStyle, ) -> Rc<dyn Fn(PointerEvent)> {
use crate::word_boundaries::find_word_boundaries;
Rc::new(move |event: PointerEvent| {
let click_x =
(event.position.x - refs.content_offset.get() + refs.scroll_offset.get()).max(0.0);
let click_y = (event.position.y - refs.content_y_offset.get()).max(0.0);
match event.kind {
PointerEventKind::Down => {
let handler =
TextFieldHandler::new(state.clone(), refs.node_id.get(), line_limits);
crate::text_field_focus::request_focus(refs.is_focused.clone(), handler);
let now = web_time::Instant::now();
let text = state.text();
let pos = crate::text::get_offset_for_position(
&crate::text::AnnotatedString::from(text.as_str()),
&style,
click_x,
click_y,
);
let is_double_click = if let Some(last) = refs.last_click_time.get() {
now.duration_since(last).as_millis() < DOUBLE_CLICK_MS
} else {
false
};
if is_double_click {
let count = refs.click_count.get() + 1;
refs.click_count.set(count.min(3));
if count >= 3 {
state.edit(|buffer| {
buffer.select_all();
});
refs.drag_anchor.set(Some(0));
} else if count >= 2 {
let (word_start, word_end) = find_word_boundaries(&text, pos);
state.edit(|buffer| {
buffer.select(TextRange::new(word_start, word_end));
});
refs.drag_anchor.set(Some(word_start));
}
} else {
refs.click_count.set(1);
refs.drag_anchor.set(Some(pos));
state.edit(|buffer| {
buffer.place_cursor_before_char(pos);
});
}
refs.last_click_time.set(Some(now));
event.consume();
}
PointerEventKind::Move => {
if let Some(anchor) = refs.drag_anchor.get() {
if *refs.is_focused.borrow() {
let text = state.text();
let current_pos = crate::text::get_offset_for_position(
&crate::text::AnnotatedString::from(text.as_str()),
&style,
click_x,
click_y,
);
state.set_selection(TextRange::new(anchor, current_pos));
crate::request_render_invalidation();
event.consume();
}
}
}
PointerEventKind::Up => {
refs.drag_anchor.set(None);
}
_ => {}
}
})
}
pub fn with_cursor_color(mut self, color: Color) -> Self {
self.cursor_brush = Brush::solid(color);
self
}
pub fn set_focused(&mut self, focused: bool) {
let current = *self.refs.is_focused.borrow();
if current != focused {
*self.refs.is_focused.borrow_mut() = focused;
}
}
pub fn is_focused(&self) -> bool {
*self.refs.is_focused.borrow()
}
pub fn is_focused_rc(&self) -> Rc<RefCell<bool>> {
self.refs.is_focused.clone()
}
pub fn content_offset_rc(&self) -> Rc<Cell<f32>> {
self.refs.content_offset.clone()
}
pub fn content_y_offset_rc(&self) -> Rc<Cell<f32>> {
self.refs.content_y_offset.clone()
}
pub fn text(&self) -> String {
self.state.text()
}
pub fn style(&self) -> &TextStyle {
&self.style
}
pub fn selection(&self) -> TextRange {
self.state.selection()
}
pub fn cursor_brush(&self) -> Brush {
self.cursor_brush.clone()
}
pub fn selection_brush(&self) -> Brush {
self.selection_brush.clone()
}
pub fn insert_text(&mut self, text: &str) {
self.state.edit(|buffer| {
buffer.insert(text);
});
}
pub fn copy_selection(&self) -> Option<String> {
self.state.copy_selection()
}
pub fn cut_selection(&mut self) -> Option<String> {
let text = self.copy_selection();
if text.is_some() {
self.state.edit(|buffer| {
buffer.delete(buffer.selection());
});
}
text
}
pub fn get_state(&self) -> cranpose_foundation::text::TextFieldState {
self.state.clone()
}
pub fn set_content_offset(&self, offset: f32) {
self.refs.content_offset.set(offset);
}
pub fn set_content_y_offset(&self, offset: f32) {
self.refs.content_y_offset.set(offset);
}
fn measure_text_content(&self) -> Size {
let text = self.state.text();
let node_id = self.refs.node_id.get();
let metrics = crate::text::measure_text_for_node(
node_id,
&crate::text::AnnotatedString::from(text.as_str()),
&self.style,
);
self.measured_line_height.set(metrics.line_height);
Size {
width: metrics.width,
height: metrics.height,
}
}
fn update_cached_state(&mut self) -> bool {
let value = self.state.value();
let text_changed = value.text != self.cached_text;
let selection_changed = value.selection != self.cached_selection;
if text_changed {
self.cached_text = value.text;
}
if selection_changed {
self.cached_selection = value.selection;
}
text_changed || selection_changed
}
pub fn position_cursor_at_offset(&self, x_offset: f32) {
let text = self.state.text();
if text.is_empty() {
self.state.edit(|buffer| {
buffer.place_cursor_at_start();
});
return;
}
let byte_offset = crate::text::get_offset_for_position(
&crate::text::AnnotatedString::from(text.as_str()),
&self.style,
x_offset + self.refs.scroll_offset.get(),
0.0,
);
self.state.edit(|buffer| {
buffer.place_cursor_before_char(byte_offset);
});
}
}
impl DelegatableNode for TextFieldModifierNode {
fn node_state(&self) -> &NodeState {
&self.node_state
}
}
impl ModifierNode for TextFieldModifierNode {
fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
self.refs.node_id.set(context.node_id());
context.invalidate(InvalidationKind::Layout);
context.invalidate(InvalidationKind::Draw);
context.invalidate(InvalidationKind::Semantics);
}
fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
Some(self)
}
fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
Some(self)
}
fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
Some(self)
}
fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
Some(self)
}
fn as_semantics_node(&self) -> Option<&dyn SemanticsNode> {
Some(self)
}
fn as_semantics_node_mut(&mut self) -> Option<&mut dyn SemanticsNode> {
Some(self)
}
fn as_pointer_input_node(&self) -> Option<&dyn PointerInputNode> {
Some(self)
}
fn as_pointer_input_node_mut(&mut self) -> Option<&mut dyn PointerInputNode> {
Some(self)
}
}
impl LayoutModifierNode for TextFieldModifierNode {
fn measure(
&self,
_context: &mut dyn ModifierNodeContext,
_measurable: &dyn Measurable,
constraints: Constraints,
) -> cranpose_ui_layout::LayoutModifierMeasureResult {
let text_size = self.measure_text_content();
let min_height = if text_size.height < 1.0 {
DEFAULT_LINE_HEIGHT
} else {
text_size.height
};
let width = text_size
.width
.max(constraints.min_width)
.min(constraints.max_width);
let height = min_height
.max(constraints.min_height)
.min(constraints.max_height);
let size = Size { width, height };
self.measured_size.set(size);
let _ = (self.cached_pan_resolver)(size.width);
cranpose_ui_layout::LayoutModifierMeasureResult::with_size(size)
}
fn min_intrinsic_width(&self, _measurable: &dyn Measurable, _height: f32) -> f32 {
self.measure_text_content().width
}
fn max_intrinsic_width(&self, _measurable: &dyn Measurable, _height: f32) -> f32 {
self.measure_text_content().width
}
fn min_intrinsic_height(&self, _measurable: &dyn Measurable, _width: f32) -> f32 {
self.measure_text_content().height.max(DEFAULT_LINE_HEIGHT)
}
fn max_intrinsic_height(&self, _measurable: &dyn Measurable, _width: f32) -> f32 {
self.measure_text_content().height.max(DEFAULT_LINE_HEIGHT)
}
}
impl DrawModifierNode for TextFieldModifierNode {
fn draw(&self, _draw_scope: &mut dyn DrawScope) {
}
fn create_draw_closure(
&self,
) -> Option<Rc<dyn Fn(cranpose_foundation::Size) -> Vec<cranpose_ui_graphics::DrawPrimitive>>>
{
use cranpose_ui_graphics::DrawPrimitive;
let is_focused = self.refs.is_focused.clone();
let state = self.state.clone();
let content_offset = self.refs.content_offset.clone();
let content_y_offset = self.refs.content_y_offset.clone();
let cursor_brush = self.cursor_brush.clone();
let selection_brush = self.selection_brush.clone();
let style = self.style.clone();
let cached_line_height = self.measured_line_height.clone();
let measured_size = self.measured_size.clone();
let pan_resolver = self.cached_pan_resolver.clone();
Some(Rc::new(move |size| {
if !*is_focused.borrow() {
return vec![];
}
let mut primitives = Vec::new();
let text = state.text();
let selection = state.selection();
let padding_left = content_offset.get();
let padding_top = content_y_offset.get();
let line_height = cached_line_height.get();
let measured = measured_size.get();
let viewport_width = if measured.width > 0.0 {
measured.width
} else {
(size.width - padding_left).max(0.0)
};
let viewport_height = if measured.height > 0.0 {
measured.height
} else {
(size.height - padding_top).max(0.0)
};
let pan = pan_resolver(viewport_width);
let clip_bounds = cranpose_ui_graphics::Rect {
x: padding_left,
y: padding_top,
width: viewport_width,
height: viewport_height,
};
if !selection.collapsed() {
let sel_start = selection.min();
let sel_end = selection.max();
let lines: Vec<&str> = text.split('\n').collect();
let mut byte_offset: usize = 0;
for (line_idx, line) in lines.iter().enumerate() {
let line_start = byte_offset;
let line_end = byte_offset + line.len();
if sel_end > line_start && sel_start < line_end {
let sel_start_in_line = sel_start.saturating_sub(line_start);
let sel_end_in_line = (sel_end - line_start).min(line.len());
let sel_start_x = crate::text::measure_text(
&crate::text::AnnotatedString::from(&line[..sel_start_in_line]),
&style,
)
.width
+ padding_left
- pan;
let sel_end_x = crate::text::measure_text(
&crate::text::AnnotatedString::from(&line[..sel_end_in_line]),
&style,
)
.width
+ padding_left
- pan;
let sel_width = sel_end_x - sel_start_x;
if sel_width > 0.0 {
let sel_rect = cranpose_ui_graphics::Rect {
x: sel_start_x,
y: padding_top + line_idx as f32 * line_height,
width: sel_width,
height: line_height,
};
if let Some(clipped) = intersect_rect(sel_rect, clip_bounds) {
primitives.push(DrawPrimitive::Rect {
rect: clipped,
brush: selection_brush.clone(),
});
}
}
}
byte_offset = line_end + 1;
}
}
if let Some(comp_range) = state.composition() {
let comp_start = comp_range.min();
let comp_end = comp_range.max();
if comp_start < comp_end && comp_end <= text.len() {
let lines: Vec<&str> = text.split('\n').collect();
let mut byte_offset: usize = 0;
let underline_brush = cranpose_ui_graphics::Brush::solid(
cranpose_ui_graphics::Color(0.8, 0.8, 0.8, 0.8),
);
let underline_height: f32 = 2.0;
for (line_idx, line) in lines.iter().enumerate() {
let line_start = byte_offset;
let line_end = byte_offset + line.len();
if comp_end > line_start && comp_start < line_end {
let comp_start_in_line = comp_start.saturating_sub(line_start);
let comp_end_in_line = (comp_end - line_start).min(line.len());
let comp_start_in_line = if line.is_char_boundary(comp_start_in_line) {
comp_start_in_line
} else {
0
};
let comp_end_in_line = if line.is_char_boundary(comp_end_in_line) {
comp_end_in_line
} else {
line.len()
};
let comp_start_x = crate::text::measure_text(
&crate::text::AnnotatedString::from(&line[..comp_start_in_line]),
&style,
)
.width
+ padding_left
- pan;
let comp_end_x = crate::text::measure_text(
&crate::text::AnnotatedString::from(&line[..comp_end_in_line]),
&style,
)
.width
+ padding_left
- pan;
let comp_width = comp_end_x - comp_start_x;
if comp_width > 0.0 {
let underline_rect = cranpose_ui_graphics::Rect {
x: comp_start_x,
y: padding_top + (line_idx as f32 + 1.0) * line_height
- underline_height,
width: comp_width,
height: underline_height,
};
if let Some(clipped) = intersect_rect(underline_rect, clip_bounds) {
primitives.push(DrawPrimitive::Rect {
rect: clipped,
brush: underline_brush.clone(),
});
}
}
}
byte_offset = line_end + 1;
}
}
}
if crate::cursor_animation::is_cursor_visible() {
let pos = selection.start.min(text.len());
let text_before = &text[..pos];
let line_index = text_before.matches('\n').count();
let line_start = text_before.rfind('\n').map(|i| i + 1).unwrap_or(0);
let cursor_x = crate::text::measure_text(
&crate::text::AnnotatedString::from(&text_before[line_start..]),
&style,
)
.width
+ padding_left
- pan;
let cursor_y = padding_top + line_index as f32 * line_height;
let cursor_rect = cranpose_ui_graphics::Rect {
x: cursor_x,
y: cursor_y,
width: CURSOR_WIDTH,
height: line_height,
};
if let Some(clipped) = intersect_rect(cursor_rect, clip_bounds) {
primitives.push(DrawPrimitive::Rect {
rect: clipped,
brush: cursor_brush.clone(),
});
}
}
primitives
}))
}
}
impl SemanticsNode for TextFieldModifierNode {
fn merge_semantics(&self, config: &mut SemanticsConfiguration) {
let text = self.state.text();
config.content_description = Some(text);
config.is_editable_text = true;
config.text_selection = Some(self.state.selection());
}
}
impl PointerInputNode for TextFieldModifierNode {
fn on_pointer_event(
&mut self,
_context: &mut dyn ModifierNodeContext,
_event: &PointerEvent,
) -> bool {
false
}
fn hit_test(&self, x: f32, y: f32) -> bool {
let size = self.measured_size.get();
x >= 0.0 && x <= size.width && y >= 0.0 && y <= size.height
}
fn pointer_input_handler(&self) -> Option<Rc<dyn Fn(PointerEvent)>> {
Some(self.cached_handler.clone())
}
}
#[derive(Clone)]
pub struct TextFieldElement {
state: TextFieldState,
style: TextStyle,
cursor_color: Color,
line_limits: TextFieldLineLimits,
}
impl TextFieldElement {
pub fn new(state: TextFieldState, style: TextStyle) -> Self {
Self {
state,
style,
cursor_color: DEFAULT_CURSOR_COLOR,
line_limits: TextFieldLineLimits::default(),
}
}
pub fn with_cursor_color(mut self, color: Color) -> Self {
self.cursor_color = color;
self
}
pub fn with_line_limits(mut self, line_limits: TextFieldLineLimits) -> Self {
self.line_limits = line_limits;
self
}
}
impl std::fmt::Debug for TextFieldElement {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TextFieldElement")
.field("text", &self.state.text())
.field("style", &self.style)
.field("cursor_color", &self.cursor_color)
.finish()
}
}
impl Hash for TextFieldElement {
fn hash<H: Hasher>(&self, state: &mut H) {
std::ptr::hash(std::rc::Rc::as_ptr(&self.state.inner), state);
self.cursor_color.0.to_bits().hash(state);
self.cursor_color.1.to_bits().hash(state);
self.cursor_color.2.to_bits().hash(state);
self.cursor_color.3.to_bits().hash(state);
self.style.render_hash().hash(state);
self.line_limits.hash(state);
}
}
impl PartialEq for TextFieldElement {
fn eq(&self, other: &Self) -> bool {
self.state == other.state
&& self.style == other.style
&& self.cursor_color == other.cursor_color
&& self.line_limits == other.line_limits
}
}
impl Eq for TextFieldElement {}
impl ModifierNodeElement for TextFieldElement {
type Node = TextFieldModifierNode;
fn create(&self) -> Self::Node {
TextFieldModifierNode::new(self.state.clone(), self.style.clone())
.with_cursor_color(self.cursor_color)
.with_line_limits(self.line_limits)
}
fn update(&self, node: &mut Self::Node) {
node.state = self.state.clone();
node.style = self.style.clone();
node.cursor_brush = Brush::solid(self.cursor_color);
node.line_limits = self.line_limits;
node.cached_handler = TextFieldModifierNode::create_handler(
node.state.clone(),
node.refs.clone(),
node.line_limits,
self.style.clone(),
);
node.cached_pan_resolver = TextFieldModifierNode::create_pan_resolver(
node.state.clone(),
node.refs.clone(),
node.line_limits,
self.style.clone(),
);
if node.update_cached_state() {
}
}
fn capabilities(&self) -> NodeCapabilities {
NodeCapabilities::LAYOUT
| NodeCapabilities::DRAW
| NodeCapabilities::SEMANTICS
| NodeCapabilities::POINTER_INPUT
}
fn always_update(&self) -> bool {
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::text::TextStyle;
use cranpose_core::{DefaultScheduler, Runtime};
use std::sync::Arc;
fn with_test_runtime<T>(f: impl FnOnce() -> T) -> T {
let _runtime = Runtime::new(Arc::new(DefaultScheduler));
f()
}
#[test]
fn text_field_node_creation() {
let _app_context = crate::render_state::app_context_test_scope();
with_test_runtime(|| {
let state = TextFieldState::new("Hello");
let node = TextFieldModifierNode::new(state, TextStyle::default());
assert_eq!(node.text(), "Hello");
assert!(!node.is_focused());
});
}
#[test]
fn text_field_node_focus() {
let _app_context = crate::render_state::app_context_test_scope();
with_test_runtime(|| {
let state = TextFieldState::new("Test");
let mut node = TextFieldModifierNode::new(state, TextStyle::default());
assert!(!node.is_focused());
node.set_focused(true);
assert!(node.is_focused());
node.set_focused(false);
assert!(!node.is_focused());
});
}
#[test]
fn text_field_element_creates_node() {
let _app_context = crate::render_state::app_context_test_scope();
with_test_runtime(|| {
let state = TextFieldState::new("Hello World");
let element = TextFieldElement::new(state, TextStyle::default());
let node = element.create();
assert_eq!(node.text(), "Hello World");
});
}
#[test]
fn text_field_element_equality() {
let _app_context = crate::render_state::app_context_test_scope();
with_test_runtime(|| {
let state1 = TextFieldState::new("Hello");
let state2 = TextFieldState::new("Hello");
let elem1 = TextFieldElement::new(state1.clone(), TextStyle::default());
let elem2 = TextFieldElement::new(state1.clone(), TextStyle::default()); let elem3 = TextFieldElement::new(state2, TextStyle::default());
assert_eq!(elem1, elem2, "Same state should be equal");
assert_ne!(elem1, elem3, "Different states should not be equal");
});
}
#[test]
fn text_field_element_update_refreshes_existing_node_style() {
let _app_context = crate::render_state::app_context_test_scope();
with_test_runtime(|| {
let state = TextFieldState::new("themed text");
let dark_style = TextStyle::from_span_style(crate::text::SpanStyle {
color: Some(Color::from_rgba_u8(228, 240, 252, 255)),
..crate::text::SpanStyle::default()
});
let light_style = TextStyle::from_span_style(crate::text::SpanStyle {
color: Some(Color::from_rgba_u8(14, 58, 96, 255)),
..crate::text::SpanStyle::default()
});
let initial = TextFieldElement::new(state.clone(), dark_style);
let updated = TextFieldElement::new(state, light_style.clone());
let mut node = initial.create();
updated.update(&mut node);
assert_eq!(node.text(), "themed text");
assert_eq!(node.style(), &light_style);
});
}
#[test]
fn test_cursor_x_position_calculation() {
let _app_context = crate::render_state::app_context_test_scope();
with_test_runtime(|| {
let style = crate::text::TextStyle::default();
let empty_width =
crate::text::measure_text(&crate::text::AnnotatedString::from(""), &style).width;
assert!(
empty_width.abs() < 0.1,
"Empty text should have 0 width, got {}",
empty_width
);
let hi_width =
crate::text::measure_text(&crate::text::AnnotatedString::from("Hi"), &style).width;
assert!(
hi_width > 0.0,
"Text 'Hi' should have positive width: {}",
hi_width
);
let h_width =
crate::text::measure_text(&crate::text::AnnotatedString::from("H"), &style).width;
assert!(h_width > 0.0, "Text 'H' should have positive width");
assert!(
h_width < hi_width,
"'H' width {} should be less than 'Hi' width {}",
h_width,
hi_width
);
let state = TextFieldState::new("Hi");
assert_eq!(
state.selection().start,
2,
"Cursor should be at position 2 (end of 'Hi')"
);
let text = state.text();
let cursor_pos = state.selection().start;
let text_before_cursor = &text[..cursor_pos.min(text.len())];
assert_eq!(text_before_cursor, "Hi");
let cursor_x = crate::text::measure_text(
&crate::text::AnnotatedString::from(text_before_cursor),
&style,
)
.width;
assert!(
(cursor_x - hi_width).abs() < 0.1,
"Cursor x {} should equal 'Hi' width {}",
cursor_x,
hi_width
);
});
}
#[test]
fn test_focused_node_creates_cursor() {
let _app_context = crate::render_state::app_context_test_scope();
with_test_runtime(|| {
let state = TextFieldState::new("Test");
let element = TextFieldElement::new(state.clone(), TextStyle::default());
let node = element.create();
assert!(!node.is_focused());
*node.refs.is_focused.borrow_mut() = true;
assert!(node.is_focused());
assert_eq!(node.text(), "Test");
assert_eq!(node.selection().start, 4);
});
}
}