Skip to main content

cranpose_ui/
text_field_modifier_node.rs

1//! Text field modifier node for editable text input.
2//!
3//! This module implements the modifier node for `BasicTextField`, following
4//! Jetpack Compose's `CoreTextFieldNode` architecture.
5//!
6//! The node handles:
7//! - **Layout**: Measures text content and returns appropriate size
8//! - **Draw**: Renders text, cursor, and selection highlights
9//! - **Pointer Input**: Handles tap to position cursor, drag for selection
10//! - **Semantics**: Provides text content for accessibility
11//!
12//! # Architecture
13//!
14//! Unlike display-only `TextModifierNode`, this node:
15//! - References a `TextFieldState` for mutable text
16//! - Tracks focus state for cursor visibility
17//! - Handles pointer events for cursor positioning
18
19use std::{
20    cell::{Cell, RefCell},
21    hash::{Hash, Hasher},
22    rc::Rc,
23};
24
25use cranpose_core::{mutableStateOf, MutableState};
26use cranpose_foundation::{
27    text::{TextFieldLineLimits, TextFieldState, TextRange},
28    Constraints, DelegatableNode, DrawModifierNode, DrawScope, InvalidationKind,
29    LayoutModifierNode, Measurable, ModifierNode, ModifierNodeContext, ModifierNodeElement,
30    NodeCapabilities, NodeState, PointerEvent, PointerEventKind, PointerInputNode,
31    SemanticsConfiguration, SemanticsNode, Size,
32};
33use cranpose_ui_graphics::{Brush, Color, Point};
34
35/// Live geometry a `BasicTextField` needs to place and drive its selection
36/// handles: whether the field is focused and is under direct manipulation, its
37/// on-screen origin (window coordinates) and the metrics that map a window
38/// position back to a text offset.
39#[derive(Clone, Copy, PartialEq, Debug)]
40pub struct TextFieldHandleMetrics {
41    pub focused: bool,
42    /// A primary pointer has interacted with the focused field. Mouse, touch,
43    /// and pen all expose the same draggable selection mechanics.
44    pub direct_manipulation: bool,
45    /// Field node's top-left in window coordinates.
46    pub node_origin: Point,
47    pub padding_left: f32,
48    pub padding_top: f32,
49    pub scroll_offset: f32,
50    pub line_height: f32,
51    /// Tight glyph box `(top_offset, height)` inside each line slot — what
52    /// the caret, highlight and finger handles anchor to (the reference
53    /// selection chrome rides the glyphs, not the paragraph slot).
54    pub glyph_box: (f32, f32),
55    /// Width the field wrapped its text at (`None` for single-line fields).
56    /// Lets the handles resolve the same visual (wrapped) lines the caret does.
57    pub wrap_width: Option<f32>,
58}
59
60/// Shared channel by which a `TextFieldModifierNode` publishes its live handle
61/// [`TextFieldHandleMetrics`] to the `BasicTextField` composable that renders
62/// the handles. Reads subscribe reactively (backed by a revision `MutableState`)
63/// so the composable recomposes when the field's focus/geometry changes.
64#[derive(Clone)]
65pub struct TextFieldHandleController {
66    inner: Rc<TextFieldHandleControllerInner>,
67}
68
69impl PartialEq for TextFieldHandleController {
70    fn eq(&self, other: &Self) -> bool {
71        Rc::ptr_eq(&self.inner, &other.inner)
72    }
73}
74
75struct TextFieldHandleControllerInner {
76    metrics: Cell<Option<TextFieldHandleMetrics>>,
77    revision: MutableState<u64>,
78    /// The field node's gesture-claim flag, adopted at publish time so the
79    /// widget's long-press watcher can take over the live pointer (the node
80    /// then stops drag-selecting under it).
81    gesture_claim: RefCell<Option<Rc<Cell<bool>>>>,
82    /// The field node's reactive primary-pointer stream. This stays separate
83    /// from draw-published geometry so every move reaches composables without
84    /// waiting for a render pass.
85    press_track: Cell<Option<MutableState<Option<PointerPressTrack>>>>,
86}
87
88impl TextFieldHandleController {
89    /// Creates a controller. Must run with an active runtime (i.e. inside a
90    /// composition, via `remember`).
91    pub fn new() -> Self {
92        Self {
93            inner: Rc::new(TextFieldHandleControllerInner {
94                metrics: Cell::new(None),
95                revision: mutableStateOf(0u64),
96                gesture_claim: RefCell::new(None),
97                press_track: Cell::new(None),
98            }),
99        }
100    }
101
102    /// Publishes fresh metrics, waking any reader only when they actually
103    /// changed (so a resting frame does not spin recomposition).
104    pub(crate) fn publish(&self, metrics: TextFieldHandleMetrics) {
105        if self.inner.metrics.get() != Some(metrics) {
106            self.inner.metrics.set(Some(metrics));
107            self.inner
108                .revision
109                .update(|value| *value = value.wrapping_add(1));
110        }
111    }
112
113    /// Reads the latest metrics, subscribing the current recompose scope to
114    /// future changes.
115    pub fn metrics(&self) -> Option<TextFieldHandleMetrics> {
116        let _ = self.inner.revision.value();
117        self.inner.metrics.get()
118    }
119
120    /// Adopts the field node's gesture-claim flag (idempotent).
121    pub(crate) fn adopt_gesture_claim(&self, claim: &Rc<Cell<bool>>) {
122        let mut slot = self.inner.gesture_claim.borrow_mut();
123        let adopted = slot.as_ref().is_some_and(|held| Rc::ptr_eq(held, claim));
124        if !adopted {
125            *slot = Some(Rc::clone(claim));
126        }
127    }
128
129    pub(crate) fn adopt_press_track(&self, press_track: MutableState<Option<PointerPressTrack>>) {
130        if self.inner.press_track.get() != Some(press_track) {
131            self.inner.press_track.set(Some(press_track));
132            self.inner
133                .revision
134                .update(|value| *value = value.wrapping_add(1));
135        }
136    }
137
138    /// Reads the active primary-pointer stream reactively.
139    pub fn press(&self) -> Option<PointerPressTrack> {
140        self.inner.press_track.get().and_then(|state| state.get())
141    }
142
143    /// Claims the active press gesture for the widget layer: the node stops
144    /// drag-selecting and the press stream drives the menu slide instead.
145    pub fn claim_gesture(&self) {
146        if let Some(claim) = self.inner.gesture_claim.borrow().as_ref() {
147            claim.set(true);
148        }
149    }
150
151    /// Whether the active press gesture is claimed by the widget layer.
152    pub fn gesture_claimed(&self) -> bool {
153        self.inner
154            .gesture_claim
155            .borrow()
156            .as_ref()
157            .is_some_and(|claim| claim.get())
158    }
159}
160
161impl Default for TextFieldHandleController {
162    fn default() -> Self {
163        Self::new()
164    }
165}
166
167/// Default cursor color (white - visible on dark backgrounds)
168const DEFAULT_CURSOR_COLOR: Color = Color(1.0, 1.0, 1.0, 1.0);
169
170/// Default selection highlight color (light blue with transparency)
171const DEFAULT_SELECTION_COLOR: Color = Color(0.0, 0.5, 1.0, 0.3);
172
173/// Default line height for empty text fields
174const DEFAULT_LINE_HEIGHT: f32 = 20.0;
175
176/// Cursor width in pixels
177const CURSOR_WIDTH: f32 = 2.0;
178
179/// Computes the horizontal scroll (pan) offset that keeps the cursor visible
180/// inside the viewport of a single-line text field.
181///
182/// Mirrors Jetpack Compose's `TextFieldScrollerPosition.coerceOffset` behavior:
183/// - the offset only changes when the cursor would leave the viewport,
184/// - the offset is clamped so the text never detaches from the left edge and
185///   never scrolls further than needed to show the end of the text (plus the
186///   cursor width, so a cursor at the end of the text stays visible).
187///
188/// All values are in px within the field's content coordinate space.
189pub(crate) fn compute_horizontal_scroll_offset(
190    current_offset: f32,
191    cursor_x: f32,
192    text_width: f32,
193    viewport_width: f32,
194) -> f32 {
195    if viewport_width <= 0.0 {
196        return 0.0;
197    }
198    let max_offset = (text_width + CURSOR_WIDTH - viewport_width).max(0.0);
199    let mut offset = current_offset.clamp(0.0, max_offset);
200    let visible_end = offset + viewport_width - CURSOR_WIDTH;
201    if cursor_x > visible_end {
202        // Cursor ran past the right edge: pan so it sits at the right edge.
203        offset = cursor_x - viewport_width + CURSOR_WIDTH;
204    } else if cursor_x < offset {
205        // Cursor ran past the left edge: pan so it sits at the left edge.
206        offset = cursor_x;
207    }
208    offset.clamp(0.0, max_offset)
209}
210
211/// Intersects `rect` with `bounds`, returning `None` when nothing remains.
212///
213/// Used to clip selection/cursor/composition primitives to the field's
214/// viewport so they never draw outside the field bounds.
215pub(crate) fn intersect_rect(
216    rect: cranpose_ui_graphics::Rect,
217    bounds: cranpose_ui_graphics::Rect,
218) -> Option<cranpose_ui_graphics::Rect> {
219    let x0 = rect.x.max(bounds.x);
220    let y0 = rect.y.max(bounds.y);
221    let x1 = (rect.x + rect.width).min(bounds.x + bounds.width);
222    let y1 = (rect.y + rect.height).min(bounds.y + bounds.height);
223    (x1 > x0 && y1 > y0).then_some(cranpose_ui_graphics::Rect {
224        x: x0,
225        y: y0,
226        width: x1 - x0,
227        height: y1 - y0,
228    })
229}
230
231/// Resolver that recomputes (and stores) the horizontal pan offset for a
232/// text field given the current content viewport width in px.
233pub type TextPanResolver = Rc<dyn Fn(f32) -> f32>;
234
235/// Resolves the caret's visual `(line_index, line_start_byte)` for byte
236/// `offset`.
237///
238/// For a wrapping (multi-line) field this lays the text out at the same wrap
239/// width the field measured and returns the VISUAL line the caret sits on, so
240/// the drawn caret lands on the same glyph the renderer draws. For a
241/// non-wrapping field (single line, or when no wrap width is known yet) it falls
242/// back to counting logical `\n` lines. Shared by the in-content caret and the
243/// overlay selection handles so both agree.
244pub(crate) fn caret_visual_line_for_offset(
245    text: &str,
246    style: &TextStyle,
247    node_id: Option<cranpose_core::NodeId>,
248    wrap_width: Option<f32>,
249    offset: usize,
250    affinity: crate::text_selection::LineAffinity,
251) -> (usize, usize) {
252    let offset = offset.min(text.len());
253    match wrap_width {
254        Some(width) if width.is_finite() && width > 0.0 => {
255            let annotated = crate::text::AnnotatedString::from(text);
256            let ranges = crate::text::wrapped_line_ranges(
257                node_id,
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            // Logical `\n` lines never share a boundary byte (the separator
267            // sits between them), so affinity cannot change the result here.
268            let before = &text[..offset];
269            let line_index = before.matches('\n').count();
270            let line_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0);
271            (line_index, line_start)
272        }
273    }
274}
275
276/// Window-space (pre-clip) rects covering byte range `start..end`, one per
277/// VISUAL (wrapped) line the range touches, each spanning the full
278/// `line_height`.
279///
280/// Shared by the selection highlight and the composition-preedit underline so
281/// both track soft-wrapping exactly as the renderer and caret do. Splitting on
282/// logical `\n` alone draws the rect on the wrong line whenever a line above
283/// the range soft-wraps (the x stays right, the y lands one visual line too
284/// high). Iterating the same wrapped ranges the renderer lays out keeps them in
285/// sync.
286#[allow(clippy::too_many_arguments)]
287pub(crate) fn range_visual_line_rects(
288    text: &str,
289    style: &TextStyle,
290    node_id: Option<cranpose_core::NodeId>,
291    wrap_width: Option<f32>,
292    padding_left: f32,
293    padding_top: f32,
294    pan: f32,
295    line_height: f32,
296    start: usize,
297    end: usize,
298) -> Vec<cranpose_ui_graphics::Rect> {
299    if start >= end {
300        return Vec::new();
301    }
302    let annotated = crate::text::AnnotatedString::from(text);
303    let line_ranges = crate::text::wrapped_line_ranges(
304        node_id,
305        &annotated,
306        style,
307        crate::text::TextLayoutOptions::default(),
308        wrap_width,
309    );
310    let mut rects = Vec::new();
311    for (line_idx, line_range) in line_ranges.iter().enumerate() {
312        let line_start = line_range.start;
313        let line_end = line_range.end;
314        if end <= line_start || start >= line_end {
315            continue;
316        }
317        let seg_start = start.max(line_start);
318        let seg_end = end.min(line_end);
319        let x0 = crate::text::measure_text(
320            &crate::text::AnnotatedString::from(&text[line_start..seg_start]),
321            style,
322        )
323        .width
324            + padding_left
325            - pan;
326        let x1 = crate::text::measure_text(
327            &crate::text::AnnotatedString::from(&text[line_start..seg_end]),
328            style,
329        )
330        .width
331            + padding_left
332            - pan;
333        let width = x1 - x0;
334        if width > 0.0 {
335            rects.push(cranpose_ui_graphics::Rect {
336                x: x0,
337                y: padding_top + line_idx as f32 * line_height,
338                width,
339                height: line_height,
340            });
341        }
342    }
343    rects
344}
345
346/// Shared references for text field input handling.
347///
348/// This struct bundles the shared state references passed to the pointer input handler,
349/// reducing the argument count for `create_handler` from 8 individual `Rc` parameters
350/// to a single struct (fixing clippy::too_many_arguments).
351#[derive(Clone)]
352pub(crate) struct TextFieldRefs {
353    /// Whether this field is currently focused
354    pub is_focused: Rc<RefCell<bool>>,
355    /// Content offset from left (padding) for accurate click positioning
356    pub content_offset: Rc<Cell<f32>>,
357    /// Content offset from top (padding) for cursor Y positioning
358    pub content_y_offset: Rc<Cell<f32>>,
359    /// Drag anchor position (byte offset) for click-drag selection
360    pub drag_anchor: Rc<Cell<Option<usize>>>,
361    /// Last click time for double/triple-click detection
362    pub last_click_time: Rc<Cell<Option<web_time::Instant>>>,
363    /// Last click screen position, for multi-tap slop gating
364    pub last_click_pos: Rc<Cell<Option<(f32, f32)>>>,
365    /// Click count (1=single, 2=double, 3=triple)
366    pub click_count: Rc<Cell<u8>>,
367    /// Node ID for scoped layout invalidation
368    pub node_id: Rc<Cell<Option<cranpose_core::NodeId>>>,
369    /// Horizontal scroll (pan) offset in px for single-line fields.
370    /// Keeps the cursor visible when the text is wider than the field.
371    pub scroll_offset: Rc<Cell<f32>>,
372    /// Whether the focused field has been entered through a primary pointer.
373    /// This is source-independent: desktop mouse, touch, and pen share the
374    /// same direct-manipulation selection UI.
375    pub direct_manipulation: Rc<Cell<bool>>,
376    /// Field node's top-left in window coordinates, derived from the most recent
377    /// pointer event (`global_position - position`). Used to place selection
378    /// handles in the top-level overlay, which is in window space.
379    pub node_origin: Rc<Cell<Point>>,
380    /// Line height from the last measurement. Shared with the node's
381    /// `measured_line_height` so the pointer handler maps a tap's `y` to the
382    /// correct VISUAL (wrapped) line.
383    pub line_height: Rc<Cell<f32>>,
384    /// Wrap width the last measurement laid the text out at (`None` for
385    /// single-line fields). Shared with the node's `measured_wrap_width` so the
386    /// pointer handler resolves the same wrapped lines the renderer draws.
387    pub wrap_width: Rc<Cell<Option<f32>>>,
388    /// Live primary-pointer press on the text surface (window space), for the
389    /// widget layer's long-press → slide-to-menu gesture.
390    pub press_track: MutableState<Option<PointerPressTrack>>,
391    /// Set by the widget when its long-press watcher claims the active
392    /// gesture: the node then stops drag-selecting on Move and the press
393    /// positions feed the menu slide instead.
394    pub gesture_claimed: Rc<Cell<bool>>,
395}
396
397/// A live primary-pointer press on the text surface, published by the field node
398/// for the widget layer (window coordinates).
399#[derive(Clone, Copy, Debug, PartialEq)]
400pub struct PointerPressTrack {
401    /// Where the press went down.
402    pub start: Point,
403    /// The press's current position.
404    pub position: Point,
405}
406
407impl TextFieldRefs {
408    /// Creates a new set of shared references.
409    pub fn new() -> Self {
410        Self {
411            is_focused: Rc::new(RefCell::new(false)),
412            content_offset: Rc::new(Cell::new(0.0_f32)),
413            content_y_offset: Rc::new(Cell::new(0.0_f32)),
414            drag_anchor: Rc::new(Cell::new(None::<usize>)),
415            last_click_time: Rc::new(Cell::new(None::<web_time::Instant>)),
416            last_click_pos: Rc::new(Cell::new(None::<(f32, f32)>)),
417            click_count: Rc::new(Cell::new(0_u8)),
418            node_id: Rc::new(Cell::new(None::<cranpose_core::NodeId>)),
419            scroll_offset: Rc::new(Cell::new(0.0_f32)),
420            direct_manipulation: Rc::new(Cell::new(false)),
421            node_origin: Rc::new(Cell::new(Point { x: 0.0, y: 0.0 })),
422            line_height: Rc::new(Cell::new(DEFAULT_LINE_HEIGHT)),
423            wrap_width: Rc::new(Cell::new(None::<f32>)),
424            press_track: mutableStateOf(None::<PointerPressTrack>),
425            gesture_claimed: Rc::new(Cell::new(false)),
426        }
427    }
428}
429
430/// Modifier node for editable text fields.
431///
432/// This node is the core of `BasicTextField`, handling:
433/// - Text measurement and layout
434/// - Cursor and selection rendering
435/// - Pointer input for cursor positioning
436use crate::text::TextStyle; // Add import
437
438pub struct TextFieldModifierNode {
439    /// The text field state (shared)
440    state: TextFieldState,
441    /// Shared references for input handling
442    refs: TextFieldRefs,
443    /// Text style
444    style: TextStyle, // Add style
445    /// Cursor brush color
446    cursor_brush: Brush,
447    /// Selection highlight brush
448    selection_brush: Brush,
449    /// Line limits configuration
450    line_limits: TextFieldLineLimits,
451    /// Cached text value for change detection
452    cached_text: String,
453    /// Cached selection for change detection
454    cached_selection: TextRange,
455    /// Node state for delegation
456    node_state: NodeState,
457    /// Measured size cache (shared with the draw closure as the pan viewport)
458    measured_size: Rc<Cell<Size>>,
459    /// Cached line height from last measurement (shared with draw closure)
460    measured_line_height: Rc<Cell<f32>>,
461    /// Wrap width the last measurement laid the text out at (`None` for
462    /// single-line fields, which pan instead of wrapping). Shared with the draw
463    /// closure so the caret and selection handles resolve the same *visual*
464    /// (wrapped) lines the renderer draws, instead of counting only logical
465    /// `\n` lines.
466    measured_wrap_width: Rc<Cell<Option<f32>>>,
467    /// Cached pointer input handler
468    cached_handler: Rc<dyn Fn(PointerEvent)>,
469    /// Cached horizontal pan resolver (recomputes + stores the scroll offset)
470    cached_pan_resolver: TextPanResolver,
471    /// Channel to publish live handle metrics to the `BasicTextField`
472    /// composable that renders the finger selection handles. `None` when the
473    /// field is used without handle support.
474    handle_controller: Option<TextFieldHandleController>,
475    /// The [`crate::modal::local_modal_depth`] this field was composed at,
476    /// forwarded to every focus request so a field behind an open dialog is
477    /// refused focus (see `crate::text_field_focus::request_focus`).
478    modal_depth: usize,
479}
480
481impl std::fmt::Debug for TextFieldModifierNode {
482    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
483        f.debug_struct("TextFieldModifierNode")
484            .field("text", &self.state.text())
485            .field("style", &self.style)
486            .field("is_focused", &*self.refs.is_focused.borrow())
487            .finish()
488    }
489}
490
491// Re-export from extracted module
492use crate::text_field_handler::TextFieldHandler;
493
494impl TextFieldModifierNode {
495    /// Creates a new text field modifier node.
496    pub fn new(state: TextFieldState, style: TextStyle) -> Self {
497        let value = state.value();
498        let refs = TextFieldRefs::new();
499        let refs_line_height = refs.line_height.clone();
500        let refs_wrap_width = refs.wrap_width.clone();
501        let line_limits = TextFieldLineLimits::default();
502        let cached_handler =
503            Self::create_handler(state, refs.clone(), line_limits, style.clone(), 0);
504        let cached_pan_resolver =
505            Self::create_pan_resolver(state, refs.clone(), line_limits, style.clone());
506
507        Self {
508            state,
509            refs,
510            style,
511            cursor_brush: Brush::solid(DEFAULT_CURSOR_COLOR),
512            selection_brush: Brush::solid(DEFAULT_SELECTION_COLOR),
513            line_limits,
514            cached_text: value.text,
515            cached_selection: value.selection,
516            node_state: NodeState::new(),
517            measured_size: Rc::new(Cell::new(Size {
518                width: 0.0,
519                height: 0.0,
520            })),
521            // Alias the refs cells so the pointer handler reads the same live
522            // line-height / wrap-width the layout writes here — a tap's `y` must
523            // resolve to the same VISUAL line the renderer draws.
524            measured_line_height: refs_line_height,
525            measured_wrap_width: refs_wrap_width,
526            cached_handler,
527            cached_pan_resolver,
528            handle_controller: None,
529            modal_depth: 0,
530        }
531    }
532
533    /// Creates a node with custom line limits.
534    pub fn with_line_limits(mut self, line_limits: TextFieldLineLimits) -> Self {
535        self.line_limits = line_limits;
536        self.rebuild_cached_closures();
537        self
538    }
539
540    /// Rebuilds the closures that capture how this field is configured.
541    ///
542    /// The pointer handler and the pan resolver capture state, style, line
543    /// limits and modal depth by value, so changing any of those leaves a
544    /// closure describing the configuration the node no longer has. One place
545    /// rebuilds both from the node's own fields, and every path that changes
546    /// them ends here — a field configured while it is being constructed and
547    /// one reconfigured by a recomposition arrive at the same node.
548    fn rebuild_cached_closures(&mut self) {
549        self.cached_handler = Self::create_handler(
550            self.state,
551            self.refs.clone(),
552            self.line_limits,
553            self.style.clone(),
554            self.modal_depth,
555        );
556        self.cached_pan_resolver = Self::create_pan_resolver(
557            self.state,
558            self.refs.clone(),
559            self.line_limits,
560            self.style.clone(),
561        );
562    }
563
564    /// Installs the controller the field publishes live handle metrics to.
565    pub fn with_handle_controller(mut self, controller: TextFieldHandleController) -> Self {
566        self.handle_controller = Some(controller);
567        self
568    }
569
570    /// Creates the horizontal pan resolver closure.
571    ///
572    /// The resolver takes the content viewport width (px) and returns the
573    /// horizontal scroll offset that keeps the cursor visible, storing the
574    /// result in `refs.scroll_offset` so pointer input and rendering agree.
575    /// It recomputes from the live state so layout, the render scene builder,
576    /// and the draw closure all observe the same value within a frame.
577    fn create_pan_resolver(
578        state: TextFieldState,
579        refs: TextFieldRefs,
580        line_limits: TextFieldLineLimits,
581        style: TextStyle,
582    ) -> TextPanResolver {
583        Rc::new(move |viewport_width: f32| {
584            if !line_limits.is_single_line() {
585                // Multi-line fields do not pan horizontally.
586                refs.scroll_offset.set(0.0);
587                return 0.0;
588            }
589            let text = state.text();
590            let pos = state.selection().start.min(text.len());
591            let text_width = crate::text::measure_text(
592                &crate::text::AnnotatedString::from(text.as_str()),
593                &style,
594            )
595            .width;
596            let cursor_x = crate::text::measure_text(
597                &crate::text::AnnotatedString::from(&text[..pos]),
598                &style,
599            )
600            .width;
601            let offset = compute_horizontal_scroll_offset(
602                refs.scroll_offset.get(),
603                cursor_x,
604                text_width,
605                viewport_width,
606            );
607            refs.scroll_offset.set(offset);
608            offset
609        })
610    }
611
612    /// Returns the pan resolver for single-line fields, `None` for multi-line.
613    ///
614    /// Exposed to the modifier slices so the render scene builder can pan the
615    /// text glyphs by the same offset used for the cursor and selection.
616    pub fn text_pan_resolver(&self) -> Option<TextPanResolver> {
617        self.line_limits
618            .is_single_line()
619            .then(|| self.cached_pan_resolver.clone())
620    }
621
622    /// Returns the current horizontal scroll (pan) offset in px.
623    pub fn scroll_offset(&self) -> f32 {
624        self.refs.scroll_offset.get()
625    }
626
627    /// Returns the current line limits configuration.
628    pub fn line_limits(&self) -> TextFieldLineLimits {
629        self.line_limits
630    }
631
632    /// Creates the pointer input handler closure.
633    fn create_handler(
634        state: TextFieldState,
635        refs: TextFieldRefs,
636        line_limits: TextFieldLineLimits,
637        style: TextStyle, // Add style
638        modal_depth: usize,
639    ) -> Rc<dyn Fn(PointerEvent)> {
640        // Tap-count classification plus word/line/paragraph boundaries drive the
641        // multi-tap selection granularity gestures.
642        use crate::{
643            text_selection::{
644                classify_tap_count, find_line_boundaries, find_paragraph_boundaries,
645                resolve_selection_tap_count, tap_selection_granularity, SelectionGranularity,
646                MULTI_TAP_SLOP_PX, MULTI_TAP_TIMEOUT_MS,
647            },
648            word_boundaries::find_word_boundaries,
649        };
650
651        Rc::new(move |event: PointerEvent| {
652            // Seed the field node's window-space origin from this pointer event
653            // so the very first handle placement after a tap has a value even
654            // before the next layout pass runs. The layout pass
655            // (`window_origin_sink`) is the authoritative source that keeps it
656            // fresh as the field scrolls; both agree (`global - local` equals
657            // the composited window origin at rest).
658            refs.node_origin.set(Point {
659                x: event.global_position.x - event.position.x,
660                y: event.global_position.y - event.position.y,
661            });
662
663            // Account for content padding offsets and the horizontal pan
664            // offset (single-line fields pan to keep the cursor visible, so
665            // clicks must map back into text space).
666            let click_x =
667                (event.position.x - refs.content_offset.get() + refs.scroll_offset.get()).max(0.0);
668            let click_y = (event.position.y - refs.content_y_offset.get()).max(0.0);
669
670            match event.kind {
671                PointerEventKind::Down => {
672                    // Direct selection mechanics are source-independent:
673                    // mouse, touch and pen all expose handles and the same
674                    // continuous long-press → slide-to-menu gesture.
675                    refs.direct_manipulation.set(true);
676                    refs.press_track.set(Some(PointerPressTrack {
677                        start: event.global_position,
678                        position: event.global_position,
679                    }));
680                    refs.gesture_claimed.set(false);
681
682                    // Request focus with O(1) handler, passing node_id and line
683                    // limits for key handling plus the live geometry cells the
684                    // layout keeps fresh, so coordinate-based platform text input
685                    // (iOS caret positioning) can read the caret's window rect.
686                    let handler = TextFieldHandler::new(
687                        state,
688                        refs.node_id.get(),
689                        line_limits,
690                        crate::text_field_handler::CaretGeometryRefs {
691                            node_origin: refs.node_origin.clone(),
692                            content_offset: refs.content_offset.clone(),
693                            content_y_offset: refs.content_y_offset.clone(),
694                            scroll_offset: refs.scroll_offset.clone(),
695                            style: style.clone(),
696                        },
697                    );
698                    crate::text_field_focus::request_focus(
699                        refs.is_focused.clone(),
700                        handler,
701                        modal_depth,
702                    );
703
704                    let now = web_time::Instant::now();
705                    let text = state.text();
706                    let pos = crate::text::offset_for_position_wrapped(
707                        &text,
708                        &style,
709                        refs.node_id.get(),
710                        refs.wrap_width.get(),
711                        refs.line_height.get(),
712                        click_x,
713                        click_y,
714                    );
715
716                    // Classify the press into a 1-based tap count by both the
717                    // time since and the distance from the previous press (a tap
718                    // far from the last one starts a fresh single tap, matching
719                    // Android's double-tap slop).
720                    let previous = refs.last_click_pos.get().and_then(|(px, py)| {
721                        let count = refs.click_count.get();
722                        (count > 0).then_some((count, px, py))
723                    });
724                    let elapsed_ms = refs
725                        .last_click_time
726                        .get()
727                        .map(|last| now.duration_since(last).as_millis())
728                        .unwrap_or(u128::MAX);
729                    let tap_count = classify_tap_count(
730                        previous,
731                        elapsed_ms,
732                        event.position.x,
733                        event.position.y,
734                        MULTI_TAP_TIMEOUT_MS,
735                        MULTI_TAP_SLOP_PX,
736                    );
737
738                    // A lone tap that lands INSIDE an existing (non-collapsed)
739                    // selection selects the word under the finger (Android/iOS
740                    // "tap the selection to re-grab a word"). Tapping the SAME
741                    // spot again grows the granularity word → line → paragraph →
742                    // word …, keyed on location so it keeps escalating even when
743                    // the taps arrive too slowly to count as a rapid multi-tap.
744                    // A lone tap elsewhere just places the caret.
745                    let selection = state.selection();
746                    let tap_in_selection =
747                        !selection.collapsed() && pos >= selection.min() && pos <= selection.max();
748                    // Same-spot repeat, independent of the multi-tap timeout:
749                    // within slop of the previous press.
750                    let repeat_in_place = refs
751                        .last_click_pos
752                        .get()
753                        .map(|(px, py)| {
754                            let dx = event.position.x - px;
755                            let dy = event.position.y - py;
756                            dx * dx + dy * dy <= MULTI_TAP_SLOP_PX * MULTI_TAP_SLOP_PX
757                        })
758                        .unwrap_or(false);
759                    let effective_count = resolve_selection_tap_count(
760                        tap_count,
761                        refs.click_count.get(),
762                        tap_in_selection,
763                        repeat_in_place,
764                    );
765
766                    match tap_selection_granularity(effective_count) {
767                        SelectionGranularity::Paragraph => {
768                            // Fourth tap: grow to the whole paragraph.
769                            let (start, end) = find_paragraph_boundaries(&text, pos);
770                            state.edit(|buffer| {
771                                buffer.select(TextRange::new(start, end));
772                            });
773                            refs.drag_anchor.set(Some(start));
774                        }
775                        SelectionGranularity::Line => {
776                            // Triple tap: select the line.
777                            let (line_start, line_end) = find_line_boundaries(&text, pos);
778                            state.edit(|buffer| {
779                                buffer.select(TextRange::new(line_start, line_end));
780                            });
781                            refs.drag_anchor.set(Some(line_start));
782                        }
783                        SelectionGranularity::Word => {
784                            // Double tap (or a tap inside an existing selection):
785                            // select the word.
786                            let (word_start, word_end) = find_word_boundaries(&text, pos);
787                            state.edit(|buffer| {
788                                buffer.select(TextRange::new(word_start, word_end));
789                            });
790                            refs.drag_anchor.set(Some(word_start));
791                        }
792                        SelectionGranularity::Caret => {
793                            // Single tap: place the cursor.
794                            refs.drag_anchor.set(Some(pos));
795                            state.edit(|buffer| {
796                                buffer.place_cursor_before_char(pos);
797                            });
798                        }
799                    }
800
801                    refs.click_count.set(effective_count);
802                    refs.last_click_time.set(Some(now));
803                    refs.last_click_pos
804                        .set(Some((event.position.x, event.position.y)));
805                    event.consume();
806                }
807                PointerEventKind::Move => {
808                    // Keep the live press stream fresh for the widget layer.
809                    if let Some(mut track) = refs.press_track.get() {
810                        track.position = event.global_position;
811                        refs.press_track.set(Some(track));
812                        crate::request_render_invalidation();
813                    }
814                    // A claimed gesture belongs to the widget's menu slide:
815                    // the node must not keep drag-selecting under it.
816                    if refs.gesture_claimed.get() {
817                        event.consume();
818                        return;
819                    }
820                    // If we have a drag anchor, extend selection during drag
821                    if let Some(anchor) = refs.drag_anchor.get() {
822                        if *refs.is_focused.borrow() {
823                            let text = state.text();
824                            let current_pos = crate::text::offset_for_position_wrapped(
825                                &text,
826                                &style,
827                                refs.node_id.get(),
828                                refs.wrap_width.get(),
829                                refs.line_height.get(),
830                                click_x,
831                                click_y,
832                            );
833
834                            // Update selection directly (without undo stack push)
835                            state.set_selection(TextRange::new(anchor, current_pos));
836
837                            // Selection change only needs redraw, not layout
838                            crate::request_render_invalidation();
839
840                            event.consume();
841                        }
842                    }
843                }
844                PointerEventKind::Up => {
845                    // Clear drag anchor on mouse up
846                    refs.drag_anchor.set(None);
847                    refs.press_track.set(None);
848                    refs.gesture_claimed.set(false);
849                    // The contextual menu reads the live press through metrics
850                    // published during drawing. Ensure the release reaches that
851                    // channel even when no visual state changed in the field
852                    // itself, so a continuous hold, slide, and release can run
853                    // the hovered menu action.
854                    crate::request_render_invalidation();
855                }
856                PointerEventKind::Cancel => {
857                    refs.press_track.set(None);
858                    refs.gesture_claimed.set(false);
859                    crate::request_render_invalidation();
860                }
861                _ => {}
862            }
863        })
864    }
865
866    /// Creates a node with a custom accent: the caret is drawn solid in
867    /// `color` and the selection highlight is derived from it at
868    /// [`crate::widgets::SELECTION_HIGHLIGHT_ALPHA`] — the reference field
869    /// tints caret, handles and highlight from the one accent.
870    pub fn with_cursor_color(mut self, color: Color) -> Self {
871        self.cursor_brush = Brush::solid(color);
872        self.selection_brush = Brush::solid(
873            color.with_alpha(crate::widgets::basic_text_field::SELECTION_HIGHLIGHT_ALPHA),
874        );
875        self
876    }
877
878    /// Sets the focus state.
879    pub fn set_focused(&mut self, focused: bool) {
880        let current = *self.refs.is_focused.borrow();
881        if current != focused {
882            *self.refs.is_focused.borrow_mut() = focused;
883            if !focused {
884                self.refs.direct_manipulation.set(false);
885                self.refs.press_track.set(None);
886                self.refs.gesture_claimed.set(false);
887            }
888        }
889    }
890
891    /// Returns whether the field is focused.
892    pub fn is_focused(&self) -> bool {
893        *self.refs.is_focused.borrow()
894    }
895
896    /// Returns the shared cell the field's composited window origin is written
897    /// into (window coordinates of the field node's top-left).
898    ///
899    /// The layout pass writes the field's TRUE on-screen origin here every frame
900    /// — resolved through all ancestor placements (a scrolling `LazyColumn` /
901    /// `vertical_scroll` offsets its items via placement, which the layout tree
902    /// bakes into each node's absolute rect) plus ancestor graphics-layer
903    /// translations. The draw closure reads it back to publish handle metrics,
904    /// so the finger selection/cursor handles anchor at (and their window→offset
905    /// inverse mapping agrees with) the field's real glyphs even while the list
906    /// scrolls. Without this the origin was only ever sampled from the last
907    /// pointer event and went stale the moment the field scrolled.
908    pub(crate) fn window_origin_sink(&self) -> Rc<Cell<Point>> {
909        self.refs.node_origin.clone()
910    }
911
912    /// Returns the current text.
913    pub fn text(&self) -> String {
914        self.state.text()
915    }
916
917    pub fn style(&self) -> &TextStyle {
918        &self.style
919    }
920
921    /// Returns the current selection.
922    pub fn selection(&self) -> TextRange {
923        self.state.selection()
924    }
925
926    /// Returns the cursor brush for rendering.
927    pub fn cursor_brush(&self) -> Brush {
928        self.cursor_brush.clone()
929    }
930
931    /// Returns the selection brush for rendering selection highlight.
932    pub fn selection_brush(&self) -> Brush {
933        self.selection_brush.clone()
934    }
935
936    /// Inserts text at the current cursor position (for paste operations).
937    pub fn insert_text(&mut self, text: &str) {
938        self.state.edit(|buffer| {
939            buffer.insert(text);
940        });
941    }
942
943    /// Copies the selected text and returns it (for web copy operation).
944    /// Returns None if no selection.
945    pub fn copy_selection(&self) -> Option<String> {
946        self.state.copy_selection()
947    }
948
949    /// Cuts the selected text: copies and deletes it.
950    /// Returns the cut text, or None if no selection.
951    pub fn cut_selection(&mut self) -> Option<String> {
952        let text = self.copy_selection();
953        if text.is_some() {
954            self.state.edit(|buffer| {
955                buffer.delete(buffer.selection());
956            });
957        }
958        text
959    }
960
961    /// Updates the content offset (padding.left) for accurate click-to-position cursor placement.
962    /// Called from slices collection where padding is known.
963    pub fn set_content_offset(&self, offset: f32) {
964        self.refs.content_offset.set(offset);
965    }
966
967    /// Updates the content Y offset (padding.top) for cursor Y positioning.
968    /// Called from slices collection where padding is known.
969    pub fn set_content_y_offset(&self, offset: f32) {
970        self.refs.content_y_offset.set(offset);
971    }
972
973    /// The wrap width a multi-line field lays its text out at, or `None` when
974    /// the text must not wrap (single-line fields pan horizontally instead).
975    ///
976    /// Multi-line fields wrap at the available content width exactly like the
977    /// render scene builder, so the measured height reflects every wrapped line
978    /// and the field grows to fit its content instead of clipping it.
979    fn wrap_width(&self, available_width: f32) -> Option<f32> {
980        (!self.line_limits.is_single_line() && available_width.is_finite() && available_width > 0.0)
981            .then_some(available_width)
982    }
983
984    /// Measures the text content using node-identity-based caching.
985    ///
986    /// `wrap_width` bounds the layout width so multi-line text wraps; `None`
987    /// measures the natural single-line width (single-line fields, intrinsic
988    /// width queries).
989    fn measure_text_content(&self, wrap_width: Option<f32>) -> Size {
990        let text = self.state.text();
991        let node_id = self.refs.node_id.get();
992        let annotated = crate::text::AnnotatedString::from(text.as_str());
993        let metrics = match wrap_width {
994            Some(max_width) => crate::text::measure_text_with_options_for_node(
995                node_id,
996                &annotated,
997                &self.style,
998                crate::text::TextLayoutOptions::default(),
999                Some(max_width),
1000            ),
1001            None => crate::text::measure_text_for_node(node_id, &annotated, &self.style),
1002        };
1003        self.measured_line_height.set(metrics.line_height);
1004        Size {
1005            width: metrics.width,
1006            height: metrics.height,
1007        }
1008    }
1009
1010    /// Updates cached state and returns true if changed.
1011    fn update_cached_state(&mut self) -> bool {
1012        let value = self.state.value();
1013        let text_changed = value.text != self.cached_text;
1014        let selection_changed = value.selection != self.cached_selection;
1015
1016        if text_changed {
1017            self.cached_text = value.text;
1018        }
1019        if selection_changed {
1020            self.cached_selection = value.selection;
1021        }
1022
1023        text_changed || selection_changed
1024    }
1025
1026    // NOTE: Key event handling is done via TextFieldHandler::handle_key() which is
1027    // registered with the focus system for O(1) dispatch. DO NOT add a handle_key_event()
1028    // method here - it would be duplicate code that never gets called.
1029}
1030
1031impl DelegatableNode for TextFieldModifierNode {
1032    fn node_state(&self) -> &NodeState {
1033        &self.node_state
1034    }
1035}
1036
1037impl ModifierNode for TextFieldModifierNode {
1038    fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
1039        // Store node_id for scoped layout invalidation (avoids O(app) global invalidation)
1040        self.refs.node_id.set(context.node_id());
1041
1042        context.invalidate(InvalidationKind::Layout);
1043        context.invalidate(InvalidationKind::Draw);
1044        context.invalidate(InvalidationKind::Semantics);
1045    }
1046
1047    fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
1048        Some(self)
1049    }
1050
1051    fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
1052        Some(self)
1053    }
1054
1055    fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
1056        Some(self)
1057    }
1058
1059    fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
1060        Some(self)
1061    }
1062
1063    fn as_semantics_node(&self) -> Option<&dyn SemanticsNode> {
1064        Some(self)
1065    }
1066
1067    fn as_semantics_node_mut(&mut self) -> Option<&mut dyn SemanticsNode> {
1068        Some(self)
1069    }
1070
1071    fn as_pointer_input_node(&self) -> Option<&dyn PointerInputNode> {
1072        Some(self)
1073    }
1074
1075    fn as_pointer_input_node_mut(&mut self) -> Option<&mut dyn PointerInputNode> {
1076        Some(self)
1077    }
1078}
1079
1080impl LayoutModifierNode for TextFieldModifierNode {
1081    fn measure(
1082        &self,
1083        _context: &mut dyn ModifierNodeContext,
1084        _measurable: &dyn Measurable,
1085        constraints: Constraints,
1086    ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
1087        // Measure the text content, wrapping multi-line fields at the available
1088        // width so the field grows to fit every wrapped line instead of
1089        // clipping content past the first line.
1090        let wrap_width = self.wrap_width(constraints.max_width);
1091        // Remember the wrap width so the draw closure can resolve the same
1092        // visual (wrapped) lines when placing the caret and selection handles.
1093        self.measured_wrap_width.set(wrap_width);
1094        let text_size = self.measure_text_content(wrap_width);
1095
1096        // Add minimum height for empty text (cursor needs space)
1097        let min_height = if text_size.height < 1.0 {
1098            DEFAULT_LINE_HEIGHT
1099        } else {
1100            text_size.height
1101        };
1102
1103        // Constrain to provided constraints
1104        let width = text_size
1105            .width
1106            .max(constraints.min_width)
1107            .min(constraints.max_width);
1108        let height = min_height
1109            .max(constraints.min_height)
1110            .min(constraints.max_height);
1111
1112        let size = Size { width, height };
1113        self.measured_size.set(size);
1114
1115        // Refresh the horizontal pan offset so it is up to date for pointer
1116        // input and rendering even before the next draw pass runs.
1117        let _ = (self.cached_pan_resolver)(size.width);
1118
1119        cranpose_ui_layout::LayoutModifierMeasureResult::with_size(size)
1120    }
1121
1122    fn min_intrinsic_width(&self, _measurable: &dyn Measurable, _height: f32) -> f32 {
1123        self.measure_text_content(None).width
1124    }
1125
1126    fn max_intrinsic_width(&self, _measurable: &dyn Measurable, _height: f32) -> f32 {
1127        self.measure_text_content(None).width
1128    }
1129
1130    fn min_intrinsic_height(&self, _measurable: &dyn Measurable, width: f32) -> f32 {
1131        self.measure_text_content(self.wrap_width(width))
1132            .height
1133            .max(DEFAULT_LINE_HEIGHT)
1134    }
1135
1136    fn max_intrinsic_height(&self, _measurable: &dyn Measurable, width: f32) -> f32 {
1137        self.measure_text_content(self.wrap_width(width))
1138            .height
1139            .max(DEFAULT_LINE_HEIGHT)
1140    }
1141}
1142
1143/// Content viewport (excludes padding), falling back to the node size when
1144/// measurement has not run yet. Shared by the field's behind (selection
1145/// highlight) and overlay (caret, IME underline) draw closures.
1146fn content_viewport(
1147    measured: cranpose_ui_graphics::Size,
1148    size: cranpose_foundation::Size,
1149    padding_left: f32,
1150    padding_top: f32,
1151) -> (f32, f32) {
1152    let width = if measured.width > 0.0 {
1153        measured.width
1154    } else {
1155        (size.width - padding_left).max(0.0)
1156    };
1157    let height = if measured.height > 0.0 {
1158        measured.height
1159    } else {
1160        (size.height - padding_top).max(0.0)
1161    };
1162    (width, height)
1163}
1164
1165impl DrawModifierNode for TextFieldModifierNode {
1166    fn draw(&self, _draw_scope: &mut dyn DrawScope) {
1167        // No-op: Cursor and selection are rendered via create_draw_closure() which
1168        // creates DrawPrimitive::Rect directly. This enables draw-time evaluation
1169        // of focus state and cursor blink timing.
1170    }
1171
1172    fn create_draw_closure(
1173        &self,
1174    ) -> Option<Rc<dyn Fn(&mut cranpose_ui_graphics::DrawScopeDefault)>> {
1175        use cranpose_ui_graphics::{DrawPrimitive, DrawScope as _};
1176
1177        // Capture state via Rc clone (cheap) for draw-time evaluation
1178        let is_focused = self.refs.is_focused.clone();
1179        let state = self.state;
1180        let content_offset = self.refs.content_offset.clone();
1181        let content_y_offset = self.refs.content_y_offset.clone();
1182        let cursor_brush = self.cursor_brush.clone();
1183        let style = self.style.clone();
1184        let cached_line_height = self.measured_line_height.clone();
1185        let measured_size = self.measured_size.clone();
1186        let measured_wrap_width = self.measured_wrap_width.clone();
1187        let node_id = self.refs.node_id.clone();
1188        let pan_resolver = self.cached_pan_resolver.clone();
1189        let handle_controller = self.handle_controller.clone();
1190        let node_origin = self.refs.node_origin.clone();
1191        let direct_manipulation = self.refs.direct_manipulation.clone();
1192        let press_track = self.refs.press_track;
1193        let gesture_claimed = self.refs.gesture_claimed.clone();
1194
1195        Some(Rc::new(move |scope| {
1196            let size = scope.size();
1197            // Check focus at DRAW time
1198            if !*is_focused.borrow() {
1199                // Publish an unfocused snapshot so the composable clears any
1200                // finger handles when the field loses focus.
1201                if let Some(controller) = &handle_controller {
1202                    controller.publish(TextFieldHandleMetrics {
1203                        focused: false,
1204                        direct_manipulation: false,
1205                        node_origin: node_origin.get(),
1206                        padding_left: 0.0,
1207                        padding_top: 0.0,
1208                        scroll_offset: 0.0,
1209                        line_height: cached_line_height.get(),
1210                        glyph_box: crate::text::glyph_line_box(&style, cached_line_height.get()),
1211                        wrap_width: measured_wrap_width.get(),
1212                    });
1213                }
1214                return;
1215            }
1216
1217            let mut primitives = Vec::new();
1218
1219            let text = state.text();
1220            let selection = state.selection();
1221            let padding_left = content_offset.get();
1222            let padding_top = content_y_offset.get();
1223            // Reuse line_height from the most recent layout measurement
1224            // instead of re-measuring the full text.
1225            let line_height = cached_line_height.get();
1226
1227            let (viewport_width, viewport_height) =
1228                content_viewport(measured_size.get(), size, padding_left, padding_top);
1229            // Horizontal pan that keeps the cursor visible (0 for multi-line).
1230            let pan = pan_resolver(viewport_width);
1231
1232            // Publish live geometry so the `BasicTextField` composable can place
1233            // and drive the finger selection handles.
1234            if let Some(controller) = &handle_controller {
1235                controller.adopt_gesture_claim(&gesture_claimed);
1236                controller.adopt_press_track(press_track);
1237                controller.publish(TextFieldHandleMetrics {
1238                    focused: true,
1239                    direct_manipulation: direct_manipulation.get(),
1240                    node_origin: node_origin.get(),
1241                    padding_left,
1242                    padding_top,
1243                    scroll_offset: pan,
1244                    line_height,
1245                    glyph_box: crate::text::glyph_line_box(&style, line_height),
1246                    wrap_width: measured_wrap_width.get(),
1247                });
1248            }
1249            // Everything the field draws (selection, IME underline, cursor)
1250            // is clipped to the content viewport so primitives never extend
1251            // outside the field bounds.
1252            let clip_bounds = cranpose_ui_graphics::Rect {
1253                x: padding_left,
1254                y: padding_top,
1255                width: viewport_width,
1256                height: viewport_height,
1257            };
1258
1259            // (The selection highlight renders BEHIND the glyphs — see
1260            // create_behind_draw_closure; a translucent fill over the text
1261            // tinted the selected glyphs.)
1262
1263            // Draw composition (IME preedit) underline
1264            // This shows the user which text is being composed by the input method
1265            if let Some(comp_range) = state.composition() {
1266                let comp_start = comp_range.min();
1267                let comp_end = comp_range.max();
1268
1269                if comp_start < comp_end && comp_end <= text.len() {
1270                    // Underline color: slightly transparent white/gray
1271                    let underline_brush = cranpose_ui_graphics::Brush::solid(
1272                        cranpose_ui_graphics::Color(0.8, 0.8, 0.8, 0.8),
1273                    );
1274                    let underline_height: f32 = 2.0;
1275
1276                    // Per-visual-line rects, shrunk to a strip at the bottom of
1277                    // each line — same wrap-aware layout as the selection.
1278                    for line_rect in range_visual_line_rects(
1279                        &text,
1280                        &style,
1281                        node_id.get(),
1282                        measured_wrap_width.get(),
1283                        padding_left,
1284                        padding_top,
1285                        pan,
1286                        line_height,
1287                        comp_start,
1288                        comp_end,
1289                    ) {
1290                        let underline_rect = cranpose_ui_graphics::Rect {
1291                            x: line_rect.x,
1292                            y: line_rect.y + line_height - underline_height,
1293                            width: line_rect.width,
1294                            height: underline_height,
1295                        };
1296                        if let Some(clipped) = intersect_rect(underline_rect, clip_bounds) {
1297                            primitives.push(DrawPrimitive::Rect {
1298                                rect: clipped,
1299                                brush: underline_brush.clone(),
1300                                stroke: None,
1301                            });
1302                        }
1303                    }
1304                }
1305            }
1306
1307            // Draw cursor - check visibility at DRAW time for blinking. The
1308            // caret exists only for a collapsed selection: with a range
1309            // selected the edges are marked by the finger handles, and a
1310            // caret drawn at the range start just thickens the start
1311            // handle's stem.
1312            if selection.collapsed() && crate::cursor_animation::is_cursor_visible() {
1313                let pos = selection.start.min(text.len());
1314                // Resolve the caret's VISUAL (wrapped) line so it lands on the
1315                // same glyph the renderer draws — the field wraps long lines, and
1316                // counting only logical `\n` lines would draw the caret on the
1317                // wrong line (and, with the full logical-line-prefix width, off
1318                // the right edge) while typing/the magnifier stay correct.
1319                // Upstream affinity: a caret placed by a finger at a wrapped
1320                // line's right edge draws at that line's end, not one line
1321                // down at the left edge (matching the cursor handle's anchor).
1322                let (line_index, line_start) = caret_visual_line_for_offset(
1323                    &text,
1324                    &style,
1325                    node_id.get(),
1326                    measured_wrap_width.get(),
1327                    pos,
1328                    crate::text_selection::LineAffinity::Upstream,
1329                );
1330                let cursor_x = crate::text::measure_text(
1331                    &crate::text::AnnotatedString::from(&text[line_start..pos]),
1332                    &style,
1333                )
1334                .width
1335                    + padding_left
1336                    - pan;
1337                // The caret spans the tight glyph box, not the paragraph
1338                // slot — the reference caret's ends ride the glyph extents.
1339                let (box_off, box_h) = crate::text::glyph_line_box(&style, line_height);
1340                let cursor_y = padding_top + line_index as f32 * line_height + box_off;
1341
1342                let cursor_rect = cranpose_ui_graphics::Rect {
1343                    x: cursor_x,
1344                    y: cursor_y,
1345                    width: CURSOR_WIDTH,
1346                    height: box_h,
1347                };
1348
1349                if let Some(clipped) = intersect_rect(cursor_rect, clip_bounds) {
1350                    primitives.push(DrawPrimitive::Rect {
1351                        rect: clipped,
1352                        brush: cursor_brush.clone(),
1353                        stroke: None,
1354                    });
1355                }
1356            }
1357
1358            scope.push_recorded(primitives);
1359        }))
1360    }
1361
1362    fn create_behind_draw_closure(
1363        &self,
1364    ) -> Option<Rc<dyn Fn(&mut cranpose_ui_graphics::DrawScopeDefault)>> {
1365        use cranpose_ui_graphics::{DrawPrimitive, DrawScope as _};
1366
1367        let is_focused = self.refs.is_focused.clone();
1368        let state = self.state;
1369        let content_offset = self.refs.content_offset.clone();
1370        let content_y_offset = self.refs.content_y_offset.clone();
1371        let selection_brush = self.selection_brush.clone();
1372        let style = self.style.clone();
1373        let cached_line_height = self.measured_line_height.clone();
1374        let measured_size = self.measured_size.clone();
1375        let measured_wrap_width = self.measured_wrap_width.clone();
1376        let node_id = self.refs.node_id.clone();
1377        let pan_resolver = self.cached_pan_resolver.clone();
1378
1379        Some(Rc::new(move |scope| {
1380            let size = scope.size();
1381            if !*is_focused.borrow() {
1382                return;
1383            }
1384            let selection = state.selection();
1385            if selection.collapsed() {
1386                return;
1387            }
1388            let text = state.text();
1389            let padding_left = content_offset.get();
1390            let padding_top = content_y_offset.get();
1391            let line_height = cached_line_height.get();
1392            let (viewport_width, viewport_height) =
1393                content_viewport(measured_size.get(), size, padding_left, padding_top);
1394            let pan = pan_resolver(viewport_width);
1395            let clip_bounds = cranpose_ui_graphics::Rect {
1396                x: padding_left,
1397                y: padding_top,
1398                width: viewport_width,
1399                height: viewport_height,
1400            };
1401
1402            // Highlight per VISUAL (wrapped) line so it lands on the same
1403            // glyphs the renderer draws — BENEATH them (the reference keeps
1404            // selected glyphs unblended white over the tint).
1405            let mut primitives = Vec::new();
1406            // Highlight rects hug the tight glyph box of each line — the
1407            // reference selection shows GAPS between lines when the
1408            // paragraph line height exceeds the natural text height.
1409            let (box_off, box_h) = crate::text::glyph_line_box(&style, line_height);
1410            for sel_rect in range_visual_line_rects(
1411                &text,
1412                &style,
1413                node_id.get(),
1414                measured_wrap_width.get(),
1415                padding_left,
1416                padding_top,
1417                pan,
1418                line_height,
1419                selection.min(),
1420                selection.max(),
1421            ) {
1422                let sel_rect = cranpose_ui_graphics::Rect {
1423                    y: sel_rect.y + box_off,
1424                    height: box_h,
1425                    ..sel_rect
1426                };
1427                if let Some(clipped) = intersect_rect(sel_rect, clip_bounds) {
1428                    primitives.push(DrawPrimitive::Rect {
1429                        rect: clipped,
1430                        brush: selection_brush.clone(),
1431                        stroke: None,
1432                    });
1433                }
1434            }
1435            scope.push_recorded(primitives);
1436        }))
1437    }
1438}
1439
1440impl SemanticsNode for TextFieldModifierNode {
1441    fn merge_semantics(&self, config: &mut SemanticsConfiguration) {
1442        let text = self.state.text();
1443        config.content_description = Some(text);
1444        config.is_editable_text = true;
1445        config.text_selection = Some(self.state.selection());
1446    }
1447}
1448
1449impl PointerInputNode for TextFieldModifierNode {
1450    fn on_pointer_event(
1451        &mut self,
1452        _context: &mut dyn ModifierNodeContext,
1453        _event: &PointerEvent,
1454    ) -> bool {
1455        // No-op: All pointer handling is done via pointer_input_handler() closure.
1456        // This follows Jetpack Compose's delegation pattern where the node simply
1457        // forwards to a delegated pointer input handler (see TextFieldDecoratorModifier.kt:741-747).
1458        //
1459        // The cached_handler closure handles:
1460        // - Focus request on Down
1461        // - Cursor positioning
1462        // - Double-click word selection
1463        // - Triple-click select all
1464        // - Drag selection
1465        false
1466    }
1467
1468    fn hit_test(&self, x: f32, y: f32) -> bool {
1469        // Check if point is within measured bounds
1470        let size = self.measured_size.get();
1471        x >= 0.0 && x <= size.width && y >= 0.0 && y <= size.height
1472    }
1473
1474    fn pointer_input_handler(&self) -> Option<Rc<dyn Fn(PointerEvent)>> {
1475        // Return cached handler for pointer input dispatch
1476        Some(self.cached_handler.clone())
1477    }
1478}
1479
1480// ============================================================================
1481// TextFieldElement - Creates and updates TextFieldModifierNode
1482// ============================================================================
1483
1484/// Element that creates and updates `TextFieldModifierNode` instances.
1485///
1486/// This follows the modifier element pattern where the element is responsible for:
1487/// - Creating new nodes (via `create`)
1488/// - Updating existing nodes when properties change (via `update`)
1489/// - Declaring capabilities (LAYOUT | DRAW | SEMANTICS)
1490#[derive(Clone)]
1491pub struct TextFieldElement {
1492    /// The text field state
1493    state: TextFieldState,
1494    /// Text style
1495    style: TextStyle,
1496    /// Cursor color
1497    cursor_color: Color,
1498    /// Line limits configuration
1499    line_limits: TextFieldLineLimits,
1500    /// Channel the node publishes live handle metrics to (finger selection
1501    /// handles). `None` disables handle support.
1502    handle_controller: Option<TextFieldHandleController>,
1503    /// The [`crate::modal::local_modal_depth`] this field was composed at.
1504    modal_depth: usize,
1505}
1506
1507impl TextFieldElement {
1508    /// Creates a new text field element.
1509    pub fn new(state: TextFieldState, style: TextStyle) -> Self {
1510        Self {
1511            state,
1512            style,
1513            cursor_color: DEFAULT_CURSOR_COLOR,
1514            line_limits: TextFieldLineLimits::default(),
1515            handle_controller: None,
1516            modal_depth: 0,
1517        }
1518    }
1519
1520    /// Creates an element with custom cursor color.
1521    pub fn with_cursor_color(mut self, color: Color) -> Self {
1522        self.cursor_color = color;
1523        self
1524    }
1525
1526    /// Creates an element with custom line limits.
1527    pub fn with_line_limits(mut self, line_limits: TextFieldLineLimits) -> Self {
1528        self.line_limits = line_limits;
1529        self
1530    }
1531
1532    /// Installs the finger-handle metrics channel shared with the composable.
1533    pub fn with_handle_controller(mut self, controller: TextFieldHandleController) -> Self {
1534        self.handle_controller = Some(controller);
1535        self
1536    }
1537
1538    /// Sets the modal depth this field was composed at (see
1539    /// [`crate::modal::local_modal_depth`]).
1540    pub fn with_modal_depth(mut self, depth: usize) -> Self {
1541        self.modal_depth = depth;
1542        self
1543    }
1544}
1545
1546impl std::fmt::Debug for TextFieldElement {
1547    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1548        f.debug_struct("TextFieldElement")
1549            .field("text", &self.state.text())
1550            .field("style", &self.style)
1551            .field("cursor_color", &self.cursor_color)
1552            .finish()
1553    }
1554}
1555
1556impl Hash for TextFieldElement {
1557    fn hash<H: Hasher>(&self, state: &mut H) {
1558        // Hash by state Rc pointer identity - matches PartialEq
1559        // This ensures equal elements hash equal (correctness requirement)
1560        self.state.id().hash(state);
1561        // Hash cursor color
1562        self.cursor_color.0.to_bits().hash(state);
1563        self.cursor_color.1.to_bits().hash(state);
1564        self.cursor_color.2.to_bits().hash(state);
1565        self.cursor_color.3.to_bits().hash(state);
1566        self.style.render_hash().hash(state);
1567        self.line_limits.hash(state);
1568        self.modal_depth.hash(state);
1569    }
1570}
1571
1572impl PartialEq for TextFieldElement {
1573    fn eq(&self, other: &Self) -> bool {
1574        // Compare by state identity (same Rc), cursor color, and line limits
1575        // This ensures node reuse when same state is passed, while detecting
1576        // actual changes that require updates
1577        self.state == other.state
1578            && self.style == other.style
1579            && self.cursor_color == other.cursor_color
1580            && self.line_limits == other.line_limits
1581            && self.modal_depth == other.modal_depth
1582    }
1583}
1584
1585impl Eq for TextFieldElement {}
1586
1587impl ModifierNodeElement for TextFieldElement {
1588    type Node = TextFieldModifierNode;
1589
1590    fn create(&self) -> Self::Node {
1591        let mut node = TextFieldModifierNode::new(self.state, self.style.clone())
1592            .with_cursor_color(self.cursor_color)
1593            .with_line_limits(self.line_limits);
1594        node.modal_depth = self.modal_depth;
1595        if let Some(controller) = self.handle_controller.clone() {
1596            node = node.with_handle_controller(controller);
1597        }
1598        node.rebuild_cached_closures();
1599        node
1600    }
1601
1602    fn update(&self, node: &mut Self::Node) {
1603        // Update the state reference
1604        node.state = self.state;
1605        node.style = self.style.clone();
1606        node.cursor_brush = Brush::solid(self.cursor_color);
1607        node.line_limits = self.line_limits;
1608        node.handle_controller = self.handle_controller.clone();
1609        node.modal_depth = self.modal_depth;
1610        node.rebuild_cached_closures();
1611
1612        // Check if content changed and update cache
1613        if node.update_cached_state() {
1614            // Content changed - node will need layout/draw invalidation
1615            // This happens automatically through the modifier reconciliation
1616        }
1617    }
1618
1619    fn capabilities(&self) -> NodeCapabilities {
1620        NodeCapabilities::LAYOUT
1621            | NodeCapabilities::DRAW
1622            | NodeCapabilities::SEMANTICS
1623            | NodeCapabilities::POINTER_INPUT
1624    }
1625
1626    fn always_update(&self) -> bool {
1627        // Always update to capture new state/handler while preserving focus state
1628        true
1629    }
1630}
1631
1632#[cfg(test)]
1633mod tests {
1634    use std::sync::Arc;
1635
1636    use cranpose_core::{DefaultScheduler, Runtime};
1637
1638    use super::*;
1639    use crate::text::TextStyle;
1640
1641    /// Sets up a test runtime and keeps it alive for the duration of the test.
1642    fn with_test_runtime<T>(f: impl FnOnce() -> T) -> T {
1643        let _runtime = Runtime::new(Arc::new(DefaultScheduler));
1644        f()
1645    }
1646
1647    #[test]
1648    fn text_field_node_creation() {
1649        let _app_context = crate::render_state::app_context_test_scope();
1650        with_test_runtime(|| {
1651            let state = TextFieldState::new("Hello");
1652            let node = TextFieldModifierNode::new(state, TextStyle::default());
1653            assert_eq!(node.text(), "Hello");
1654            assert!(!node.is_focused());
1655        });
1656    }
1657
1658    // Regression: a selection (or preedit) whose logical line sits *below* a
1659    // soft-wrapped line must highlight on the correct VISUAL line. The old
1660    // logical-`\n` split placed it one line too high whenever a line above
1661    // wrapped — the reported "correct x, wrong y line" iOS selection bug.
1662    #[test]
1663    fn selection_rects_follow_wrapped_visual_lines() {
1664        let _app_context = crate::render_state::app_context_test_scope();
1665        // Monospaced test measurer: 14.0 * 0.6 = 8.4 px per char. Wrap width 30
1666        // fits 3 chars (25.2) but not 4 (33.6), so "aaaaa" wraps to "aaa"/"aa".
1667        let text = "aaaaa\nbb";
1668        let style = TextStyle::default();
1669        let line_height = 10.0_f32;
1670
1671        // Select "bb" — logical line 1, but VISUAL line 2 (two visual lines
1672        // above it: "aaa", "aa").
1673        let rects = range_visual_line_rects(
1674            text,
1675            &style,
1676            None,
1677            Some(30.0),
1678            0.0,
1679            0.0,
1680            0.0,
1681            line_height,
1682            6,
1683            8,
1684        );
1685        assert_eq!(rects.len(), 1, "one visual line touched, got {rects:?}");
1686        assert_eq!(
1687            rects[0].y,
1688            2.0 * line_height,
1689            "highlight must land on visual line 2, not logical line 1"
1690        );
1691        assert!(rects[0].width > 0.0);
1692
1693        // A selection spanning the wrap boundary produces one rect per visual
1694        // line, at consecutive y positions.
1695        let spanning = range_visual_line_rects(
1696            text,
1697            &style,
1698            None,
1699            Some(30.0),
1700            0.0,
1701            0.0,
1702            0.0,
1703            line_height,
1704            0,
1705            5,
1706        );
1707        assert_eq!(spanning.len(), 2, "wrapped line spans two visual rows");
1708        assert_eq!(spanning[0].y, 0.0);
1709        assert_eq!(spanning[1].y, line_height);
1710    }
1711
1712    // Regression: a finger tap must resolve to the byte offset on the VISUAL
1713    // (wrapped) line under the finger. The measurer's plain get_offset_for_position
1714    // maps `y` through logical `\n` lines only, so on wrapped text the caret
1715    // landed below the finger — the reported "taps miss the y coordinate" bug.
1716    #[test]
1717    fn tap_resolves_offset_on_wrapped_visual_line() {
1718        let _app_context = crate::render_state::app_context_test_scope();
1719        // Same fixture: wrap width 30 splits "aaaaa" into "aaa"/"aa"; "bb" is the
1720        // third visual line. line_height 10 → line 2 spans y in [20, 30).
1721        let text = "aaaaa\nbb";
1722        let style = TextStyle::default();
1723        let line_height = 10.0_f32;
1724
1725        // Tap on visual line 2 ("bb") must land in bytes 6..=8, not in the
1726        // wrapped first logical line.
1727        let off = crate::text::offset_for_position_wrapped(
1728            text,
1729            &style,
1730            None,
1731            Some(30.0),
1732            line_height,
1733            8.0,
1734            22.0,
1735        );
1736        assert!(
1737            (6..=8).contains(&off),
1738            "tap on visual line 'bb' resolved to {off}, expected 6..=8"
1739        );
1740
1741        // Tap on visual line 1 (the "aa" continuation of the first logical line)
1742        // must land in bytes 3..=5.
1743        let off1 = crate::text::offset_for_position_wrapped(
1744            text,
1745            &style,
1746            None,
1747            Some(30.0),
1748            line_height,
1749            4.0,
1750            12.0,
1751        );
1752        assert!(
1753            (3..=5).contains(&off1),
1754            "tap on wrapped 'aa' resolved to {off1}, expected 3..=5"
1755        );
1756
1757        // Single-line (no wrap width): degrades to the one logical line.
1758        let off2 = crate::text::offset_for_position_wrapped(
1759            "hello",
1760            &style,
1761            None,
1762            None,
1763            line_height,
1764            0.0,
1765            0.0,
1766        );
1767        assert_eq!(off2, 0);
1768    }
1769
1770    #[test]
1771    fn text_field_node_focus() {
1772        let _app_context = crate::render_state::app_context_test_scope();
1773        with_test_runtime(|| {
1774            let state = TextFieldState::new("Test");
1775            let mut node = TextFieldModifierNode::new(state, TextStyle::default());
1776            assert!(!node.is_focused());
1777
1778            node.set_focused(true);
1779            assert!(node.is_focused());
1780
1781            node.set_focused(false);
1782            assert!(!node.is_focused());
1783        });
1784    }
1785
1786    #[test]
1787    fn text_field_element_creates_node() {
1788        let _app_context = crate::render_state::app_context_test_scope();
1789        with_test_runtime(|| {
1790            let state = TextFieldState::new("Hello World");
1791            let element = TextFieldElement::new(state, TextStyle::default());
1792
1793            let node = element.create();
1794            assert_eq!(node.text(), "Hello World");
1795        });
1796    }
1797
1798    /// End-to-end guard for source-independent direct manipulation through the
1799    /// real pointer handler and draw closure. Keyboard-only focus keeps a clean
1800    /// caret; touch, mouse, and stylus presses publish handles and a continuous
1801    /// press stream for long-press → slide-to-menu.
1802    #[test]
1803    fn every_primary_pointer_source_publishes_direct_manipulation_metrics() {
1804        use cranpose_foundation::{PointerEvent, PointerEventKind, PointerSource};
1805        use cranpose_ui_graphics::Point;
1806
1807        let _app_context = crate::render_state::app_context_test_scope();
1808        with_test_runtime(|| {
1809            let state = TextFieldState::new("hello world");
1810            let controller = TextFieldHandleController::new();
1811            let mut node = TextFieldModifierNode::new(state, TextStyle::default())
1812                .with_handle_controller(controller.clone());
1813            // Give the field a measured size so the draw closure has geometry.
1814            node.measured_size.set(Size {
1815                width: 120.0,
1816                height: 20.0,
1817            });
1818
1819            let handler = node
1820                .pointer_input_handler()
1821                .expect("field exposes a pointer handler");
1822            let draw = node
1823                .create_draw_closure()
1824                .expect("field exposes a draw closure");
1825            let at = Point { x: 12.0, y: 8.0 };
1826            let size = Size {
1827                width: 120.0,
1828                height: 20.0,
1829            };
1830            // The closure records into a caller-provided scope; the test only
1831            // cares about the metrics side effects, so the recording is dropped.
1832            let run_draw = || {
1833                let mut scope = crate::draw::command_draw_scope(size);
1834                draw(&mut scope);
1835            };
1836
1837            node.set_focused(true);
1838            run_draw();
1839            let keyboard_metrics = controller
1840                .metrics()
1841                .expect("focused field publishes handle metrics");
1842            assert!(!keyboard_metrics.direct_manipulation);
1843
1844            handler(
1845                PointerEvent::new(PointerEventKind::Down, at, at).with_source(PointerSource::Touch),
1846            );
1847            run_draw();
1848            let metrics = controller
1849                .metrics()
1850                .expect("focused field publishes handle metrics");
1851            assert!(metrics.focused, "a tap focuses the field");
1852            assert!(
1853                metrics.direct_manipulation,
1854                "a touch tap must expose direct-manipulation handles"
1855            );
1856            assert!(
1857                controller.press().is_some(),
1858                "touch must publish the live press"
1859            );
1860
1861            handler(
1862                PointerEvent::new(PointerEventKind::Down, at, at).with_source(PointerSource::Mouse),
1863            );
1864            run_draw();
1865            let metrics = controller
1866                .metrics()
1867                .expect("focused field publishes handle metrics");
1868            assert!(
1869                metrics.direct_manipulation,
1870                "a mouse tap must expose the same direct-manipulation handles"
1871            );
1872            assert!(
1873                controller.press().is_some(),
1874                "mouse must publish the live press"
1875            );
1876
1877            handler(
1878                PointerEvent::new(PointerEventKind::Down, at, at)
1879                    .with_source(PointerSource::Stylus),
1880            );
1881            run_draw();
1882            let metrics = controller
1883                .metrics()
1884                .expect("focused field publishes handle metrics");
1885            assert!(
1886                metrics.direct_manipulation,
1887                "a stylus contact must expose the same direct-manipulation handles"
1888            );
1889            assert!(
1890                controller.press().is_some(),
1891                "stylus must publish the live press"
1892            );
1893
1894            crate::text_field_focus::clear_focus();
1895        });
1896    }
1897
1898    /// A double tap on a word must select that word. This regressed after
1899    /// selection handles began appearing inside `LazyColumn` items in 0.1.39:
1900    /// the cursor handle shown by the first tap overlapped the text line and
1901    /// consumed the second tap. The field's own gesture classification (proven
1902    /// here) is correct — two quick taps at the same spot escalate to a word
1903    /// selection — so the fix is geometric (keep the handle's touch box off the
1904    /// text line; see `selection_handle::handle_shape`).
1905    #[test]
1906    fn double_tap_selects_the_word_under_the_finger() {
1907        use cranpose_foundation::{PointerEvent, PointerEventKind, PointerSource};
1908        use cranpose_ui_graphics::Point;
1909
1910        let _app_context = crate::render_state::app_context_test_scope();
1911        with_test_runtime(|| {
1912            let state = TextFieldState::new("hello world");
1913            let node = TextFieldModifierNode::new(state, TextStyle::default());
1914            node.measured_size.set(Size {
1915                width: 200.0,
1916                height: 20.0,
1917            });
1918            let handler = node
1919                .pointer_input_handler()
1920                .expect("field exposes a pointer handler");
1921
1922            // Two touch taps at the same spot, back to back (well within the
1923            // multi-tap timeout and slop): near the start of "hello".
1924            let at = Point { x: 2.0, y: 8.0 };
1925            handler(
1926                PointerEvent::new(PointerEventKind::Down, at, at).with_source(PointerSource::Touch),
1927            );
1928            handler(
1929                PointerEvent::new(PointerEventKind::Down, at, at).with_source(PointerSource::Touch),
1930            );
1931
1932            let selection = state.selection();
1933            assert!(
1934                !selection.collapsed(),
1935                "a double tap must produce a (word) selection, got {selection:?}"
1936            );
1937            let selected = &state.text()[selection.min()..selection.max()];
1938            assert_eq!(
1939                selected, "hello",
1940                "double tap should select the whole word under the finger"
1941            );
1942
1943            crate::text_field_focus::clear_focus();
1944        });
1945    }
1946
1947    /// The multi-tap selection granularity ladder (bug 8): repeated in-place taps
1948    /// escalate word → line → paragraph, then cycle back to word. Mirrors mature
1949    /// editors (Android `TextView`, iOS, VS Code).
1950    #[test]
1951    fn repeated_taps_escalate_word_line_paragraph_then_cycle() {
1952        use cranpose_foundation::{PointerEvent, PointerEventKind, PointerSource};
1953        use cranpose_ui_graphics::Point;
1954
1955        let _app_context = crate::render_state::app_context_test_scope();
1956        with_test_runtime(|| {
1957            // Two lines in the first paragraph, a blank line, then a second
1958            // paragraph — so line and paragraph selections differ.
1959            let text = "alpha beta\ngamma delta\n\nsecond para";
1960            let state = TextFieldState::new(text);
1961            let node = TextFieldModifierNode::new(state, TextStyle::default()).with_line_limits(
1962                TextFieldLineLimits::MultiLine {
1963                    min_lines: 1,
1964                    max_lines: usize::MAX,
1965                },
1966            );
1967            node.measured_size.set(Size {
1968                width: 400.0,
1969                height: 80.0,
1970            });
1971            let handler = node
1972                .pointer_input_handler()
1973                .expect("field exposes a pointer handler");
1974
1975            // Tap in place on the first line ("alpha").
1976            let at = Point { x: 2.0, y: 4.0 };
1977            let tap = || {
1978                handler(
1979                    PointerEvent::new(PointerEventKind::Down, at, at)
1980                        .with_source(PointerSource::Touch),
1981                );
1982            };
1983            let selected = |state: &TextFieldState| {
1984                let s = state.selection();
1985                state.text()[s.min()..s.max()].to_string()
1986            };
1987
1988            tap(); // 1 → caret
1989            assert!(state.selection().collapsed(), "first tap places the caret");
1990            tap(); // 2 → word
1991            assert_eq!(selected(&state), "alpha", "double tap selects the word");
1992            tap(); // 3 → line
1993            assert_eq!(
1994                selected(&state),
1995                "alpha beta",
1996                "triple tap selects the line"
1997            );
1998            tap(); // 4 → paragraph
1999            assert_eq!(
2000                selected(&state),
2001                "alpha beta\ngamma delta",
2002                "fourth tap grows to the paragraph"
2003            );
2004            tap(); // 5 → cycles back to word
2005            assert_eq!(
2006                selected(&state),
2007                "alpha",
2008                "fifth tap cycles back to the word"
2009            );
2010
2011            crate::text_field_focus::clear_focus();
2012        });
2013    }
2014
2015    /// A single tap that lands inside an existing selection re-grabs the word
2016    /// under the finger (Android/iOS behaviour), rather than collapsing to a
2017    /// caret (bug 8).
2018    #[test]
2019    fn single_tap_inside_selection_selects_the_word() {
2020        use cranpose_foundation::{PointerEvent, PointerEventKind, PointerSource};
2021        use cranpose_ui_graphics::Point;
2022
2023        let _app_context = crate::render_state::app_context_test_scope();
2024        with_test_runtime(|| {
2025            let state = TextFieldState::new("hello world");
2026            let node = TextFieldModifierNode::new(state, TextStyle::default());
2027            node.measured_size.set(Size {
2028                width: 200.0,
2029                height: 20.0,
2030            });
2031            let handler = node
2032                .pointer_input_handler()
2033                .expect("field exposes a pointer handler");
2034
2035            // Pre-existing broad selection over the whole text.
2036            state.edit(|buffer| buffer.select(TextRange::new(0, 11)));
2037            assert!(!state.selection().collapsed());
2038
2039            // A lone tap over "hello" (fresh tap count) must select that word,
2040            // not drop the selection.
2041            let at = Point { x: 2.0, y: 8.0 };
2042            handler(
2043                PointerEvent::new(PointerEventKind::Down, at, at).with_source(PointerSource::Touch),
2044            );
2045
2046            let selection = state.selection();
2047            assert!(
2048                !selection.collapsed(),
2049                "a tap inside a selection must not collapse it, got {selection:?}"
2050            );
2051            assert_eq!(
2052                &state.text()[selection.min()..selection.max()],
2053                "hello",
2054                "a tap inside a selection re-selects the word under the finger"
2055            );
2056
2057            crate::text_field_focus::clear_focus();
2058        });
2059    }
2060
2061    /// Bug (c) at the handler level: repeated taps at the SAME spot inside an
2062    /// existing selection climb the granularity ladder word → line → paragraph →
2063    /// word even when each tap arrives after the multi-tap timeout has lapsed
2064    /// (the growth is keyed on location, not the double-tap timer). Forcing a
2065    /// timeout between taps (clearing `last_click_time`) makes the raw tap count
2066    /// reset to 1 each time, so this exercises the location-based path rather
2067    /// than the rapid-multi-tap path.
2068    #[test]
2069    fn slow_taps_inside_selection_cycle_word_line_paragraph_by_location() {
2070        use cranpose_foundation::{PointerEvent, PointerEventKind, PointerSource};
2071        use cranpose_ui_graphics::Point;
2072
2073        let _app_context = crate::render_state::app_context_test_scope();
2074        with_test_runtime(|| {
2075            let text = "alpha beta\ngamma delta\n\nsecond para";
2076            let state = TextFieldState::new(text);
2077            let node = TextFieldModifierNode::new(state, TextStyle::default()).with_line_limits(
2078                TextFieldLineLimits::MultiLine {
2079                    min_lines: 1,
2080                    max_lines: usize::MAX,
2081                },
2082            );
2083            node.measured_size.set(Size {
2084                width: 400.0,
2085                height: 80.0,
2086            });
2087            let handler = node
2088                .pointer_input_handler()
2089                .expect("field exposes a pointer handler");
2090
2091            // A broad pre-existing selection over the whole text.
2092            state.edit(|buffer| buffer.select(TextRange::new(0, text.len())));
2093
2094            let at = Point { x: 2.0, y: 4.0 };
2095            let selected = |state: &TextFieldState| {
2096                let s = state.selection();
2097                state.text()[s.min()..s.max()].to_string()
2098            };
2099            // Each call forces the multi-tap timer to look expired, so the raw
2100            // tap count resets to 1 while the tap position stays put.
2101            let slow_tap = || {
2102                node.refs.last_click_time.set(None);
2103                handler(
2104                    PointerEvent::new(PointerEventKind::Down, at, at)
2105                        .with_source(PointerSource::Touch),
2106                );
2107            };
2108
2109            slow_tap(); // inside selection → word
2110            assert_eq!(
2111                selected(&state),
2112                "alpha",
2113                "tap inside selection grabs the word"
2114            );
2115            slow_tap(); // same spot → line
2116            assert_eq!(
2117                selected(&state),
2118                "alpha beta",
2119                "same-spot tap grows to the line even after the timeout"
2120            );
2121            slow_tap(); // same spot → paragraph
2122            assert_eq!(
2123                selected(&state),
2124                "alpha beta\ngamma delta",
2125                "same-spot tap grows to the paragraph"
2126            );
2127            slow_tap(); // same spot → cycles back to word
2128            assert_eq!(
2129                selected(&state),
2130                "alpha",
2131                "same-spot tap cycles back to the word"
2132            );
2133
2134            crate::text_field_focus::clear_focus();
2135        });
2136    }
2137
2138    #[test]
2139    fn text_field_element_equality() {
2140        let _app_context = crate::render_state::app_context_test_scope();
2141        with_test_runtime(|| {
2142            let state1 = TextFieldState::new("Hello");
2143            let state2 = TextFieldState::new("Hello"); // Different Rc, same text
2144
2145            let elem1 = TextFieldElement::new(state1, TextStyle::default());
2146            let elem2 = TextFieldElement::new(state1, TextStyle::default()); // Same state (Rc identity)
2147            let elem3 = TextFieldElement::new(state2, TextStyle::default()); // Different state
2148
2149            // Elements are equal only when they share the same state Rc
2150            // This ensures proper Eq/Hash contract compliance
2151            assert_eq!(elem1, elem2, "Same state should be equal");
2152            assert_ne!(elem1, elem3, "Different states should not be equal");
2153        });
2154    }
2155
2156    #[test]
2157    fn text_field_element_update_refreshes_existing_node_style() {
2158        let _app_context = crate::render_state::app_context_test_scope();
2159        with_test_runtime(|| {
2160            let state = TextFieldState::new("themed text");
2161            let dark_style = TextStyle::from_span_style(crate::text::SpanStyle {
2162                color: Some(Color::from_rgba_u8(228, 240, 252, 255)),
2163                ..crate::text::SpanStyle::default()
2164            });
2165            let light_style = TextStyle::from_span_style(crate::text::SpanStyle {
2166                color: Some(Color::from_rgba_u8(14, 58, 96, 255)),
2167                ..crate::text::SpanStyle::default()
2168            });
2169            let initial = TextFieldElement::new(state, dark_style);
2170            let updated = TextFieldElement::new(state, light_style.clone());
2171            let mut node = initial.create();
2172
2173            updated.update(&mut node);
2174
2175            assert_eq!(node.text(), "themed text");
2176            assert_eq!(node.style(), &light_style);
2177        });
2178    }
2179
2180    /// A multi-line field must measure the *wrapped* height at the available
2181    /// width, so a long transcript grows the field instead of being clipped to
2182    /// a single line. Regression for the "edits only appear after focus loss"
2183    /// bug where a wrapped OCR transcript rendered only its first line.
2184    #[test]
2185    fn multiline_field_measures_wrapped_height() {
2186        let _app_context = crate::render_state::app_context_test_scope();
2187        with_test_runtime(|| {
2188            let long = "abcd ".repeat(40); // ~200 chars, no explicit newlines
2189            let state = TextFieldState::new(&long);
2190            let node = TextFieldModifierNode::new(state, TextStyle::default());
2191            assert!(
2192                !node.line_limits().is_single_line(),
2193                "default fields are multi-line"
2194            );
2195
2196            let natural = node.measure_text_content(None);
2197            let wrapped = node.measure_text_content(node.wrap_width(20.0));
2198
2199            assert!(
2200                wrapped.height > natural.height,
2201                "wrapped multi-line height {} must exceed the single-line height {}",
2202                wrapped.height,
2203                natural.height
2204            );
2205        });
2206    }
2207
2208    /// Single-line fields pan horizontally instead of wrapping, so they never
2209    /// derive a wrap width even under a narrow constraint.
2210    #[test]
2211    fn single_line_field_never_wraps() {
2212        let _app_context = crate::render_state::app_context_test_scope();
2213        with_test_runtime(|| {
2214            let state = TextFieldState::new("abcd ".repeat(40));
2215            let node = TextFieldModifierNode::new(state, TextStyle::default())
2216                .with_line_limits(TextFieldLineLimits::SingleLine);
2217            assert_eq!(
2218                node.wrap_width(20.0),
2219                None,
2220                "single-line fields must not wrap"
2221            );
2222        });
2223    }
2224
2225    /// Test that cursor draw command position is calculated correctly.
2226    ///
2227    /// This test verifies that when we measure text width for cursor position:
2228    /// 1. The cursor x position = width of text before cursor
2229    /// 2. For text at cursor end, x = full text width
2230    #[test]
2231    fn test_cursor_x_position_calculation() {
2232        let _app_context = crate::render_state::app_context_test_scope();
2233        with_test_runtime(|| {
2234            // Test that text measurement works correctly for cursor positioning
2235            let style = crate::text::TextStyle::default();
2236
2237            // Empty text - cursor should be at x=0
2238            let empty_width =
2239                crate::text::measure_text(&crate::text::AnnotatedString::from(""), &style).width;
2240            assert!(
2241                empty_width.abs() < 0.1,
2242                "Empty text should have 0 width, got {}",
2243                empty_width
2244            );
2245
2246            // Non-empty text - cursor at end should be at text width
2247            let hi_width =
2248                crate::text::measure_text(&crate::text::AnnotatedString::from("Hi"), &style).width;
2249            assert!(
2250                hi_width > 0.0,
2251                "Text 'Hi' should have positive width: {}",
2252                hi_width
2253            );
2254
2255            // Partial text - cursor after 'H' should be at width of 'H'
2256            let h_width =
2257                crate::text::measure_text(&crate::text::AnnotatedString::from("H"), &style).width;
2258            assert!(h_width > 0.0, "Text 'H' should have positive width");
2259            assert!(
2260                h_width < hi_width,
2261                "'H' width {} should be less than 'Hi' width {}",
2262                h_width,
2263                hi_width
2264            );
2265
2266            // Verify TextFieldState selection tracks cursor correctly
2267            let state = TextFieldState::new("Hi");
2268            assert_eq!(
2269                state.selection().start,
2270                2,
2271                "Cursor should be at position 2 (end of 'Hi')"
2272            );
2273
2274            // The text before cursor at position 2 in "Hi" is "Hi" itself
2275            let text = state.text();
2276            let cursor_pos = state.selection().start;
2277            let text_before_cursor = &text[..cursor_pos.min(text.len())];
2278            assert_eq!(text_before_cursor, "Hi");
2279
2280            // So cursor x = width of "Hi"
2281            let cursor_x = crate::text::measure_text(
2282                &crate::text::AnnotatedString::from(text_before_cursor),
2283                &style,
2284            )
2285            .width;
2286            assert!(
2287                (cursor_x - hi_width).abs() < 0.1,
2288                "Cursor x {} should equal 'Hi' width {}",
2289                cursor_x,
2290                hi_width
2291            );
2292        });
2293    }
2294
2295    /// Test cursor is created when focused node is in slices.
2296    #[test]
2297    fn test_focused_node_creates_cursor() {
2298        let _app_context = crate::render_state::app_context_test_scope();
2299        with_test_runtime(|| {
2300            let state = TextFieldState::new("Test");
2301            let element = TextFieldElement::new(state, TextStyle::default());
2302            let node = element.create();
2303
2304            // Initially not focused
2305            assert!(!node.is_focused());
2306
2307            // Set focus
2308            *node.refs.is_focused.borrow_mut() = true;
2309            assert!(node.is_focused());
2310
2311            // Verify the node has correct text
2312            assert_eq!(node.text(), "Test");
2313
2314            // Verify selection is at end
2315            assert_eq!(node.selection().start, 4);
2316        });
2317    }
2318}