1use std::{
2 cell::{Cell, RefCell},
3 hash::{Hash, Hasher},
4 rc::Rc,
5};
6
7use cranpose_core::{MutableState, mutableStateOf};
8use cranpose_foundation::{
9 Constraints, DelegatableNode, DrawModifierNode, FocusState, InvalidationKind,
10 LayoutModifierNode, Measurable, ModifierNode, ModifierNodeContext, ModifierNodeElement,
11 NodeCapabilities, NodeState, PointerEvent, PointerEventKind, PointerInputNode,
12 SemanticsConfiguration, SemanticsNode, Size,
13 text::{OutputTransformation, TextFieldLineLimits, TextFieldState, TextRange},
14};
15use cranpose_ui_graphics::{Brush, Color, Point, ProjectiveTransform, WindowCoordinates};
16use cranpose_ui_layout::ceil_to_px;
17
18use crate::text_field_presentation::{FieldPresentation, PresentationCache};
19
20#[derive(Clone, Copy, PartialEq, Debug)]
21pub struct TextFieldHandleMetrics {
22 pub focused: bool,
23 pub direct_manipulation: bool,
24 pub local_to_window: ProjectiveTransform,
26 pub padding_left: f32,
27 pub padding_top: f32,
28 pub scroll_offset: f32,
29 pub line_height: f32,
30 pub glyph_box: (f32, f32),
31 pub wrap_width: Option<f32>,
32}
33
34#[derive(Clone)]
35pub struct TextFieldHandleController {
36 inner: Rc<TextFieldHandleControllerInner>,
37}
38
39impl PartialEq for TextFieldHandleController {
40 fn eq(&self, other: &Self) -> bool {
41 Rc::ptr_eq(&self.inner, &other.inner)
42 }
43}
44
45struct TextFieldHandleControllerInner {
46 metrics: Cell<Option<TextFieldHandleMetrics>>,
47 activation: MutableState<u64>,
48 geometry: MutableState<u64>,
49 gesture_claim: RefCell<Option<Rc<Cell<bool>>>>,
50 press_track: Cell<Option<MutableState<Option<PointerPressTrack>>>>,
51 presentation: RefCell<Option<Rc<PresentationCache>>>,
52}
53
54impl TextFieldHandleController {
55 pub fn new() -> Self {
56 Self {
57 inner: Rc::new(TextFieldHandleControllerInner {
58 metrics: Cell::new(None),
59 activation: mutableStateOf(0u64),
60 geometry: mutableStateOf(0u64),
61 gesture_claim: RefCell::new(None),
62 press_track: Cell::new(None),
63 presentation: RefCell::new(None),
64 }),
65 }
66 }
67
68 pub(crate) fn publish(&self, metrics: TextFieldHandleMetrics) {
69 let previous = self.inner.metrics.replace(Some(metrics));
70 if previous == Some(metrics) {
71 return;
72 }
73 let was_live = previous.map(|metrics| (metrics.focused, metrics.direct_manipulation));
74 if was_live != Some((metrics.focused, metrics.direct_manipulation)) {
75 self.bump(&self.inner.activation);
76 }
77 self.bump(&self.inner.geometry);
78 }
79
80 fn bump(&self, revision: &MutableState<u64>) {
81 revision.update(|value| *value = value.wrapping_add(1));
82 }
83
84 pub fn metrics(&self) -> Option<TextFieldHandleMetrics> {
97 let _ = self.inner.activation.value();
98 self.inner.metrics.get()
99 }
100
101 pub fn live_metrics(&self) -> Option<TextFieldHandleMetrics> {
109 let _ = self.inner.geometry.value();
110 self.inner.metrics.get()
111 }
112
113 pub fn metrics_now(&self) -> Option<TextFieldHandleMetrics> {
119 self.inner.metrics.get()
120 }
121
122 pub(crate) fn adopt_gesture_claim(&self, claim: &Rc<Cell<bool>>) {
123 let mut slot = self.inner.gesture_claim.borrow_mut();
124 let adopted = slot.as_ref().is_some_and(|held| Rc::ptr_eq(held, claim));
125 if !adopted {
126 *slot = Some(Rc::clone(claim));
127 }
128 }
129
130 pub(crate) fn adopt_press_track(&self, press_track: MutableState<Option<PointerPressTrack>>) {
131 if self.inner.press_track.get() != Some(press_track) {
132 self.inner.press_track.set(Some(press_track));
133 self.bump(&self.inner.activation);
134 }
135 }
136
137 pub(crate) fn adopt_presentation(&self, cache: &Rc<PresentationCache>) {
138 let mut slot = self.inner.presentation.borrow_mut();
139 if !slot.as_ref().is_some_and(|held| Rc::ptr_eq(held, cache)) {
140 *slot = Some(Rc::clone(cache));
141 }
142 }
143
144 pub(crate) fn presentation(&self, state: TextFieldState) -> Rc<FieldPresentation> {
147 let cache = self.inner.presentation.borrow().clone();
148 cache.unwrap_or_default().get(state)
149 }
150
151 pub fn press(&self) -> Option<PointerPressTrack> {
152 self.inner.press_track.get().and_then(|state| state.get())
153 }
154
155 pub fn claim_gesture(&self) {
156 if let Some(claim) = self.inner.gesture_claim.borrow().as_ref() {
157 claim.set(true);
158 }
159 }
160
161 pub fn gesture_claimed(&self) -> bool {
162 self.inner
163 .gesture_claim
164 .borrow()
165 .as_ref()
166 .is_some_and(|claim| claim.get())
167 }
168}
169
170impl Default for TextFieldHandleController {
171 fn default() -> Self {
172 Self::new()
173 }
174}
175
176const DEFAULT_CURSOR_COLOR: Color = Color(1.0, 1.0, 1.0, 1.0);
177
178pub(crate) const DEFAULT_SELECTION_COLOR: Color = Color(0.0, 0.5, 1.0, 0.3);
179
180const DEFAULT_LINE_HEIGHT: f32 = 20.0;
181
182const MIN_SIZE_TEXT: &str = "HHHHHHHHHH";
185
186const CURSOR_WIDTH: f32 = 2.0;
187
188pub(crate) fn compute_horizontal_scroll_offset(
189 current_offset: f32,
190 cursor_x: f32,
191 text_width: f32,
192 viewport_width: f32,
193) -> f32 {
194 if viewport_width <= 0.0 {
195 return 0.0;
196 }
197 let max_offset = (text_width + CURSOR_WIDTH - viewport_width).max(0.0);
198 let mut offset = current_offset.clamp(0.0, max_offset);
199 let visible_end = offset + viewport_width - CURSOR_WIDTH;
200 if cursor_x > visible_end {
201 offset = cursor_x - viewport_width + CURSOR_WIDTH;
202 } else if cursor_x < offset {
203 offset = cursor_x;
204 }
205 offset.clamp(0.0, max_offset)
206}
207
208pub(crate) fn intersect_rect(
209 rect: cranpose_ui_graphics::Rect,
210 bounds: cranpose_ui_graphics::Rect,
211) -> Option<cranpose_ui_graphics::Rect> {
212 let x0 = rect.x.max(bounds.x);
213 let y0 = rect.y.max(bounds.y);
214 let x1 = (rect.x + rect.width).min(bounds.x + bounds.width);
215 let y1 = (rect.y + rect.height).min(bounds.y + bounds.height);
216 (x1 > x0 && y1 > y0).then_some(cranpose_ui_graphics::Rect {
217 x: x0,
218 y: y0,
219 width: x1 - x0,
220 height: y1 - y0,
221 })
222}
223
224pub type TextPanResolver = Rc<dyn Fn(f32) -> f32>;
227
228#[derive(Clone)]
229pub(crate) struct TextFieldLayoutHandle {
230 state: TextFieldState,
231 node_id: Rc<Cell<Option<cranpose_core::NodeId>>>,
232 wrap_width: Rc<Cell<Option<f32>>>,
233 presentation: Rc<PresentationCache>,
234}
235
236impl TextFieldLayoutHandle {
237 pub(crate) fn measured_layout(
238 &self,
239 style: &TextStyle,
240 ) -> std::rc::Rc<crate::text::PreparedTextLayout> {
241 crate::text::prepare_text_layout_for_node(
242 self.node_id.get(),
243 &self.presentation.get(self.state).shown,
244 &std::sync::Arc::new(style.clone()),
245 crate::text::TextLayoutOptions::default(),
246 self.wrap_width.get(),
247 )
248 }
249}
250
251pub(crate) fn caret_visual_line_for_offset(
252 text: &str,
253 style: &TextStyle,
254 node_id: Option<cranpose_core::NodeId>,
255 wrap_width: Option<f32>,
256 offset: usize,
257 affinity: crate::text_selection::LineAffinity,
258) -> (usize, usize) {
259 let offset = offset.min(text.len());
260 match wrap_width {
261 Some(width) if width.is_finite() && width > 0.0 => {
262 let annotated = crate::text::AnnotatedString::from(text);
263 let ranges = crate::text::wrapped_line_ranges(
264 node_id,
265 &annotated,
266 style,
267 crate::text::TextLayoutOptions::default(),
268 Some(width),
269 );
270 crate::text_selection::caret_visual_line(&ranges, offset, affinity)
271 }
272 _ => {
273 let before = &text[..offset];
274 let line_index = before.matches('\n').count();
275 let line_start = before.rfind('\n').map_or(0, |i| i + 1);
276 (line_index, line_start)
277 }
278 }
279}
280
281#[expect(clippy::too_many_arguments)]
282pub(crate) fn range_visual_line_rects(
283 text: &str,
284 style: &TextStyle,
285 node_id: Option<cranpose_core::NodeId>,
286 wrap_width: Option<f32>,
287 pan: f32,
288 line_height: f32,
289 start: usize,
290 end: usize,
291) -> Vec<cranpose_ui_graphics::Rect> {
292 if start >= end {
293 return Vec::new();
294 }
295 let annotated = crate::text::AnnotatedString::from(text);
296 let line_ranges = crate::text::wrapped_line_ranges(
297 node_id,
298 &annotated,
299 style,
300 crate::text::TextLayoutOptions::default(),
301 wrap_width,
302 );
303 let mut rects = Vec::new();
304 for (line_idx, line_range) in line_ranges.iter().enumerate() {
305 let line_start = line_range.start;
306 let line_end = line_range.end;
307 if end <= line_start || start >= line_end {
308 continue;
309 }
310 let seg_start = start.max(line_start);
311 let seg_end = end.min(line_end);
312 let x0 = crate::text::measure_text(
313 &crate::text::AnnotatedString::from(&text[line_start..seg_start]),
314 style,
315 )
316 .width
317 - pan;
318 let x1 = crate::text::measure_text(
319 &crate::text::AnnotatedString::from(&text[line_start..seg_end]),
320 style,
321 )
322 .width
323 - pan;
324 let width = x1 - x0;
325 if width > 0.0 {
326 rects.push(cranpose_ui_graphics::Rect {
327 x: x0,
328 y: line_idx as f32 * line_height,
329 width,
330 height: line_height,
331 });
332 }
333 }
334 rects
335}
336
337fn hit_test_offset(
340 state: TextFieldState,
341 refs: &TextFieldRefs,
342 style: &TextStyle,
343 x: f32,
344 y: f32,
345) -> usize {
346 let presentation = refs.presentation.get(state);
347 presentation.to_source(crate::text::offset_for_position_wrapped(
348 presentation.text(),
349 style,
350 refs.node_id.get(),
351 refs.wrap_width.get(),
352 refs.line_height.get(),
353 x,
354 y,
355 ))
356}
357
358fn selection_anchor_at(
359 state: TextFieldState,
360 pos: usize,
361 granularity: crate::text_selection::SelectionGranularity,
362) -> crate::text_selection::SelectionAnchor {
363 state.with_text(|text| crate::text_selection::SelectionAnchor::at(text, pos, granularity))
364}
365
366fn dragged_selection(
367 state: TextFieldState,
368 anchor: crate::text_selection::SelectionAnchor,
369 pos: usize,
370) -> TextRange {
371 state.with_text(|text| anchor.dragged_to(text, pos))
372}
373
374fn build_focus_handler(
375 state: TextFieldState,
376 refs: &TextFieldRefs,
377 line_limits: TextFieldLineLimits,
378 style: &TextStyle,
379) -> Rc<dyn crate::text_field_focus::FocusedTextFieldHandler> {
380 crate::text_field_handler::TextFieldHandler::new(
381 state,
382 refs.node_id.get(),
383 refs.focus_node.get(),
384 line_limits,
385 refs.focus_options.get().show_keyboard_on_focus,
386 crate::text_field_handler::InputRefs {
387 keyboard_options: refs.keyboard_options.clone(),
388 keyboard_action: refs.keyboard_action.clone(),
389 transformation: refs.input_transformation.clone(),
390 secure: refs.is_secure(),
391 },
392 crate::text_field_handler::CaretGeometryRefs {
393 window: refs.window.clone(),
394 content_origin: refs.content_origin.clone(),
395 scroll_offset: refs.scroll_offset.clone(),
396 wrap_width: refs.wrap_width.clone(),
397 presentation: refs.presentation.clone(),
398 style: style.clone(),
399 },
400 )
401}
402
403fn request_pointer_focus(
404 state: TextFieldState,
405 refs: &TextFieldRefs,
406 line_limits: TextFieldLineLimits,
407 style: &TextStyle,
408 modal_depth: usize,
409) {
410 if modal_depth < crate::modal::current_modal_depth() {
411 return;
412 }
413 let routed = refs
414 .focus_node
415 .get()
416 .is_some_and(crate::focus_dispatch::request_focus_in_context);
417 if !routed {
418 crate::text_field_focus::request_focus(
419 refs.is_focused.clone(),
420 build_focus_handler(state, refs, line_limits, style),
421 modal_depth,
422 );
423 }
424 if !refs.focus_options.get().show_keyboard_on_focus && *refs.is_focused.borrow() {
425 crate::text_input_session::notify_text_input_focus_gained();
426 }
427}
428
429pub(crate) struct TextFieldFocusBridge {
430 state: TextFieldState,
431 refs: TextFieldRefs,
432 style: TextStyle,
433 line_limits: TextFieldLineLimits,
434}
435
436impl TextFieldFocusBridge {
437 pub(crate) fn handle(
439 state: TextFieldState,
440 refs: TextFieldRefs,
441 style: TextStyle,
442 line_limits: TextFieldLineLimits,
443 ) -> Rc<dyn crate::focus_dispatch::FocusTargetHandle> {
444 Rc::new(Self {
445 state,
446 refs,
447 style,
448 line_limits,
449 })
450 }
451}
452
453impl crate::focus_dispatch::FocusTargetHandle for TextFieldFocusBridge {
454 fn set_focus_state(&self, state: FocusState) {
455 if state.is_focused() {
456 crate::text_field_focus::request_focus(
457 self.refs.is_focused.clone(),
458 build_focus_handler(self.state, &self.refs, self.line_limits, &self.style),
459 self.refs.focus_options.get().modal_depth,
460 );
461 } else if crate::text_field_focus::focused_field_node() == self.refs.node_id.get() {
462 crate::text_field_focus::clear_focus();
463 }
464 }
465}
466
467#[derive(Clone, Copy)]
468struct TextFieldFocusOptions {
469 modal_depth: usize,
470 show_keyboard_on_focus: bool,
471 secure: bool,
473}
474
475#[derive(Clone)]
476pub(crate) struct TextFieldRefs {
477 pub is_focused: Rc<RefCell<bool>>,
478 pub content_origin: Rc<RefCell<crate::modifier::CoordinatorRect>>,
481 pub drag_anchor: Rc<Cell<Option<crate::text_selection::SelectionAnchor>>>,
482 pub last_click_time: Rc<Cell<Option<web_time::Instant>>>,
483 pub last_click_pos: Rc<Cell<Option<(f32, f32)>>>,
484 pub click_count: Rc<Cell<u8>>,
485 pub node_id: Rc<Cell<Option<cranpose_core::NodeId>>>,
486 pub focus_node: Rc<Cell<Option<cranpose_core::NodeId>>>,
489 pub scroll_offset: Rc<Cell<f32>>,
490 pub direct_manipulation: Rc<Cell<bool>>,
491 pub window: Rc<Cell<WindowCoordinates>>,
493 pub line_height: Rc<Cell<f32>>,
494 pub wrap_width: Rc<Cell<Option<f32>>>,
495 pub press_track: MutableState<Option<PointerPressTrack>>,
496 pub gesture_claimed: Rc<Cell<bool>>,
497 focus_options: Rc<Cell<TextFieldFocusOptions>>,
498 pub keyboard_options: Rc<Cell<crate::KeyboardOptions>>,
501 pub keyboard_action: Rc<RefCell<Option<crate::KeyboardActionHandler>>>,
502 pub input_transformation: Rc<RefCell<Option<cranpose_foundation::text::InputTransformation>>>,
503 pub(crate) presentation: Rc<PresentationCache>,
506}
507
508#[derive(Clone, Copy, Debug, PartialEq)]
509pub struct PointerPressTrack {
510 pub start: Point,
511 pub position: Point,
512}
513
514impl TextFieldRefs {
515 pub fn new() -> Self {
516 Self {
517 is_focused: Rc::new(RefCell::new(false)),
518 content_origin: Rc::default(),
519 drag_anchor: Rc::new(Cell::new(None)),
520 last_click_time: Rc::new(Cell::new(None::<web_time::Instant>)),
521 last_click_pos: Rc::new(Cell::new(None::<(f32, f32)>)),
522 click_count: Rc::new(Cell::new(0_u8)),
523 node_id: Rc::new(Cell::new(None::<cranpose_core::NodeId>)),
524 focus_node: Rc::new(Cell::new(None::<cranpose_core::NodeId>)),
525 scroll_offset: Rc::new(Cell::new(0.0_f32)),
526 direct_manipulation: Rc::new(Cell::new(false)),
527 window: Rc::new(Cell::new(WindowCoordinates::default())),
528 line_height: Rc::new(Cell::new(DEFAULT_LINE_HEIGHT)),
529 wrap_width: Rc::new(Cell::new(None::<f32>)),
530 press_track: mutableStateOf(None::<PointerPressTrack>),
531 gesture_claimed: Rc::new(Cell::new(false)),
532 focus_options: Rc::new(Cell::new(TextFieldFocusOptions {
533 modal_depth: 0,
534 show_keyboard_on_focus: true,
535 secure: false,
536 })),
537 keyboard_options: Rc::default(),
538 keyboard_action: Rc::default(),
539 input_transformation: Rc::default(),
540 presentation: Rc::default(),
541 }
542 }
543
544 pub(crate) fn key(&self) -> u64 {
547 Rc::as_ptr(&self.is_focused) as usize as u64
548 }
549
550 pub(crate) fn is_secure(&self) -> bool {
552 self.focus_options.get().secure
553 }
554}
555
556impl PartialEq for TextFieldRefs {
557 fn eq(&self, other: &Self) -> bool {
558 Rc::ptr_eq(&self.is_focused, &other.is_focused)
559 }
560}
561
562use crate::text::TextStyle;
563
564pub struct TextFieldModifierNode {
565 state: TextFieldState,
566 refs: TextFieldRefs,
567 style: TextStyle,
568 cursor_brush: Brush,
569 selection_brush: Brush,
570 line_limits: TextFieldLineLimits,
571 cached_revision: u64,
572 cached_selection: TextRange,
573 node_state: NodeState,
574 measured_size: Rc<Cell<Size>>,
575 min_size: Cell<Option<(f32, Size)>>,
577 measured_line_height: Rc<Cell<f32>>,
578 measured_wrap_width: Rc<Cell<Option<f32>>>,
579 cached_handler: Rc<dyn Fn(PointerEvent)>,
580 cached_pan_resolver: TextPanResolver,
581 handle_controller: Option<TextFieldHandleController>,
582 modal_depth: usize,
583 focus_bridge: Option<Rc<dyn crate::focus_dispatch::FocusTargetHandle>>,
584 decorated: bool,
587}
588
589impl std::fmt::Debug for TextFieldModifierNode {
590 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
591 f.debug_struct("TextFieldModifierNode")
592 .field("text", &debug_text(self.state, self.refs.is_secure()))
593 .field("style", &self.style)
594 .field("is_focused", &*self.refs.is_focused.borrow())
595 .finish()
596 }
597}
598
599impl TextFieldModifierNode {
600 pub fn new(state: TextFieldState, style: TextStyle) -> Self {
602 Self::with_refs(state, style, TextFieldRefs::new(), false)
603 }
604
605 fn with_refs(
606 state: TextFieldState,
607 style: TextStyle,
608 refs: TextFieldRefs,
609 decorated: bool,
610 ) -> Self {
611 let refs_line_height = refs.line_height.clone();
612 let refs_wrap_width = refs.wrap_width.clone();
613 let line_limits = TextFieldLineLimits::default();
614 let cached_handler =
615 Self::create_handler(state, refs.clone(), line_limits, style.clone(), 0);
616 let cached_pan_resolver =
617 Self::create_pan_resolver(state, refs.clone(), line_limits, style.clone());
618
619 Self {
620 state,
621 refs,
622 style,
623 cursor_brush: Brush::solid(DEFAULT_CURSOR_COLOR),
624 selection_brush: Brush::solid(DEFAULT_SELECTION_COLOR),
625 line_limits,
626 cached_revision: state.text_revision(),
627 cached_selection: state.selection(),
628 node_state: NodeState::new(),
629 measured_size: Rc::new(Cell::new(Size {
630 width: 0.0,
631 height: 0.0,
632 })),
633 min_size: Cell::new(None),
634 measured_line_height: refs_line_height,
635 measured_wrap_width: refs_wrap_width,
636 cached_handler,
637 cached_pan_resolver,
638 handle_controller: None,
639 modal_depth: 0,
640 focus_bridge: None,
641 decorated,
642 }
643 }
644
645 pub fn with_line_limits(mut self, line_limits: TextFieldLineLimits) -> Self {
647 self.line_limits = line_limits;
648 self.rebuild_cached_closures();
649 self
650 }
651
652 fn rebuild_cached_closures(&mut self) {
653 self.cached_handler = Self::create_handler(
654 self.state,
655 self.refs.clone(),
656 self.line_limits,
657 self.style.clone(),
658 self.modal_depth,
659 );
660 self.cached_pan_resolver = Self::create_pan_resolver(
661 self.state,
662 self.refs.clone(),
663 self.line_limits,
664 self.style.clone(),
665 );
666 }
667
668 pub fn with_handle_controller(mut self, controller: TextFieldHandleController) -> Self {
670 self.handle_controller = Some(controller);
671 self
672 }
673
674 fn create_pan_resolver(
675 state: TextFieldState,
676 refs: TextFieldRefs,
677 line_limits: TextFieldLineLimits,
678 style: TextStyle,
679 ) -> TextPanResolver {
680 Rc::new(move |viewport_width: f32| {
681 if !line_limits.is_single_line() {
682 refs.scroll_offset.set(0.0);
683 return 0.0;
684 }
685 let presentation = refs.presentation.get(state);
686 let pos = presentation.to_shown(state.selection().start);
687 let text_width = crate::text::measure_text(&presentation.shown, &style).width;
688 let cursor_x = crate::text::measure_text(
689 &crate::text::AnnotatedString::from(&presentation.text()[..pos]),
690 &style,
691 )
692 .width;
693 let offset = compute_horizontal_scroll_offset(
694 refs.scroll_offset.get(),
695 cursor_x,
696 text_width,
697 viewport_width,
698 );
699 refs.scroll_offset.set(offset);
700 offset
701 })
702 }
703
704 pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
709 self.line_limits
710 .is_single_line()
711 .then(|| self.cached_pan_resolver.clone())
712 }
713
714 pub fn scroll_offset(&self) -> f32 {
716 self.refs.scroll_offset.get()
717 }
718
719 pub fn line_limits(&self) -> TextFieldLineLimits {
721 self.line_limits
722 }
723
724 pub(crate) fn create_handler(
725 state: TextFieldState,
726 refs: TextFieldRefs,
727 line_limits: TextFieldLineLimits,
728 style: TextStyle,
729 modal_depth: usize,
730 ) -> Rc<dyn Fn(PointerEvent)> {
731 use crate::text_selection::{
732 MULTI_TAP_SLOP_PX, MULTI_TAP_TIMEOUT_MS, SelectionGranularity, classify_tap_count,
733 resolve_selection_tap_count, tap_selection_granularity,
734 };
735
736 Rc::new(move |event: PointerEvent| {
737 let content = refs.content_origin.borrow().origin();
738 let click_x = (event.position.x - content.x + refs.scroll_offset.get()).max(0.0);
739 let click_y = (event.position.y - content.y).max(0.0);
740
741 match event.kind {
742 PointerEventKind::Down => {
743 refs.direct_manipulation.set(true);
744 refs.press_track.set(Some(PointerPressTrack {
745 start: event.global_position,
746 position: event.global_position,
747 }));
748 refs.gesture_claimed.set(false);
749
750 request_pointer_focus(state, &refs, line_limits, &style, modal_depth);
751
752 let now = web_time::Instant::now();
753 let pos = hit_test_offset(state, &refs, &style, click_x, click_y);
754
755 let previous = refs.last_click_pos.get().and_then(|(px, py)| {
756 let count = refs.click_count.get();
757 (count > 0).then_some((count, px, py))
758 });
759 let elapsed_ms = refs
760 .last_click_time
761 .get()
762 .map_or(u128::MAX, |last| now.duration_since(last).as_millis());
763 let tap_count = classify_tap_count(
764 previous,
765 elapsed_ms,
766 event.position.x,
767 event.position.y,
768 MULTI_TAP_TIMEOUT_MS,
769 MULTI_TAP_SLOP_PX,
770 );
771
772 let selection = state.selection();
773 let tap_in_selection =
774 !selection.collapsed() && pos >= selection.min() && pos <= selection.max();
775 let repeat_in_place = refs.last_click_pos.get().is_some_and(|(px, py)| {
776 let dx = event.position.x - px;
777 let dy = event.position.y - py;
778 dx * dx + dy * dy <= MULTI_TAP_SLOP_PX * MULTI_TAP_SLOP_PX
779 });
780 let effective_count = resolve_selection_tap_count(
781 tap_count,
782 refs.click_count.get(),
783 tap_in_selection,
784 repeat_in_place,
785 );
786
787 let granularity = tap_selection_granularity(effective_count);
788 let anchor = selection_anchor_at(state, pos, granularity);
789 refs.drag_anchor.set(Some(anchor));
790 state.edit(|buffer| match granularity {
791 SelectionGranularity::Caret => buffer.place_cursor_before_char(pos),
792 _ => buffer.select(TextRange::new(anchor.start, anchor.end)),
793 });
794
795 refs.click_count.set(effective_count);
796 refs.last_click_time.set(Some(now));
797 refs.last_click_pos
798 .set(Some((event.position.x, event.position.y)));
799 event.consume();
800 }
801 PointerEventKind::Move => {
802 if let Some(mut track) = refs.press_track.get() {
803 track.position = event.global_position;
804 refs.press_track.set(Some(track));
805 if let Some(node_id) = refs.node_id.get() {
806 crate::schedule_draw_repass(node_id);
807 }
808 crate::request_render_invalidation();
809 }
810 if refs.gesture_claimed.get() {
811 event.consume();
812 return;
813 }
814 if let Some(anchor) = refs.drag_anchor.get()
815 && *refs.is_focused.borrow()
816 {
817 let current_pos = hit_test_offset(state, &refs, &style, click_x, click_y);
818 state.set_selection(dragged_selection(state, anchor, current_pos));
819
820 crate::request_render_invalidation();
821
822 event.consume();
823 }
824 }
825 PointerEventKind::Up => {
826 refs.drag_anchor.set(None);
827 refs.press_track.set(None);
828 refs.gesture_claimed.set(false);
829 if let Some(node_id) = refs.node_id.get() {
830 crate::schedule_draw_repass(node_id);
831 }
832 crate::request_render_invalidation();
833 }
834 PointerEventKind::Cancel => {
835 refs.press_track.set(None);
836 refs.gesture_claimed.set(false);
837 if let Some(node_id) = refs.node_id.get() {
838 crate::schedule_draw_repass(node_id);
839 }
840 crate::request_render_invalidation();
841 }
842 _ => {}
843 }
844 })
845 }
846
847 pub fn with_cursor_color(mut self, color: Color) -> Self {
852 self.cursor_brush = Brush::solid(color);
853 self.selection_brush = Brush::solid(
854 color.with_alpha(crate::widgets::basic_text_field::SELECTION_HIGHLIGHT_ALPHA),
855 );
856 self
857 }
858
859 pub fn set_focused(&mut self, focused: bool) {
861 let current = *self.refs.is_focused.borrow();
862 if current != focused {
863 *self.refs.is_focused.borrow_mut() = focused;
864 if !focused {
865 self.refs.direct_manipulation.set(false);
866 self.refs.press_track.set(None);
867 self.refs.gesture_claimed.set(false);
868 }
869 }
870 }
871
872 pub fn is_focused(&self) -> bool {
874 *self.refs.is_focused.borrow()
875 }
876
877 pub(crate) fn window_sink(&self) -> Rc<Cell<WindowCoordinates>> {
878 self.refs.window.clone()
879 }
880
881 pub(crate) fn layout_handle(&self) -> TextFieldLayoutHandle {
882 TextFieldLayoutHandle {
883 state: self.state,
884 node_id: self.refs.node_id.clone(),
885 wrap_width: self.measured_wrap_width.clone(),
886 presentation: self.refs.presentation.clone(),
887 }
888 }
889
890 pub fn text(&self) -> String {
892 self.state.text()
893 }
894
895 pub(crate) fn shown_text(&self) -> Rc<crate::text::AnnotatedString> {
897 Rc::clone(&self.refs.presentation.get(self.state).shown)
898 }
899
900 pub fn style(&self) -> &TextStyle {
901 &self.style
902 }
903
904 pub fn selection(&self) -> TextRange {
906 self.state.selection()
907 }
908
909 pub fn cursor_brush(&self) -> Brush {
911 self.cursor_brush.clone()
912 }
913
914 pub fn selection_brush(&self) -> Brush {
916 self.selection_brush.clone()
917 }
918
919 pub(crate) fn set_content_origin(&self, origin: crate::modifier::CoordinatorRect) {
922 *self.refs.content_origin.borrow_mut() = origin;
923 }
924
925 fn wrap_width(&self, available_width: f32) -> Option<f32> {
926 (!self.line_limits.is_single_line() && available_width.is_finite() && available_width > 0.0)
927 .then_some(available_width)
928 }
929
930 fn measure_text_content(&self, wrap_width: Option<f32>) -> crate::text::TextMetrics {
931 let presentation = self.refs.presentation.get(self.state);
932 let node_id = self.refs.node_id.get();
933 let annotated = &*presentation.shown;
934 let metrics = match wrap_width {
935 Some(max_width) => crate::text::measure_text_with_options_for_node(
936 node_id,
937 annotated,
938 &self.style,
939 crate::text::TextLayoutOptions::default(),
940 Some(max_width),
941 ),
942 None => crate::text::measure_text_for_node(node_id, annotated, &self.style),
943 };
944 self.measured_line_height.set(metrics.line_height);
945 metrics
946 }
947
948 fn text_size(&self, wrap_width: Option<f32>, density: f32) -> (Size, crate::text::TextMetrics) {
951 let metrics = self.measure_text_content(wrap_width);
952 (
953 Size {
954 width: ceil_to_px(metrics.width, density),
955 height: ceil_to_px(metrics.height, density),
956 },
957 metrics,
958 )
959 }
960
961 fn min_size(&self, density: f32) -> Size {
965 if let Some((taken_at, size)) = self.min_size.get()
966 && taken_at == density
967 {
968 return size;
969 }
970 let metrics = crate::text::measure_text(
971 &crate::text::AnnotatedString::from(MIN_SIZE_TEXT),
972 &self.style,
973 );
974 let size = Size {
975 width: ceil_to_px(metrics.width, density),
976 height: ceil_to_px(metrics.height, density),
977 };
978 self.min_size.set(Some((density, size)));
979 size
980 }
981
982 fn update_cached_state(&mut self) -> bool {
983 let revision = self.state.text_revision();
984 let selection = self.state.selection();
985 let changed = revision != self.cached_revision || selection != self.cached_selection;
986 self.cached_revision = revision;
987 self.cached_selection = selection;
988 changed
989 }
990}
991
992impl DelegatableNode for TextFieldModifierNode {
993 fn node_state(&self) -> &NodeState {
994 &self.node_state
995 }
996}
997
998impl ModifierNode for TextFieldModifierNode {
999 fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
1000 self.refs.node_id.set(context.node_id());
1001
1002 context.invalidate(InvalidationKind::Layout);
1003 context.invalidate(InvalidationKind::Draw);
1004 if self.decorated {
1005 return;
1006 }
1007 context.invalidate(InvalidationKind::Semantics);
1008 self.refs.focus_node.set(context.node_id());
1009
1010 if let Some(node_id) = context.node_id() {
1011 let bridge = TextFieldFocusBridge::handle(
1012 self.state,
1013 self.refs.clone(),
1014 self.style.clone(),
1015 self.line_limits,
1016 );
1017 self.focus_bridge = Some(Rc::clone(&bridge));
1018 crate::focus_dispatch::register_focus_target(node_id, bridge);
1019 }
1020 }
1021
1022 fn on_detach(&mut self) {
1023 if let (Some(node_id), Some(bridge)) = (self.refs.node_id.get(), self.focus_bridge.take()) {
1024 crate::focus_dispatch::unregister_focus_target(node_id, &bridge);
1025 }
1026 }
1027
1028 fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
1029 Some(self)
1030 }
1031
1032 fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
1033 Some(self)
1034 }
1035
1036 fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
1037 Some(self)
1038 }
1039
1040 fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
1041 Some(self)
1042 }
1043
1044 cranpose_foundation::impl_semantics_node!();
1045
1046 fn as_pointer_input_node(&self) -> Option<&dyn PointerInputNode> {
1047 (!self.decorated).then_some(self)
1048 }
1049
1050 fn as_pointer_input_node_mut(&mut self) -> Option<&mut dyn PointerInputNode> {
1051 if self.decorated { None } else { Some(self) }
1052 }
1053}
1054
1055impl LayoutModifierNode for TextFieldModifierNode {
1056 fn measure(
1057 &self,
1058 context: &mut dyn ModifierNodeContext,
1059 _measurable: &dyn Measurable,
1060 constraints: Constraints,
1061 ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
1062 let density = context.density();
1063 let wrap_width = self.wrap_width(constraints.max_width);
1064 self.measured_wrap_width.set(wrap_width);
1065 let (text, metrics) = self.text_size(wrap_width, density);
1066 let min = self.min_size(density);
1067 let fit = |length: f32, min: f32, low: f32, high: f32| {
1069 length.max(min.max(low).min(high)).min(high)
1070 };
1071 let size = Size {
1072 width: fit(
1073 text.width,
1074 min.width,
1075 constraints.min_width,
1076 constraints.max_width,
1077 ),
1078 height: fit(
1079 text.height,
1080 min.height,
1081 constraints.min_height,
1082 constraints.max_height,
1083 ),
1084 };
1085 self.measured_size.set(size);
1086
1087 let _ = (self.cached_pan_resolver)(size.width);
1088
1089 let first = crate::text::measure::text_line_box(&self.style)
1090 .map(crate::text::LineBox::first_baseline)
1091 .or_else(|| crate::text::measure::first_baseline(&self.style));
1092 let lines = cranpose_ui_layout::AlignmentLines::new(
1093 first,
1094 first.map(|baseline| {
1095 baseline + metrics.line_count.saturating_sub(1) as f32 * metrics.line_height
1096 }),
1097 );
1098 cranpose_ui_layout::LayoutModifierMeasureResult::with_size(size).with_alignment_lines(lines)
1099 }
1100
1101 fn min_intrinsic_width(&self, _measurable: &dyn Measurable, _height: f32, density: f32) -> f32 {
1104 self.text_size(None, density).0.width
1105 }
1106
1107 fn max_intrinsic_width(&self, _measurable: &dyn Measurable, _height: f32, density: f32) -> f32 {
1108 self.text_size(None, density).0.width
1109 }
1110
1111 fn min_intrinsic_height(&self, _measurable: &dyn Measurable, width: f32, density: f32) -> f32 {
1112 self.intrinsic_height(width, density)
1113 }
1114
1115 fn max_intrinsic_height(&self, _measurable: &dyn Measurable, width: f32, density: f32) -> f32 {
1116 self.intrinsic_height(width, density)
1117 }
1118}
1119
1120impl TextFieldModifierNode {
1121 fn intrinsic_height(&self, width: f32, density: f32) -> f32 {
1122 self.text_size(self.wrap_width(width), density)
1123 .0
1124 .height
1125 .max(self.min_size(density).height)
1126 }
1127}
1128
1129fn content_viewport(
1133 measured: cranpose_ui_graphics::Size,
1134 size: cranpose_foundation::Size,
1135) -> (f32, f32) {
1136 let width = if measured.width > 0.0 {
1137 measured.width
1138 } else {
1139 size.width
1140 };
1141 let height = if measured.height > 0.0 {
1142 measured.height
1143 } else {
1144 size.height
1145 };
1146 (width, height)
1147}
1148
1149impl DrawModifierNode for TextFieldModifierNode {
1150 fn create_draw_closure(
1151 &self,
1152 ) -> Option<Rc<dyn Fn(&mut cranpose_ui_graphics::DrawScopeDefault)>> {
1153 use cranpose_ui_graphics::{DrawPrimitive, DrawScope as _};
1154
1155 let is_focused = self.refs.is_focused.clone();
1156 let state = self.state;
1157 let content_origin = self.refs.content_origin.clone();
1158 let cursor_brush = self.cursor_brush.clone();
1159 let style = self.style.clone();
1160 let cached_line_height = self.measured_line_height.clone();
1161 let measured_size = self.measured_size.clone();
1162 let measured_wrap_width = self.measured_wrap_width.clone();
1163 let node_id = self.refs.node_id.clone();
1164 let pan_resolver = self.cached_pan_resolver.clone();
1165 let handle_controller = self.handle_controller.clone();
1166 let window = self.refs.window.clone();
1167 let direct_manipulation = self.refs.direct_manipulation.clone();
1168 let press_track = self.refs.press_track;
1169 let gesture_claimed = self.refs.gesture_claimed.clone();
1170 let presentation_cache = self.refs.presentation.clone();
1171
1172 Some(Rc::new(move |scope| {
1173 let size = scope.size();
1174 if !*is_focused.borrow() {
1175 if let Some(controller) = &handle_controller {
1176 controller.publish(TextFieldHandleMetrics {
1177 focused: false,
1178 direct_manipulation: false,
1179 local_to_window: window.get().local_to_window,
1180 padding_left: 0.0,
1181 padding_top: 0.0,
1182 scroll_offset: 0.0,
1183 line_height: cached_line_height.get(),
1184 glyph_box: crate::text::glyph_line_box(&style, cached_line_height.get()),
1185 wrap_width: measured_wrap_width.get(),
1186 });
1187 }
1188 return;
1189 }
1190
1191 let mut primitives = Vec::new();
1192
1193 let presentation = presentation_cache.get(state);
1194 let text = presentation.text();
1195 let selection = state.selection();
1196 let line_height = cached_line_height.get();
1197
1198 let (viewport_width, viewport_height) = content_viewport(measured_size.get(), size);
1199 let pan = pan_resolver(viewport_width);
1200
1201 if let Some(controller) = &handle_controller {
1202 controller.adopt_gesture_claim(&gesture_claimed);
1203 controller.adopt_press_track(press_track);
1204 controller.publish(TextFieldHandleMetrics {
1205 focused: true,
1206 direct_manipulation: direct_manipulation.get(),
1207 local_to_window: window.get().local_to_window,
1208 padding_left: content_origin.borrow().origin().x,
1209 padding_top: content_origin.borrow().origin().y,
1210 scroll_offset: pan,
1211 line_height,
1212 glyph_box: crate::text::glyph_line_box(&style, line_height),
1213 wrap_width: measured_wrap_width.get(),
1214 });
1215 }
1216 let clip_bounds = cranpose_ui_graphics::Rect {
1217 x: 0.0,
1218 y: 0.0,
1219 width: viewport_width,
1220 height: viewport_height,
1221 };
1222
1223 if let Some(comp_range) = state.composition() {
1224 let (comp_start, comp_end) = presentation.range_to_shown(comp_range);
1225
1226 if comp_start < comp_end && comp_end <= text.len() {
1227 let underline_brush = cranpose_ui_graphics::Brush::solid(
1228 cranpose_ui_graphics::Color(0.8, 0.8, 0.8, 0.8),
1229 );
1230 let underline_height: f32 = 2.0;
1231
1232 for line_rect in range_visual_line_rects(
1233 text,
1234 &style,
1235 node_id.get(),
1236 measured_wrap_width.get(),
1237 pan,
1238 line_height,
1239 comp_start,
1240 comp_end,
1241 ) {
1242 let underline_rect = cranpose_ui_graphics::Rect {
1243 x: line_rect.x,
1244 y: line_rect.y + line_height - underline_height,
1245 width: line_rect.width,
1246 height: underline_height,
1247 };
1248 if let Some(clipped) = intersect_rect(underline_rect, clip_bounds) {
1249 primitives.push(DrawPrimitive::Rect {
1250 rect: clipped,
1251 brush: underline_brush.clone(),
1252 stroke: None,
1253 });
1254 }
1255 }
1256 }
1257 }
1258
1259 if selection.collapsed() && crate::cursor_animation::is_cursor_visible() {
1260 let pos = presentation.to_shown(selection.start);
1261 let (line_index, line_start) = caret_visual_line_for_offset(
1262 text,
1263 &style,
1264 node_id.get(),
1265 measured_wrap_width.get(),
1266 pos,
1267 crate::text_selection::LineAffinity::Upstream,
1268 );
1269 let cursor_x = crate::text::measure_text(
1270 &crate::text::AnnotatedString::from(&text[line_start..pos]),
1271 &style,
1272 )
1273 .width
1274 - pan;
1275 let (box_off, box_h) = crate::text::glyph_line_box(&style, line_height);
1276 let cursor_y = line_index as f32 * line_height + box_off;
1277
1278 let cursor_rect = cranpose_ui_graphics::Rect {
1279 x: cursor_x,
1280 y: cursor_y,
1281 width: CURSOR_WIDTH,
1282 height: box_h,
1283 };
1284
1285 if let Some(clipped) = intersect_rect(cursor_rect, clip_bounds) {
1286 primitives.push(DrawPrimitive::Rect {
1287 rect: clipped,
1288 brush: cursor_brush.clone(),
1289 stroke: None,
1290 });
1291 }
1292 }
1293
1294 scope.push_recorded(primitives);
1295 }))
1296 }
1297
1298 fn create_behind_draw_closure(
1299 &self,
1300 ) -> Option<Rc<dyn Fn(&mut cranpose_ui_graphics::DrawScopeDefault)>> {
1301 use cranpose_ui_graphics::{DrawPrimitive, DrawScope as _};
1302
1303 let is_focused = self.refs.is_focused.clone();
1304 let state = self.state;
1305 let selection_brush = self.selection_brush.clone();
1306 let style = self.style.clone();
1307 let cached_line_height = self.measured_line_height.clone();
1308 let measured_size = self.measured_size.clone();
1309 let measured_wrap_width = self.measured_wrap_width.clone();
1310 let node_id = self.refs.node_id.clone();
1311 let pan_resolver = self.cached_pan_resolver.clone();
1312 let presentation_cache = self.refs.presentation.clone();
1313
1314 Some(Rc::new(move |scope| {
1315 let size = scope.size();
1316 if !*is_focused.borrow() {
1317 return;
1318 }
1319 let selection = state.selection();
1320 if selection.collapsed() {
1321 return;
1322 }
1323 let presentation = presentation_cache.get(state);
1324 let text = presentation.text();
1325 let (selection_start, selection_end) = presentation.range_to_shown(selection);
1326 let line_height = cached_line_height.get();
1327 let (viewport_width, viewport_height) = content_viewport(measured_size.get(), size);
1328 let pan = pan_resolver(viewport_width);
1329 let clip_bounds = cranpose_ui_graphics::Rect {
1330 x: 0.0,
1331 y: 0.0,
1332 width: viewport_width,
1333 height: viewport_height,
1334 };
1335
1336 let mut primitives = Vec::new();
1337 let (box_off, box_h) = crate::text::glyph_line_box(&style, line_height);
1338 for sel_rect in range_visual_line_rects(
1339 text,
1340 &style,
1341 node_id.get(),
1342 measured_wrap_width.get(),
1343 pan,
1344 line_height,
1345 selection_start,
1346 selection_end,
1347 ) {
1348 let sel_rect = cranpose_ui_graphics::Rect {
1349 y: sel_rect.y + box_off,
1350 height: box_h,
1351 ..sel_rect
1352 };
1353 if let Some(clipped) = intersect_rect(sel_rect, clip_bounds) {
1354 primitives.push(DrawPrimitive::Rect {
1355 rect: clipped,
1356 brush: selection_brush.clone(),
1357 stroke: None,
1358 });
1359 }
1360 }
1361 scope.push_recorded(primitives);
1362 }))
1363 }
1364}
1365
1366impl SemanticsNode for TextFieldModifierNode {
1367 fn merge_semantics(&self, config: &mut SemanticsConfiguration) {
1368 if !self.decorated {
1369 merge_text_field_semantics(self.state, self.line_limits, self.refs.is_secure(), config);
1370 }
1371 }
1372
1373 fn reach(&self) -> cranpose_foundation::SemanticsReach {
1376 cranpose_foundation::SemanticsReach {
1377 merges_live_state: true,
1378 ..cranpose_foundation::SemanticsReach::default()
1379 }
1380 }
1381}
1382
1383fn debug_text(state: TextFieldState, secure: bool) -> String {
1387 if secure {
1388 state.with_text(|text| format!("<{} secret bytes>", text.len()))
1389 } else {
1390 state.text()
1391 }
1392}
1393
1394pub(crate) fn merge_text_field_semantics(
1395 state: TextFieldState,
1396 line_limits: TextFieldLineLimits,
1397 secure: bool,
1398 config: &mut SemanticsConfiguration,
1399) {
1400 if secure {
1401 config.password = true;
1404 config.text = Some(state.with_text(|text| {
1405 unicode_segmentation::UnicodeSegmentation::graphemes(text, true)
1406 .map(|_| '\u{2022}')
1407 .collect()
1408 }));
1409 } else {
1410 let text = state.text();
1411 if config.content_description.is_none() {
1412 config.content_description = Some(text.clone());
1413 }
1414 config.text = Some(text);
1415 }
1416 config.is_editable_text = true;
1417 config.is_clickable = true;
1418 config.multiline = !matches!(line_limits, TextFieldLineLimits::SingleLine);
1419 config.set_text = Some(cranpose_foundation::SemanticsSetText::new(move |text| {
1420 state.set_text(text)
1421 }));
1422 config.set_selection = Some(cranpose_foundation::SemanticsSetSelection::new(
1423 move |anchor, focus| {
1424 let (anchor, focus) = state.with_text(|text| {
1425 (
1426 text.floor_char_boundary(anchor),
1427 text.floor_char_boundary(focus),
1428 )
1429 });
1430 state.set_selection(TextRange::new(anchor, focus));
1431 crate::cursor_animation::reset_cursor_blink();
1432 crate::request_render_invalidation();
1433 true
1434 },
1435 ));
1436 config.text_selection = Some(state.selection());
1437}
1438
1439impl PointerInputNode for TextFieldModifierNode {
1440 fn on_pointer_event(
1441 &mut self,
1442 _context: &mut dyn ModifierNodeContext,
1443 _event: &PointerEvent,
1444 ) -> bool {
1445 false
1446 }
1447
1448 fn hit_test(&self, x: f32, y: f32) -> bool {
1449 let size = self.measured_size.get();
1450 x >= 0.0 && x <= size.width && y >= 0.0 && y <= size.height
1451 }
1452
1453 fn pointer_input_handler(&self) -> Option<Rc<dyn Fn(PointerEvent)>> {
1454 Some(self.cached_handler.clone())
1455 }
1456}
1457
1458#[derive(Clone)]
1465pub struct TextFieldElement {
1466 state: TextFieldState,
1467 style: TextStyle,
1468 cursor_color: Color,
1469 line_limits: TextFieldLineLimits,
1470 show_keyboard_on_focus: bool,
1471 keyboard_options: crate::KeyboardOptions,
1472 keyboard_action: Option<crate::KeyboardActionHandler>,
1475 input_transformation: Option<cranpose_foundation::text::InputTransformation>,
1477 output_transformation: Option<OutputTransformation>,
1479 secure: bool,
1480 handle_controller: Option<TextFieldHandleController>,
1481 modal_depth: usize,
1482 decorator: Option<TextFieldRefs>,
1483}
1484
1485impl TextFieldElement {
1486 pub fn new(state: TextFieldState, style: TextStyle) -> Self {
1488 Self {
1489 state,
1490 style,
1491 cursor_color: DEFAULT_CURSOR_COLOR,
1492 line_limits: TextFieldLineLimits::default(),
1493 show_keyboard_on_focus: true,
1494 keyboard_options: crate::KeyboardOptions::default(),
1495 keyboard_action: None,
1496 input_transformation: None,
1497 output_transformation: None,
1498 secure: false,
1499 handle_controller: None,
1500 modal_depth: 0,
1501 decorator: None,
1502 }
1503 }
1504
1505 pub(crate) fn decorated_by(mut self, refs: TextFieldRefs) -> Self {
1508 self.decorator = Some(refs);
1509 self
1510 }
1511
1512 pub fn with_cursor_color(mut self, color: Color) -> Self {
1514 self.cursor_color = color;
1515 self
1516 }
1517
1518 pub fn with_line_limits(mut self, line_limits: TextFieldLineLimits) -> Self {
1520 self.line_limits = line_limits;
1521 self
1522 }
1523
1524 pub fn with_show_keyboard_on_focus(mut self, show: bool) -> Self {
1527 self.show_keyboard_on_focus = show;
1528 self
1529 }
1530
1531 pub fn with_keyboard(
1534 mut self,
1535 options: crate::KeyboardOptions,
1536 action: Option<crate::KeyboardActionHandler>,
1537 ) -> Self {
1538 self.keyboard_options = options;
1539 self.keyboard_action = action;
1540 self
1541 }
1542
1543 pub fn with_input_transformation(
1545 mut self,
1546 transformation: Option<cranpose_foundation::text::InputTransformation>,
1547 ) -> Self {
1548 self.input_transformation = transformation;
1549 self
1550 }
1551
1552 pub fn with_output_transformation(
1554 mut self,
1555 transformation: Option<OutputTransformation>,
1556 ) -> Self {
1557 self.output_transformation = transformation;
1558 self
1559 }
1560
1561 pub(crate) fn secure(mut self, secure: bool) -> Self {
1564 self.secure = secure;
1565 self
1566 }
1567
1568 pub fn with_handle_controller(mut self, controller: TextFieldHandleController) -> Self {
1570 self.handle_controller = Some(controller);
1571 self
1572 }
1573
1574 pub fn with_modal_depth(mut self, depth: usize) -> Self {
1577 self.modal_depth = depth;
1578 self
1579 }
1580}
1581
1582impl std::fmt::Debug for TextFieldElement {
1583 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1584 f.debug_struct("TextFieldElement")
1585 .field("text", &debug_text(self.state, self.secure))
1586 .field("style", &self.style)
1587 .field("cursor_color", &self.cursor_color)
1588 .finish()
1589 }
1590}
1591
1592impl Hash for TextFieldElement {
1593 fn hash<H: Hasher>(&self, state: &mut H) {
1594 self.state.id().hash(state);
1595 self.cursor_color.0.to_bits().hash(state);
1596 self.cursor_color.1.to_bits().hash(state);
1597 self.cursor_color.2.to_bits().hash(state);
1598 self.cursor_color.3.to_bits().hash(state);
1599 self.style.render_hash().hash(state);
1600 self.line_limits.hash(state);
1601 self.show_keyboard_on_focus.hash(state);
1602 self.keyboard_options.hash(state);
1603 self.secure.hash(state);
1604 self.modal_depth.hash(state);
1605 self.decorator.as_ref().map(TextFieldRefs::key).hash(state);
1606 }
1607}
1608
1609impl PartialEq for TextFieldElement {
1610 fn eq(&self, other: &Self) -> bool {
1611 self.state == other.state
1612 && self.style == other.style
1613 && self.cursor_color == other.cursor_color
1614 && self.line_limits == other.line_limits
1615 && self.show_keyboard_on_focus == other.show_keyboard_on_focus
1616 && self.keyboard_options == other.keyboard_options
1617 && self.output_transformation == other.output_transformation
1618 && self.secure == other.secure
1619 && self.modal_depth == other.modal_depth
1620 && self.decorator == other.decorator
1621 }
1622}
1623
1624impl Eq for TextFieldElement {}
1625
1626impl TextFieldElement {
1627 fn hand_input_options_to(&self, refs: &TextFieldRefs) {
1630 refs.keyboard_options.set(self.keyboard_options);
1631 refs.keyboard_action.replace(self.keyboard_action.clone());
1632 refs.input_transformation
1633 .replace(self.input_transformation.clone());
1634 refs.presentation
1635 .set_transformation(self.output_transformation.clone());
1636 if let Some(controller) = &self.handle_controller {
1637 controller.adopt_presentation(&refs.presentation);
1638 }
1639 }
1640}
1641
1642impl ModifierNodeElement for TextFieldElement {
1643 type Node = TextFieldModifierNode;
1644
1645 fn create(&self) -> Self::Node {
1646 let refs = self.decorator.clone().unwrap_or_else(TextFieldRefs::new);
1647 let decorated = self.decorator.is_some();
1648 let mut node =
1649 TextFieldModifierNode::with_refs(self.state, self.style.clone(), refs, decorated)
1650 .with_cursor_color(self.cursor_color)
1651 .with_line_limits(self.line_limits);
1652 node.modal_depth = self.modal_depth;
1653 node.refs.focus_options.set(TextFieldFocusOptions {
1654 modal_depth: self.modal_depth,
1655 show_keyboard_on_focus: self.show_keyboard_on_focus,
1656 secure: self.secure,
1657 });
1658 self.hand_input_options_to(&node.refs);
1659 if let Some(controller) = self.handle_controller.clone() {
1660 node = node.with_handle_controller(controller);
1661 }
1662 node.rebuild_cached_closures();
1663 node
1664 }
1665
1666 fn update(&self, node: &mut Self::Node) {
1667 node.state = self.state;
1668 if node.style != self.style {
1669 node.min_size.set(None);
1670 node.style = self.style.clone();
1671 }
1672 node.cursor_brush = Brush::solid(self.cursor_color);
1673 node.line_limits = self.line_limits;
1674 node.handle_controller.clone_from(&self.handle_controller);
1675 node.modal_depth = self.modal_depth;
1676 let previous_focus_options = node.refs.focus_options.replace(TextFieldFocusOptions {
1677 modal_depth: self.modal_depth,
1678 show_keyboard_on_focus: self.show_keyboard_on_focus,
1679 secure: self.secure,
1680 });
1681 if self.show_keyboard_on_focus
1682 && !previous_focus_options.show_keyboard_on_focus
1683 && *node.refs.is_focused.borrow()
1684 {
1685 crate::text_input_session::notify_text_input_focus_gained();
1686 }
1687 self.hand_input_options_to(&node.refs);
1688 node.rebuild_cached_closures();
1689
1690 if node.update_cached_state() {}
1691 }
1692
1693 fn key(&self) -> Option<u64> {
1696 self.decorator.as_ref().map(TextFieldRefs::key)
1697 }
1698
1699 fn capabilities(&self) -> NodeCapabilities {
1700 let drawn = NodeCapabilities::LAYOUT | NodeCapabilities::DRAW | NodeCapabilities::SEMANTICS;
1701 if self.decorator.is_some() {
1702 drawn
1703 } else {
1704 drawn | NodeCapabilities::POINTER_INPUT
1705 }
1706 }
1707
1708 fn always_update(&self) -> bool {
1709 true
1710 }
1711}
1712
1713#[cfg(test)]
1714#[path = "tests/text_field_modifier_node_tests.rs"]
1715mod tests;