Skip to main content

cranpose_ui/
text_field_modifier_node.rs

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    /// Maps the field's local coordinates to its window.
25    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    /// The field's current handle metrics, subscribing the caller to whether
85    /// the handles are live -- to [`TextFieldHandleMetrics::focused`] and
86    /// [`TextFieldHandleMetrics::direct_manipulation`], and to nothing else.
87    ///
88    /// The rest of the metrics describe where the field sits, and a field
89    /// moves for reasons that have nothing to do with its handles: a list
90    /// scrolling under it, a bounce settling, a layout shifting by a
91    /// fraction of a pixel. A caller that only wants to know whether to emit
92    /// handles must not be recomposed by any of that, so geometry is not part
93    /// of this subscription. Use [`Self::live_metrics`] once the handles are
94    /// live and their position has to follow the field, and
95    /// [`Self::metrics_now`] outside composition.
96    pub fn metrics(&self) -> Option<TextFieldHandleMetrics> {
97        let _ = self.inner.activation.value();
98        self.inner.metrics.get()
99    }
100
101    /// The field's current handle metrics, subscribing the caller to the
102    /// field's position as well.
103    ///
104    /// For a caller that places something at the caret and has to keep it
105    /// there while the field moves. Reach for it only past a
106    /// [`TextFieldHandleMetrics::focused`] check, because every caller that
107    /// holds this subscription recomposes whenever the field moves at all.
108    pub fn live_metrics(&self) -> Option<TextFieldHandleMetrics> {
109        let _ = self.inner.geometry.value();
110        self.inner.metrics.get()
111    }
112
113    /// The field's current handle metrics, subscribing the caller to nothing.
114    ///
115    /// For gesture callbacks and effects, which run after composition and want
116    /// the position as it is now rather than as it was when their scope last
117    /// composed.
118    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    /// The field's text as shown, from the field's own cache once its node
145    /// exists.
146    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);
177const DEFAULT_SELECTION_COLOR: Color =
178    crate::text_selection_colors::DEFAULT_TEXT_SELECTION_COLORS.background_color;
179
180const DEFAULT_LINE_HEIGHT: f32 = 20.0;
181
182/// What Compose's `textFieldMinSize` lays out to find a field's smallest
183/// box: one line of ten 'H's.
184const 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
224/// Resolver that recomputes (and stores) the horizontal pan offset for a
225/// text field given the current content viewport width in px.
226pub type TextPanResolver = Rc<dyn Fn(f32) -> f32>;
227
228#[derive(Clone)]
229pub(crate) struct TextFieldLayoutHandle {
230    state: TextFieldState,
231    wrap_width: Rc<Cell<Option<f32>>>,
232    presentation: Rc<PresentationCache>,
233}
234
235impl TextFieldLayoutHandle {
236    pub(crate) fn measured_layout(&self, style: &TextStyle) -> Rc<crate::text::PreparedTextLayout> {
237        crate::text::prepare_text_layout(
238            &self.presentation.get(self.state).shown,
239            style,
240            crate::text::TextLayoutOptions::default(),
241            self.wrap_width.get(),
242        )
243    }
244}
245
246pub(crate) fn caret_visual_line_for_offset(
247    text: &str,
248    style: &TextStyle,
249    wrap_width: Option<f32>,
250    offset: usize,
251    affinity: crate::text_selection::LineAffinity,
252) -> (usize, usize) {
253    let offset = offset.min(text.len());
254    match wrap_width {
255        Some(width) if width.is_finite() && width > 0.0 => {
256            let annotated = crate::text::AnnotatedString::from(text);
257            let ranges = crate::text::wrapped_line_ranges(
258                &annotated,
259                style,
260                crate::text::TextLayoutOptions::default(),
261                Some(width),
262            );
263            crate::text_selection::caret_visual_line(&ranges, offset, affinity)
264        }
265        _ => {
266            let before = &text[..offset];
267            let line_index = before.matches('\n').count();
268            let line_start = before.rfind('\n').map_or(0, |i| i + 1);
269            (line_index, line_start)
270        }
271    }
272}
273
274pub(crate) fn range_visual_line_rects(
275    text: &str,
276    style: &TextStyle,
277    wrap_width: Option<f32>,
278    pan: f32,
279    line_height: f32,
280    range: std::ops::Range<usize>,
281) -> Vec<cranpose_ui_graphics::Rect> {
282    let std::ops::Range { start, end } = range;
283    if start >= end {
284        return Vec::new();
285    }
286    let annotated = crate::text::AnnotatedString::from(text);
287    let line_ranges = crate::text::wrapped_line_ranges(
288        &annotated,
289        style,
290        crate::text::TextLayoutOptions::default(),
291        wrap_width,
292    );
293    let mut rects = Vec::new();
294    for (line_idx, line_range) in line_ranges.iter().enumerate() {
295        let line_start = line_range.start;
296        let line_end = line_range.end;
297        if end <= line_start || start >= line_end {
298            continue;
299        }
300        let seg_start = start.max(line_start);
301        let seg_end = end.min(line_end);
302        let x0 = crate::text::measure_text(
303            &crate::text::AnnotatedString::from(&text[line_start..seg_start]),
304            style,
305        )
306        .width
307            - pan;
308        let x1 = crate::text::measure_text(
309            &crate::text::AnnotatedString::from(&text[line_start..seg_end]),
310            style,
311        )
312        .width
313            - pan;
314        let width = x1 - x0;
315        if width > 0.0 {
316            rects.push(cranpose_ui_graphics::Rect {
317                x: x0,
318                y: line_idx as f32 * line_height,
319                width,
320                height: line_height,
321            });
322        }
323    }
324    rects
325}
326
327/// The text offset under a point of the field's content: the hit on the
328/// shown text, mapped back to the text.
329fn hit_test_offset(
330    state: TextFieldState,
331    refs: &TextFieldRefs,
332    style: &TextStyle,
333    x: f32,
334    y: f32,
335) -> usize {
336    let presentation = refs.presentation.get(state);
337    presentation.to_source(crate::text::offset_for_position_wrapped(
338        presentation.text(),
339        style,
340        refs.wrap_width.get(),
341        x,
342        y,
343    ))
344}
345
346fn selection_anchor_at(
347    state: TextFieldState,
348    pos: usize,
349    granularity: crate::text_selection::SelectionGranularity,
350) -> crate::text_selection::SelectionAnchor {
351    state.with_text(|text| crate::text_selection::SelectionAnchor::at(text, pos, granularity))
352}
353
354fn dragged_selection(
355    state: TextFieldState,
356    anchor: crate::text_selection::SelectionAnchor,
357    pos: usize,
358) -> TextRange {
359    state.with_text(|text| anchor.dragged_to(text, pos))
360}
361
362fn build_focus_handler(
363    state: TextFieldState,
364    refs: &TextFieldRefs,
365    line_limits: TextFieldLineLimits,
366    style: &TextStyle,
367) -> Rc<dyn crate::text_field_focus::FocusedTextFieldHandler> {
368    crate::text_field_handler::TextFieldHandler::new(
369        state,
370        refs.node_id.get(),
371        refs.focus_node.get(),
372        line_limits,
373        refs.focus_options.get().show_keyboard_on_focus,
374        crate::text_field_handler::InputRefs {
375            keyboard_options: Rc::clone(&refs.keyboard_options),
376            keyboard_action: Rc::clone(&refs.keyboard_action),
377            transformation: Rc::clone(&refs.input_transformation),
378            secure: refs.is_secure(),
379        },
380        crate::text_field_handler::CaretGeometryRefs {
381            window: Rc::clone(&refs.window),
382            content_origin: Rc::clone(&refs.content_origin),
383            scroll_offset: Rc::clone(&refs.scroll_offset),
384            wrap_width: Rc::clone(&refs.wrap_width),
385            presentation: Rc::clone(&refs.presentation),
386            style: style.clone(),
387        },
388    )
389}
390
391fn request_pointer_focus(
392    state: TextFieldState,
393    refs: &TextFieldRefs,
394    line_limits: TextFieldLineLimits,
395    style: &TextStyle,
396    modal_depth: usize,
397) {
398    if modal_depth < crate::modal::current_modal_depth() {
399        return;
400    }
401    let routed = refs
402        .focus_node
403        .get()
404        .is_some_and(crate::focus_dispatch::request_focus_in_context);
405    if !routed {
406        crate::text_field_focus::request_focus(
407            Rc::clone(&refs.is_focused),
408            build_focus_handler(state, refs, line_limits, style),
409            modal_depth,
410        );
411    }
412    if !refs.focus_options.get().show_keyboard_on_focus && *refs.is_focused.borrow() {
413        crate::text_input_session::notify_text_input_focus_gained();
414    }
415}
416
417pub(crate) struct TextFieldFocusBridge {
418    state: TextFieldState,
419    refs: TextFieldRefs,
420    style: TextStyle,
421    line_limits: TextFieldLineLimits,
422}
423
424impl TextFieldFocusBridge {
425    /// The focus target of the field with these refs.
426    pub(crate) fn handle(
427        state: TextFieldState,
428        refs: TextFieldRefs,
429        style: TextStyle,
430        line_limits: TextFieldLineLimits,
431    ) -> Rc<dyn crate::focus_dispatch::FocusTargetHandle> {
432        Rc::new(Self {
433            state,
434            refs,
435            style,
436            line_limits,
437        })
438    }
439}
440
441impl crate::focus_dispatch::FocusTargetHandle for TextFieldFocusBridge {
442    fn set_focus_state(&self, state: FocusState) {
443        if state.is_focused() {
444            crate::text_field_focus::request_focus(
445                Rc::clone(&self.refs.is_focused),
446                build_focus_handler(self.state, &self.refs, self.line_limits, &self.style),
447                self.refs.focus_options.get().modal_depth,
448            );
449        } else if crate::text_field_focus::focused_field_node() == self.refs.node_id.get() {
450            crate::text_field_focus::clear_focus();
451        }
452    }
453}
454
455#[derive(Clone, Copy)]
456struct TextFieldFocusOptions {
457    modal_depth: usize,
458    show_keyboard_on_focus: bool,
459    /// The field holds a secret: no copy or cut, masked semantics.
460    secure: bool,
461}
462
463#[derive(Clone)]
464pub(crate) struct TextFieldRefs {
465    pub is_focused: Rc<RefCell<bool>>,
466    /// Where the field's content sits in its node: the rect its layout
467    /// placed the field at, after every layout modifier before it.
468    pub content_origin: Rc<RefCell<crate::modifier::CoordinatorRect>>,
469    pub drag_anchor: Rc<Cell<Option<crate::text_selection::SelectionAnchor>>>,
470    pub taps: Rc<crate::tap_counter::TapCounter>,
471    pub node_id: Rc<Cell<Option<cranpose_core::NodeId>>>,
472    /// The node focus and semantics know the field by: the decoration box
473    /// around a decorated field, else the field's own node.
474    pub focus_node: Rc<Cell<Option<cranpose_core::NodeId>>>,
475    pub scroll_offset: Rc<Cell<f32>>,
476    pub direct_manipulation: Rc<Cell<bool>>,
477    /// The field's size and window transform, written by layout.
478    pub window: Rc<Cell<WindowCoordinates>>,
479    pub line_height: Rc<Cell<f32>>,
480    pub wrap_width: Rc<Cell<Option<f32>>>,
481    pub press_track: MutableState<Option<PointerPressTrack>>,
482    pub gesture_claimed: Rc<Cell<bool>>,
483    focus_options: Rc<Cell<TextFieldFocusOptions>>,
484    /// The keyboard the field asks for, read when it gains focus and when
485    /// its action runs.
486    pub keyboard_options: Rc<Cell<crate::KeyboardOptions>>,
487    pub keyboard_action: Rc<RefCell<Option<crate::KeyboardActionHandler>>>,
488    pub input_transformation: Rc<RefCell<Option<cranpose_foundation::text::InputTransformation>>>,
489    /// The field's text as shown, shared by its layout, drawing, pointer
490    /// input, handles and platform caret geometry.
491    pub(crate) presentation: Rc<PresentationCache>,
492}
493
494#[derive(Clone, Copy, Debug, PartialEq)]
495pub struct PointerPressTrack {
496    pub start: Point,
497    pub position: Point,
498}
499
500impl TextFieldRefs {
501    pub(crate) fn new() -> Self {
502        Self {
503            is_focused: Rc::new(RefCell::new(false)),
504            content_origin: Rc::default(),
505            drag_anchor: Rc::new(Cell::new(None)),
506            taps: Rc::default(),
507            node_id: Rc::new(Cell::new(None::<cranpose_core::NodeId>)),
508            focus_node: Rc::new(Cell::new(None::<cranpose_core::NodeId>)),
509            scroll_offset: Rc::new(Cell::new(0.0_f32)),
510            direct_manipulation: Rc::new(Cell::new(false)),
511            window: Rc::new(Cell::new(WindowCoordinates::default())),
512            line_height: Rc::new(Cell::new(DEFAULT_LINE_HEIGHT)),
513            wrap_width: Rc::new(Cell::new(None::<f32>)),
514            press_track: mutableStateOf(None::<PointerPressTrack>),
515            gesture_claimed: Rc::new(Cell::new(false)),
516            focus_options: Rc::new(Cell::new(TextFieldFocusOptions {
517                modal_depth: 0,
518                show_keyboard_on_focus: true,
519                secure: false,
520            })),
521            keyboard_options: Rc::default(),
522            keyboard_action: Rc::default(),
523            input_transformation: Rc::default(),
524            presentation: Rc::default(),
525        }
526    }
527
528    /// Tells these refs from any others, so the nodes sharing them can be
529    /// keyed by them.
530    pub(crate) fn key(&self) -> u64 {
531        Rc::as_ptr(&self.is_focused) as usize as u64
532    }
533
534    /// Whether the field holds a secret.
535    pub(crate) fn is_secure(&self) -> bool {
536        self.focus_options.get().secure
537    }
538}
539
540impl PartialEq for TextFieldRefs {
541    fn eq(&self, other: &Self) -> bool {
542        Rc::ptr_eq(&self.is_focused, &other.is_focused)
543    }
544}
545
546use crate::text::TextStyle;
547
548/// The modifier node behind an editable text field. It measures and draws the text, the cursor and
549/// the selection, and handles pointer input.
550pub struct TextFieldModifierNode {
551    state: TextFieldState,
552    refs: TextFieldRefs,
553    style: TextStyle,
554    cursor_brush: Brush,
555    selection_brush: Brush,
556    line_limits: TextFieldLineLimits,
557    cached_revision: u64,
558    cached_selection: TextRange,
559    node_state: NodeState,
560    measured_size: Rc<Cell<Size>>,
561    /// [`Self::min_size`] and the density it was taken at.
562    min_size: Cell<Option<(f32, Size)>>,
563    measured_line_height: Rc<Cell<f32>>,
564    measured_wrap_width: Rc<Cell<Option<f32>>>,
565    cached_handler: Rc<dyn Fn(PointerEvent)>,
566    cached_pan_resolver: TextPanResolver,
567    handle_controller: Option<TextFieldHandleController>,
568    modal_depth: usize,
569    focus_bridge: Option<Rc<dyn crate::focus_dispatch::FocusTargetHandle>>,
570    /// A decoration box around the field takes its input, focus and
571    /// semantics, sharing its refs; the field only lays out and draws.
572    decorated: bool,
573}
574
575impl std::fmt::Debug for TextFieldModifierNode {
576    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
577        f.debug_struct("TextFieldModifierNode")
578            .field("text", &debug_text(self.state, self.refs.is_secure()))
579            .field("style", &self.style)
580            .field("is_focused", &*self.refs.is_focused.borrow())
581            .finish()
582    }
583}
584
585impl TextFieldModifierNode {
586    /// Creates a new text field modifier node.
587    pub fn new(state: TextFieldState, style: TextStyle) -> Self {
588        Self::with_refs(state, style, TextFieldRefs::new(), false)
589    }
590
591    fn with_refs(
592        state: TextFieldState,
593        style: TextStyle,
594        refs: TextFieldRefs,
595        decorated: bool,
596    ) -> Self {
597        let refs_line_height = Rc::clone(&refs.line_height);
598        let refs_wrap_width = Rc::clone(&refs.wrap_width);
599        let line_limits = TextFieldLineLimits::default();
600        let cached_handler =
601            Self::create_handler(state, refs.clone(), line_limits, style.clone(), 0);
602        let cached_pan_resolver =
603            Self::create_pan_resolver(state, refs.clone(), line_limits, style.clone());
604
605        Self {
606            state,
607            refs,
608            style,
609            cursor_brush: Brush::solid(DEFAULT_CURSOR_COLOR),
610            selection_brush: Brush::solid(DEFAULT_SELECTION_COLOR),
611            line_limits,
612            cached_revision: state.text_revision(),
613            cached_selection: state.selection(),
614            node_state: NodeState::new(),
615            measured_size: Rc::new(Cell::new(Size {
616                width: 0.0,
617                height: 0.0,
618            })),
619            min_size: Cell::new(None),
620            measured_line_height: refs_line_height,
621            measured_wrap_width: refs_wrap_width,
622            cached_handler,
623            cached_pan_resolver,
624            handle_controller: None,
625            modal_depth: 0,
626            focus_bridge: None,
627            decorated,
628        }
629    }
630
631    /// Creates a node with custom line limits.
632    pub fn with_line_limits(mut self, line_limits: TextFieldLineLimits) -> Self {
633        self.line_limits = line_limits;
634        self.rebuild_cached_closures();
635        self
636    }
637
638    fn rebuild_cached_closures(&mut self) {
639        self.cached_handler = Self::create_handler(
640            self.state,
641            self.refs.clone(),
642            self.line_limits,
643            self.style.clone(),
644            self.modal_depth,
645        );
646        self.cached_pan_resolver = Self::create_pan_resolver(
647            self.state,
648            self.refs.clone(),
649            self.line_limits,
650            self.style.clone(),
651        );
652    }
653
654    /// Installs the controller the field publishes live handle metrics to.
655    pub fn with_handle_controller(mut self, controller: TextFieldHandleController) -> Self {
656        self.handle_controller = Some(controller);
657        self
658    }
659
660    fn create_pan_resolver(
661        state: TextFieldState,
662        refs: TextFieldRefs,
663        line_limits: TextFieldLineLimits,
664        style: TextStyle,
665    ) -> TextPanResolver {
666        Rc::new(move |viewport_width: f32| {
667            if !line_limits.is_single_line() {
668                refs.scroll_offset.set(0.0);
669                return 0.0;
670            }
671            let presentation = refs.presentation.get(state);
672            let pos = presentation.to_shown(state.selection().start);
673            let text_width = crate::text::measure_text(&presentation.shown, &style).width;
674            let cursor_x = crate::text::measure_text(
675                &crate::text::AnnotatedString::from(&presentation.text()[..pos]),
676                &style,
677            )
678            .width;
679            let offset = compute_horizontal_scroll_offset(
680                refs.scroll_offset.get(),
681                cursor_x,
682                text_width,
683                viewport_width,
684            );
685            refs.scroll_offset.set(offset);
686            offset
687        })
688    }
689
690    /// Returns the pan resolver for single-line fields, `None` for multi-line.
691    ///
692    /// Exposed to the modifier slices so the render scene builder can pan the
693    /// text glyphs by the same offset used for the cursor and selection.
694    pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
695        self.line_limits
696            .is_single_line()
697            .then(|| Rc::clone(&self.cached_pan_resolver))
698    }
699
700    /// Returns the current horizontal scroll (pan) offset in px.
701    pub fn scroll_offset(&self) -> f32 {
702        self.refs.scroll_offset.get()
703    }
704
705    /// Returns the current line limits configuration.
706    pub fn line_limits(&self) -> TextFieldLineLimits {
707        self.line_limits
708    }
709
710    pub(crate) fn create_handler(
711        state: TextFieldState,
712        refs: TextFieldRefs,
713        line_limits: TextFieldLineLimits,
714        style: TextStyle,
715        modal_depth: usize,
716    ) -> Rc<dyn Fn(PointerEvent)> {
717        use crate::text_selection::{
718            SelectionGranularity, resolve_selection_tap_count, tap_selection_granularity,
719        };
720
721        Rc::new(move |event: PointerEvent| {
722            let content = refs.content_origin.borrow().origin();
723            let click_x = (event.position.x - content.x + refs.scroll_offset.get()).max(0.0);
724            let click_y = (event.position.y - content.y).max(0.0);
725
726            match event.kind {
727                PointerEventKind::Down => {
728                    refs.direct_manipulation.set(true);
729                    refs.press_track.set(Some(PointerPressTrack {
730                        start: event.global_position,
731                        position: event.global_position,
732                    }));
733                    refs.gesture_claimed.set(false);
734
735                    request_pointer_focus(state, &refs, line_limits, &style, modal_depth);
736
737                    let uptime = event.uptime();
738                    let pos = hit_test_offset(state, &refs, &style, click_x, click_y);
739                    let selection = state.selection();
740                    let tap_in_selection =
741                        !selection.collapsed() && pos >= selection.min() && pos <= selection.max();
742                    let effective_count = resolve_selection_tap_count(
743                        refs.taps.count_at(uptime, event.position),
744                        refs.taps.last_count(),
745                        tap_in_selection,
746                        refs.taps.in_place(event.position),
747                    );
748
749                    let granularity = tap_selection_granularity(effective_count);
750                    let anchor = selection_anchor_at(state, pos, granularity);
751                    refs.drag_anchor.set(Some(anchor));
752                    state.edit(|buffer| match granularity {
753                        SelectionGranularity::Caret => buffer.place_cursor_before_char(pos),
754                        _ => buffer.select(TextRange::new(anchor.start, anchor.end)),
755                    });
756
757                    refs.taps.record(uptime, event.position, effective_count);
758                    event.consume();
759                }
760                PointerEventKind::Move => {
761                    if let Some(mut track) = refs.press_track.get() {
762                        track.position = event.global_position;
763                        refs.press_track.set(Some(track));
764                        if let Some(node_id) = refs.node_id.get() {
765                            crate::schedule_draw_repass(node_id);
766                        }
767                        crate::request_render_invalidation();
768                    }
769                    if refs.gesture_claimed.get() {
770                        event.consume();
771                        return;
772                    }
773                    if let Some(anchor) = refs.drag_anchor.get()
774                        && *refs.is_focused.borrow()
775                    {
776                        let current_pos = hit_test_offset(state, &refs, &style, click_x, click_y);
777                        state.set_selection(dragged_selection(state, anchor, current_pos));
778
779                        crate::request_render_invalidation();
780
781                        event.consume();
782                    }
783                }
784                PointerEventKind::Up => {
785                    refs.drag_anchor.set(None);
786                    refs.press_track.set(None);
787                    refs.gesture_claimed.set(false);
788                    if let Some(node_id) = refs.node_id.get() {
789                        crate::schedule_draw_repass(node_id);
790                    }
791                    crate::request_render_invalidation();
792                }
793                PointerEventKind::Cancel => {
794                    refs.press_track.set(None);
795                    refs.gesture_claimed.set(false);
796                    if let Some(node_id) = refs.node_id.get() {
797                        crate::schedule_draw_repass(node_id);
798                    }
799                    crate::request_render_invalidation();
800                }
801                _ => {}
802            }
803        })
804    }
805
806    /// Sets the focus state.
807    pub fn set_focused(&mut self, focused: bool) {
808        let current = *self.refs.is_focused.borrow();
809        if current != focused {
810            *self.refs.is_focused.borrow_mut() = focused;
811            if !focused {
812                self.refs.direct_manipulation.set(false);
813                self.refs.press_track.set(None);
814                self.refs.gesture_claimed.set(false);
815            }
816        }
817    }
818
819    /// Returns whether the field is focused.
820    pub fn is_focused(&self) -> bool {
821        *self.refs.is_focused.borrow()
822    }
823
824    pub(crate) fn window_sink(&self) -> Rc<Cell<WindowCoordinates>> {
825        Rc::clone(&self.refs.window)
826    }
827
828    pub(crate) fn layout_handle(&self) -> TextFieldLayoutHandle {
829        TextFieldLayoutHandle {
830            state: self.state,
831            wrap_width: Rc::clone(&self.measured_wrap_width),
832            presentation: Rc::clone(&self.refs.presentation),
833        }
834    }
835
836    /// Returns the current text.
837    pub fn text(&self) -> String {
838        self.state.text()
839    }
840
841    /// The field's text as shown, shared rather than copied.
842    pub(crate) fn shown_text(&self) -> crate::text::AnnotatedString {
843        self.refs.presentation.get(self.state).shown.clone()
844    }
845
846    /// Returns the text style the field lays out and draws with.
847    pub fn style(&self) -> &TextStyle {
848        &self.style
849    }
850
851    /// Returns the current selection.
852    pub fn selection(&self) -> TextRange {
853        self.state.selection()
854    }
855
856    /// Returns the cursor brush for rendering.
857    pub fn cursor_brush(&self) -> Brush {
858        self.cursor_brush.clone()
859    }
860
861    /// Returns the selection brush for rendering selection highlight.
862    pub fn selection_brush(&self) -> Brush {
863        self.selection_brush.clone()
864    }
865
866    /// Where the field's content sits in its node, set by slice collection
867    /// and placed by layout; clicks, the caret and the handles map through it.
868    pub(crate) fn set_content_origin(&self, origin: crate::modifier::CoordinatorRect) {
869        *self.refs.content_origin.borrow_mut() = origin;
870    }
871
872    fn wrap_width(&self, available_width: f32) -> Option<f32> {
873        (!self.line_limits.is_single_line() && available_width.is_finite() && available_width > 0.0)
874            .then_some(available_width)
875    }
876
877    fn measure_text_content(&self, wrap_width: Option<f32>) -> crate::text::TextMetrics {
878        let presentation = self.refs.presentation.get(self.state);
879        let annotated = &presentation.shown;
880        let metrics = match wrap_width {
881            Some(max_width) => crate::text::measure_text_with_options(
882                annotated,
883                &self.style,
884                crate::text::TextLayoutOptions::default(),
885                Some(max_width),
886            ),
887            None => crate::text::measure_text(annotated, &self.style),
888        };
889        self.measured_line_height.set(metrics.line_height);
890        metrics
891    }
892
893    /// The text's size on `density`'s grid: Compose sizes a field's layout
894    /// as its paragraph's size, `ceil`ed to whole pixels.
895    fn text_size(&self, wrap_width: Option<f32>, density: f32) -> (Size, crate::text::TextMetrics) {
896        let metrics = self.measure_text_content(wrap_width);
897        (
898            Size {
899                width: ceil_to_px(metrics.width, density),
900                height: ceil_to_px(metrics.height, density),
901            },
902            metrics,
903        )
904    }
905
906    /// The smallest box the field takes, as Compose's `textFieldMinSize`
907    /// gives it: one line of ten 'H's in its style, so an empty field is as
908    /// tall as a line and wide enough to type into.
909    fn min_size(&self, density: f32) -> Size {
910        if let Some((taken_at, size)) = self.min_size.get()
911            && taken_at == density
912        {
913            return size;
914        }
915        let metrics = crate::text::measure_text(
916            &crate::text::AnnotatedString::from(MIN_SIZE_TEXT),
917            &self.style,
918        );
919        let size = Size {
920            width: ceil_to_px(metrics.width, density),
921            height: ceil_to_px(metrics.height, density),
922        };
923        self.min_size.set(Some((density, size)));
924        size
925    }
926
927    fn update_cached_state(&mut self) -> bool {
928        let revision = self.state.text_revision();
929        let selection = self.state.selection();
930        let changed = revision != self.cached_revision || selection != self.cached_selection;
931        self.cached_revision = revision;
932        self.cached_selection = selection;
933        changed
934    }
935
936    fn intrinsic_height(&self, width: f32, density: f32) -> f32 {
937        self.text_size(self.wrap_width(width), density)
938            .0
939            .height
940            .max(self.min_size(density).height)
941    }
942}
943
944impl DelegatableNode for TextFieldModifierNode {
945    fn node_state(&self) -> &NodeState {
946        &self.node_state
947    }
948}
949
950impl ModifierNode for TextFieldModifierNode {
951    fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
952        self.refs.node_id.set(context.node_id());
953
954        context.invalidate(InvalidationKind::Layout);
955        context.invalidate(InvalidationKind::Draw);
956        if self.decorated {
957            return;
958        }
959        context.invalidate(InvalidationKind::Semantics);
960        self.refs.focus_node.set(context.node_id());
961
962        if let Some(node_id) = context.node_id() {
963            let bridge = TextFieldFocusBridge::handle(
964                self.state,
965                self.refs.clone(),
966                self.style.clone(),
967                self.line_limits,
968            );
969            self.focus_bridge = Some(Rc::clone(&bridge));
970            crate::focus_dispatch::register_focus_target(node_id, bridge);
971        }
972    }
973
974    fn on_detach(&mut self) {
975        if let (Some(node_id), Some(bridge)) = (self.refs.node_id.get(), self.focus_bridge.take()) {
976            crate::focus_dispatch::unregister_focus_target(node_id, &bridge);
977        }
978    }
979
980    fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
981        Some(self)
982    }
983
984    fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
985        Some(self)
986    }
987
988    fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
989        Some(self)
990    }
991
992    fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
993        Some(self)
994    }
995
996    cranpose_foundation::impl_semantics_node!();
997
998    fn as_pointer_input_node(&self) -> Option<&dyn PointerInputNode> {
999        (!self.decorated).then_some(self)
1000    }
1001
1002    fn as_pointer_input_node_mut(&mut self) -> Option<&mut dyn PointerInputNode> {
1003        if self.decorated { None } else { Some(self) }
1004    }
1005}
1006
1007impl LayoutModifierNode for TextFieldModifierNode {
1008    fn measure(
1009        &self,
1010        context: &mut dyn ModifierNodeContext,
1011        _measurable: &dyn Measurable,
1012        constraints: Constraints,
1013    ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
1014        let density = context.density();
1015        let wrap_width = self.wrap_width(constraints.max_width);
1016        self.measured_wrap_width.set(wrap_width);
1017        let (text, metrics) = self.text_size(wrap_width, density);
1018        let min = self.min_size(density);
1019        // The minimum joins the constraints' own, as a floor they bound.
1020        let fit = |length: f32, min: f32, low: f32, high: f32| {
1021            length.max(min.max(low).min(high)).min(high)
1022        };
1023        let size = Size {
1024            width: fit(
1025                text.width,
1026                min.width,
1027                constraints.min_width,
1028                constraints.max_width,
1029            ),
1030            height: fit(
1031                text.height,
1032                min.height,
1033                constraints.min_height,
1034                constraints.max_height,
1035            ),
1036        };
1037        self.measured_size.set(size);
1038
1039        let _ = (self.cached_pan_resolver)(size.width);
1040
1041        let first = crate::text::measure::text_line_box(&self.style)
1042            .map(crate::text::LineBox::first_baseline)
1043            .or_else(|| crate::text::measure::first_baseline(&self.style));
1044        let lines = cranpose_ui_layout::AlignmentLines::new(
1045            first,
1046            first.map(|baseline| {
1047                baseline + metrics.line_count.saturating_sub(1) as f32 * metrics.line_height
1048            }),
1049        );
1050        cranpose_ui_layout::LayoutModifierMeasureResult::with_size(size).with_alignment_lines(lines)
1051    }
1052
1053    // Compose's minimum size is a plain layout modifier, which leaves the
1054    // intrinsics to the text; an empty text is still a line tall.
1055    fn min_intrinsic_width(&self, _measurable: &dyn Measurable, _height: f32, density: f32) -> f32 {
1056        self.text_size(None, density).0.width
1057    }
1058
1059    fn max_intrinsic_width(&self, _measurable: &dyn Measurable, _height: f32, density: f32) -> f32 {
1060        self.text_size(None, density).0.width
1061    }
1062
1063    fn min_intrinsic_height(&self, _measurable: &dyn Measurable, width: f32, density: f32) -> f32 {
1064        self.intrinsic_height(width, density)
1065    }
1066
1067    fn max_intrinsic_height(&self, _measurable: &dyn Measurable, width: f32, density: f32) -> f32 {
1068        self.intrinsic_height(width, density)
1069    }
1070}
1071
1072/// The field's content viewport: its measured text area, or the draw
1073/// scope's size before the first measure. The draw scope is the field's
1074/// content rect, already inside the padding declared before the field.
1075fn content_viewport(measured: Size, size: Size) -> (f32, f32) {
1076    let width = if measured.width > 0.0 {
1077        measured.width
1078    } else {
1079        size.width
1080    };
1081    let height = if measured.height > 0.0 {
1082        measured.height
1083    } else {
1084        size.height
1085    };
1086    (width, height)
1087}
1088
1089impl DrawModifierNode for TextFieldModifierNode {
1090    fn create_draw_closure(
1091        &self,
1092    ) -> Option<Rc<dyn Fn(&mut cranpose_ui_graphics::DrawScopeDefault)>> {
1093        use cranpose_ui_graphics::{DrawPrimitive, DrawScope as _};
1094
1095        let is_focused = Rc::clone(&self.refs.is_focused);
1096        let state = self.state;
1097        let content_origin = Rc::clone(&self.refs.content_origin);
1098        let cursor_brush = self.cursor_brush.clone();
1099        let style = self.style.clone();
1100        let cached_line_height = Rc::clone(&self.measured_line_height);
1101        let measured_size = Rc::clone(&self.measured_size);
1102        let measured_wrap_width = Rc::clone(&self.measured_wrap_width);
1103        let pan_resolver = Rc::clone(&self.cached_pan_resolver);
1104        let handle_controller = self.handle_controller.clone();
1105        let window = Rc::clone(&self.refs.window);
1106        let direct_manipulation = Rc::clone(&self.refs.direct_manipulation);
1107        let press_track = self.refs.press_track;
1108        let gesture_claimed = Rc::clone(&self.refs.gesture_claimed);
1109        let presentation_cache = Rc::clone(&self.refs.presentation);
1110
1111        Some(Rc::new(move |scope| {
1112            let size = scope.size();
1113            if !*is_focused.borrow() {
1114                if let Some(controller) = &handle_controller {
1115                    controller.publish(TextFieldHandleMetrics {
1116                        focused: false,
1117                        direct_manipulation: false,
1118                        local_to_window: window.get().local_to_window,
1119                        padding_left: 0.0,
1120                        padding_top: 0.0,
1121                        scroll_offset: 0.0,
1122                        line_height: cached_line_height.get(),
1123                        glyph_box: crate::text::glyph_line_box(&style, cached_line_height.get()),
1124                        wrap_width: measured_wrap_width.get(),
1125                    });
1126                }
1127                return;
1128            }
1129
1130            let mut primitives = Vec::new();
1131
1132            let presentation = presentation_cache.get(state);
1133            let text = presentation.text();
1134            let selection = state.selection();
1135            let line_height = cached_line_height.get();
1136
1137            let (viewport_width, viewport_height) = content_viewport(measured_size.get(), size);
1138            let pan = pan_resolver(viewport_width);
1139
1140            if let Some(controller) = &handle_controller {
1141                controller.adopt_gesture_claim(&gesture_claimed);
1142                controller.adopt_press_track(press_track);
1143                controller.publish(TextFieldHandleMetrics {
1144                    focused: true,
1145                    direct_manipulation: direct_manipulation.get(),
1146                    local_to_window: window.get().local_to_window,
1147                    padding_left: content_origin.borrow().origin().x,
1148                    padding_top: content_origin.borrow().origin().y,
1149                    scroll_offset: pan,
1150                    line_height,
1151                    glyph_box: crate::text::glyph_line_box(&style, line_height),
1152                    wrap_width: measured_wrap_width.get(),
1153                });
1154            }
1155            let clip_bounds = cranpose_ui_graphics::Rect {
1156                x: 0.0,
1157                y: 0.0,
1158                width: viewport_width,
1159                height: viewport_height,
1160            };
1161
1162            if let Some(comp_range) = state.composition() {
1163                let (comp_start, comp_end) = presentation.range_to_shown(comp_range);
1164
1165                if comp_start < comp_end && comp_end <= text.len() {
1166                    let underline_brush = Brush::solid(Color(0.8, 0.8, 0.8, 0.8));
1167                    let underline_height: f32 = 2.0;
1168
1169                    for line_rect in range_visual_line_rects(
1170                        text,
1171                        &style,
1172                        measured_wrap_width.get(),
1173                        pan,
1174                        line_height,
1175                        comp_start..comp_end,
1176                    ) {
1177                        let underline_rect = cranpose_ui_graphics::Rect {
1178                            x: line_rect.x,
1179                            y: line_rect.y + line_height - underline_height,
1180                            width: line_rect.width,
1181                            height: underline_height,
1182                        };
1183                        if let Some(clipped) = intersect_rect(underline_rect, clip_bounds) {
1184                            primitives.push(DrawPrimitive::Rect {
1185                                rect: clipped,
1186                                brush: underline_brush.clone(),
1187                                stroke: None,
1188                            });
1189                        }
1190                    }
1191                }
1192            }
1193
1194            if selection.collapsed() && crate::cursor_animation::is_cursor_visible() {
1195                let pos = presentation.to_shown(selection.start);
1196                let (line_index, line_start) = caret_visual_line_for_offset(
1197                    text,
1198                    &style,
1199                    measured_wrap_width.get(),
1200                    pos,
1201                    crate::text_selection::LineAffinity::Upstream,
1202                );
1203                let cursor_x = crate::text::get_cursor_x_for_offset(
1204                    &crate::text::AnnotatedString::from(&text[line_start..pos]),
1205                    &style,
1206                    pos - line_start,
1207                ) - pan;
1208                let (box_off, box_h) = crate::text::glyph_line_box(&style, line_height);
1209                let cursor_y = line_index as f32 * line_height + box_off;
1210
1211                let cursor_rect = cranpose_ui_graphics::Rect {
1212                    x: cursor_x,
1213                    y: cursor_y,
1214                    width: CURSOR_WIDTH,
1215                    height: box_h,
1216                };
1217
1218                if let Some(clipped) = intersect_rect(cursor_rect, clip_bounds) {
1219                    primitives.push(DrawPrimitive::Rect {
1220                        rect: clipped,
1221                        brush: cursor_brush.clone(),
1222                        stroke: None,
1223                    });
1224                }
1225            }
1226
1227            scope.push_recorded(primitives);
1228        }))
1229    }
1230
1231    fn create_behind_draw_closure(
1232        &self,
1233    ) -> Option<Rc<dyn Fn(&mut cranpose_ui_graphics::DrawScopeDefault)>> {
1234        use cranpose_ui_graphics::{DrawPrimitive, DrawScope as _};
1235
1236        let is_focused = Rc::clone(&self.refs.is_focused);
1237        let state = self.state;
1238        let selection_brush = self.selection_brush.clone();
1239        let style = self.style.clone();
1240        let cached_line_height = Rc::clone(&self.measured_line_height);
1241        let measured_size = Rc::clone(&self.measured_size);
1242        let measured_wrap_width = Rc::clone(&self.measured_wrap_width);
1243        let pan_resolver = Rc::clone(&self.cached_pan_resolver);
1244        let presentation_cache = Rc::clone(&self.refs.presentation);
1245
1246        Some(Rc::new(move |scope| {
1247            let size = scope.size();
1248            if !*is_focused.borrow() {
1249                return;
1250            }
1251            let selection = state.selection();
1252            if selection.collapsed() {
1253                return;
1254            }
1255            let presentation = presentation_cache.get(state);
1256            let text = presentation.text();
1257            let (selection_start, selection_end) = presentation.range_to_shown(selection);
1258            let line_height = cached_line_height.get();
1259            let (viewport_width, viewport_height) = content_viewport(measured_size.get(), size);
1260            let pan = pan_resolver(viewport_width);
1261            let clip_bounds = cranpose_ui_graphics::Rect {
1262                x: 0.0,
1263                y: 0.0,
1264                width: viewport_width,
1265                height: viewport_height,
1266            };
1267
1268            let mut primitives = Vec::new();
1269            let (box_off, box_h) = crate::text::glyph_line_box(&style, line_height);
1270            for sel_rect in range_visual_line_rects(
1271                text,
1272                &style,
1273                measured_wrap_width.get(),
1274                pan,
1275                line_height,
1276                selection_start..selection_end,
1277            ) {
1278                let sel_rect = cranpose_ui_graphics::Rect {
1279                    y: sel_rect.y + box_off,
1280                    height: box_h,
1281                    ..sel_rect
1282                };
1283                if let Some(clipped) = intersect_rect(sel_rect, clip_bounds) {
1284                    primitives.push(DrawPrimitive::Rect {
1285                        rect: clipped,
1286                        brush: selection_brush.clone(),
1287                        stroke: None,
1288                    });
1289                }
1290            }
1291            scope.push_recorded(primitives);
1292        }))
1293    }
1294}
1295
1296impl SemanticsNode for TextFieldModifierNode {
1297    fn merge_semantics(&self, config: &mut SemanticsConfiguration) {
1298        if !self.decorated {
1299            merge_text_field_semantics(self.state, self.line_limits, self.refs.is_secure(), config);
1300        }
1301    }
1302
1303    /// Neither modal nor hidden, but the field's text and selection are read
1304    /// live from its state, which an app may set without touching the node.
1305    fn reach(&self) -> cranpose_foundation::SemanticsReach {
1306        cranpose_foundation::SemanticsReach {
1307            merges_live_state: true,
1308            ..cranpose_foundation::SemanticsReach::default()
1309        }
1310    }
1311}
1312
1313/// What an editable field tells accessibility, from the node that takes its
1314/// input.
1315/// A field's text for debug output: its length alone when it is a secret.
1316fn debug_text(state: TextFieldState, secure: bool) -> String {
1317    if secure {
1318        state.with_text(|text| format!("<{} secret bytes>", text.len()))
1319    } else {
1320        state.text()
1321    }
1322}
1323
1324pub(crate) fn merge_text_field_semantics(
1325    state: TextFieldState,
1326    line_limits: TextFieldLineLimits,
1327    secure: bool,
1328    config: &mut SemanticsConfiguration,
1329) {
1330    if secure {
1331        // A reader hears one dot for each character, as native password
1332        // fields read, and never the text.
1333        config.password = true;
1334        config.text = Some(state.with_text(|text| {
1335            unicode_segmentation::UnicodeSegmentation::graphemes(text, true)
1336                .map(|_| '\u{2022}')
1337                .collect()
1338        }));
1339    } else {
1340        let text = state.text();
1341        if config.content_description.is_none() {
1342            config.content_description = Some(text.clone());
1343        }
1344        config.text = Some(text);
1345    }
1346    config.is_editable_text = true;
1347    config.is_clickable = true;
1348    config.multiline = !matches!(line_limits, TextFieldLineLimits::SingleLine);
1349    config.set_text = Some(cranpose_foundation::SemanticsSetText::new(move |text| {
1350        state.set_text(text)
1351    }));
1352    config.set_selection = Some(cranpose_foundation::SemanticsSetSelection::new(
1353        move |anchor, focus| {
1354            let (anchor, focus) = state.with_text(|text| {
1355                (
1356                    text.floor_char_boundary(anchor),
1357                    text.floor_char_boundary(focus),
1358                )
1359            });
1360            state.set_selection(TextRange::new(anchor, focus));
1361            crate::cursor_animation::reset_cursor_blink();
1362            crate::request_render_invalidation();
1363            true
1364        },
1365    ));
1366    config.text_selection = Some(state.selection());
1367}
1368
1369impl PointerInputNode for TextFieldModifierNode {
1370    fn on_pointer_event(
1371        &mut self,
1372        _context: &mut dyn ModifierNodeContext,
1373        _event: &PointerEvent,
1374    ) -> bool {
1375        false
1376    }
1377
1378    fn hit_test(&self, x: f32, y: f32) -> bool {
1379        let size = self.measured_size.get();
1380        x >= 0.0 && x <= size.width && y >= 0.0 && y <= size.height
1381    }
1382
1383    fn pointer_input_handler(&self) -> Option<Rc<dyn Fn(PointerEvent)>> {
1384        Some(Rc::clone(&self.cached_handler))
1385    }
1386}
1387
1388/// Element that creates and updates `TextFieldModifierNode` instances.
1389///
1390/// This follows the modifier element pattern where the element is responsible for:
1391/// - Creating new nodes (via `create`)
1392/// - Updating existing nodes when properties change (via `update`)
1393/// - Declaring capabilities (LAYOUT | DRAW | SEMANTICS)
1394#[derive(Clone)]
1395pub struct TextFieldElement {
1396    state: TextFieldState,
1397    style: TextStyle,
1398    cursor_color: Color,
1399    selection_color: Color,
1400    line_limits: TextFieldLineLimits,
1401    show_keyboard_on_focus: bool,
1402    keyboard_options: crate::KeyboardOptions,
1403    /// Left out of equality and hashing: the element updates its node in
1404    /// every composition, which hands the node the latest closure.
1405    keyboard_action: Option<crate::KeyboardActionHandler>,
1406    /// Left out of equality and hashing, as `keyboard_action` is.
1407    input_transformation: Option<cranpose_foundation::text::InputTransformation>,
1408    /// Compared by identity and left out of hashing.
1409    output_transformation: Option<OutputTransformation>,
1410    secure: bool,
1411    handle_controller: Option<TextFieldHandleController>,
1412    modal_depth: usize,
1413    decorator: Option<TextFieldRefs>,
1414}
1415
1416impl TextFieldElement {
1417    /// Creates a new text field element.
1418    pub fn new(state: TextFieldState, style: TextStyle) -> Self {
1419        Self {
1420            state,
1421            style,
1422            cursor_color: DEFAULT_CURSOR_COLOR,
1423            selection_color: DEFAULT_SELECTION_COLOR,
1424            line_limits: TextFieldLineLimits::default(),
1425            show_keyboard_on_focus: true,
1426            keyboard_options: crate::KeyboardOptions::default(),
1427            keyboard_action: None,
1428            input_transformation: None,
1429            output_transformation: None,
1430            secure: false,
1431            handle_controller: None,
1432            modal_depth: 0,
1433            decorator: None,
1434        }
1435    }
1436
1437    /// Hands the field's input, focus and semantics to the decoration box
1438    /// that shares `refs`.
1439    pub(crate) fn decorated_by(mut self, refs: TextFieldRefs) -> Self {
1440        self.decorator = Some(refs);
1441        self
1442    }
1443
1444    /// Creates an element with custom cursor color.
1445    pub fn with_cursor_color(mut self, color: Color) -> Self {
1446        self.cursor_color = color;
1447        self
1448    }
1449
1450    /// Creates an element whose selection highlight is drawn in `color`.
1451    pub fn with_selection_color(mut self, color: Color) -> Self {
1452        self.selection_color = color;
1453        self
1454    }
1455
1456    /// Creates an element with custom line limits.
1457    pub fn with_line_limits(mut self, line_limits: TextFieldLineLimits) -> Self {
1458        self.line_limits = line_limits;
1459        self
1460    }
1461
1462    /// Sets whether focus opens the software keyboard. A pointer tap always
1463    /// requests it, including when the field is already focused.
1464    pub fn with_show_keyboard_on_focus(mut self, show: bool) -> Self {
1465        self.show_keyboard_on_focus = show;
1466        self
1467    }
1468
1469    /// Sets the software keyboard the field asks for, and what runs its
1470    /// action key.
1471    pub fn with_keyboard(
1472        mut self,
1473        options: crate::KeyboardOptions,
1474        action: Option<crate::KeyboardActionHandler>,
1475    ) -> Self {
1476        self.keyboard_options = options;
1477        self.keyboard_action = action;
1478        self
1479    }
1480
1481    /// Sets what changes or rejects each edit the person makes.
1482    pub fn with_input_transformation(
1483        mut self,
1484        transformation: Option<cranpose_foundation::text::InputTransformation>,
1485    ) -> Self {
1486        self.input_transformation = transformation;
1487        self
1488    }
1489
1490    /// Sets how the field shows its text.
1491    pub fn with_output_transformation(
1492        mut self,
1493        transformation: Option<OutputTransformation>,
1494    ) -> Self {
1495        self.output_transformation = transformation;
1496        self
1497    }
1498
1499    /// Marks the field as holding a secret: no copy or cut, semantics and
1500    /// debug output without its text.
1501    pub(crate) fn secure(mut self, secure: bool) -> Self {
1502        self.secure = secure;
1503        self
1504    }
1505
1506    /// Installs the finger-handle metrics channel shared with the composable.
1507    pub fn with_handle_controller(mut self, controller: TextFieldHandleController) -> Self {
1508        self.handle_controller = Some(controller);
1509        self
1510    }
1511
1512    /// Sets the modal depth this field was composed at (see
1513    /// [`crate::modal::local_modal_depth`]).
1514    pub fn with_modal_depth(mut self, depth: usize) -> Self {
1515        self.modal_depth = depth;
1516        self
1517    }
1518
1519    /// Gives the field's refs what its input reads when it runs: keyboard,
1520    /// action handler and transformations.
1521    fn hand_input_options_to(&self, refs: &TextFieldRefs) {
1522        refs.keyboard_options.set(self.keyboard_options);
1523        refs.keyboard_action.replace(self.keyboard_action.clone());
1524        refs.input_transformation
1525            .replace(self.input_transformation.clone());
1526        refs.presentation
1527            .set_transformation(self.output_transformation.clone());
1528        if let Some(controller) = &self.handle_controller {
1529            controller.adopt_presentation(&refs.presentation);
1530        }
1531    }
1532}
1533
1534impl std::fmt::Debug for TextFieldElement {
1535    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1536        f.debug_struct("TextFieldElement")
1537            .field("text", &debug_text(self.state, self.secure))
1538            .field("style", &self.style)
1539            .field("cursor_color", &self.cursor_color)
1540            .finish()
1541    }
1542}
1543
1544impl Hash for TextFieldElement {
1545    fn hash<H: Hasher>(&self, state: &mut H) {
1546        self.state.id().hash(state);
1547        for color in [self.cursor_color, self.selection_color] {
1548            [color.0, color.1, color.2, color.3]
1549                .map(f32::to_bits)
1550                .hash(state);
1551        }
1552        self.style.render_hash().hash(state);
1553        self.line_limits.hash(state);
1554        self.show_keyboard_on_focus.hash(state);
1555        self.keyboard_options.hash(state);
1556        self.secure.hash(state);
1557        self.modal_depth.hash(state);
1558        self.decorator.as_ref().map(TextFieldRefs::key).hash(state);
1559    }
1560}
1561
1562impl PartialEq for TextFieldElement {
1563    fn eq(&self, other: &Self) -> bool {
1564        self.state == other.state
1565            && self.style == other.style
1566            && self.cursor_color == other.cursor_color
1567            && self.selection_color == other.selection_color
1568            && self.line_limits == other.line_limits
1569            && self.show_keyboard_on_focus == other.show_keyboard_on_focus
1570            && self.keyboard_options == other.keyboard_options
1571            && self.output_transformation == other.output_transformation
1572            && self.secure == other.secure
1573            && self.modal_depth == other.modal_depth
1574            && self.decorator == other.decorator
1575    }
1576}
1577
1578impl Eq for TextFieldElement {}
1579
1580impl ModifierNodeElement for TextFieldElement {
1581    type Node = TextFieldModifierNode;
1582
1583    fn create(&self) -> Self::Node {
1584        let refs = self.decorator.clone().unwrap_or_else(TextFieldRefs::new);
1585        let decorated = self.decorator.is_some();
1586        let mut node =
1587            TextFieldModifierNode::with_refs(self.state, self.style.clone(), refs, decorated)
1588                .with_line_limits(self.line_limits);
1589        node.cursor_brush = Brush::solid(self.cursor_color);
1590        node.selection_brush = Brush::solid(self.selection_color);
1591        node.modal_depth = self.modal_depth;
1592        node.refs.focus_options.set(TextFieldFocusOptions {
1593            modal_depth: self.modal_depth,
1594            show_keyboard_on_focus: self.show_keyboard_on_focus,
1595            secure: self.secure,
1596        });
1597        self.hand_input_options_to(&node.refs);
1598        if let Some(controller) = self.handle_controller.clone() {
1599            node = node.with_handle_controller(controller);
1600        }
1601        node.rebuild_cached_closures();
1602        node
1603    }
1604
1605    fn update(&self, node: &mut Self::Node) {
1606        node.state = self.state;
1607        if node.style != self.style {
1608            node.min_size.set(None);
1609            node.style = self.style.clone();
1610        }
1611        node.cursor_brush = Brush::solid(self.cursor_color);
1612        node.selection_brush = Brush::solid(self.selection_color);
1613        node.line_limits = self.line_limits;
1614        node.handle_controller.clone_from(&self.handle_controller);
1615        node.modal_depth = self.modal_depth;
1616        let previous_focus_options = node.refs.focus_options.replace(TextFieldFocusOptions {
1617            modal_depth: self.modal_depth,
1618            show_keyboard_on_focus: self.show_keyboard_on_focus,
1619            secure: self.secure,
1620        });
1621        if self.show_keyboard_on_focus
1622            && !previous_focus_options.show_keyboard_on_focus
1623            && *node.refs.is_focused.borrow()
1624        {
1625            crate::text_input_session::notify_text_input_focus_gained();
1626        }
1627        self.hand_input_options_to(&node.refs);
1628        node.rebuild_cached_closures();
1629
1630        if node.update_cached_state() {}
1631    }
1632
1633    /// A decorated field's node shares its decoration's refs, so it is
1634    /// never handed to a field decorated by another.
1635    fn key(&self) -> Option<u64> {
1636        self.decorator.as_ref().map(TextFieldRefs::key)
1637    }
1638
1639    fn capabilities(&self) -> NodeCapabilities {
1640        let drawn = NodeCapabilities::LAYOUT | NodeCapabilities::DRAW | NodeCapabilities::SEMANTICS;
1641        if self.decorator.is_some() {
1642            drawn
1643        } else {
1644            drawn | NodeCapabilities::POINTER_INPUT
1645        }
1646    }
1647
1648    fn always_update(&self) -> bool {
1649        true
1650    }
1651}
1652
1653#[cfg(test)]
1654#[path = "tests/text_field_modifier_node_tests.rs"]
1655mod tests;