Skip to main content

cranpose_ui/widgets/
basic_text_field.rs

1//! BasicTextField widget for editable text input.
2//!
3//! This module provides the `BasicTextField` composable following Jetpack Compose's
4//! `BasicTextField` pattern from `compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/BasicTextField.kt`.
5
6use std::{
7    cell::{Cell, RefCell},
8    rc::{Rc, Weak},
9};
10
11use cranpose_core::{MutableState, NodeId, SideEffect, mutableStateOf, remember};
12use cranpose_foundation::{
13    modifier_element,
14    text::{
15        InputTransformation, OutputTransformation, TextFieldLineLimits, TextFieldState, TextRange,
16    },
17};
18use cranpose_ui_graphics::{Color, Point, Rect};
19
20use crate::{
21    bring_into_view::local_bring_into_view_responder,
22    clipboard_session::{clipboard_can_paste, clipboard_paste_into_focus, clipboard_write_text},
23    composable,
24    keyboard_options::{KeyboardActionHandler, KeyboardOptions},
25    layout::{
26        core::Alignment,
27        policies::{BoxMeasurePolicy, EmptyMeasurePolicy},
28    },
29    modifier::Modifier,
30    safe_area::local_ime_insets,
31    text::{AnnotatedString, TextStyle},
32    text_field_decorator_node::TextFieldDecoratorElement,
33    text_field_focus::{dispatch_copy, dispatch_cut, dispatch_select_all},
34    text_field_modifier_node::{
35        TextFieldElement, TextFieldHandleController, TextFieldHandleMetrics, TextFieldRefs,
36    },
37    text_selection::{
38        HANDLE_RADIUS, HandleGrabOffset, HandleKind, LineAffinity, selection_after_handle_drag,
39    },
40    widgets::{
41        CaretActionMenu, Layout, MenuAnchor, SelectionHandle, SelectionLoupe, TextSelectionMenu,
42        loupe_target_for_drag,
43    },
44};
45
46/// Hold duration before a stationary touch press on the text claims the
47/// gesture (word-select + menu while the finger is still down).
48const TEXT_LONG_PRESS_MS: u64 = 500;
49/// Travel beyond this (dp) before the hold elapses is a drag, not a
50/// long-press.
51const TEXT_LONG_PRESS_SLOP: f32 = 12.0;
52
53/// Frame-clock watcher for the long-press → slide-to-menu gesture: armed by
54/// the composition when the field node publishes a fresh touch press, it
55/// claims the gesture after the hold threshold (selecting the word under
56/// the press; the range-change side effect opens the menu). The composition
57/// slot holds the only strong reference — dropping it (press ended, field
58/// recomposed away) cancels the pending frame callback.
59struct LongPressWatcher {
60    controller: TextFieldHandleController,
61    state: TextFieldState,
62    style: TextStyle,
63    start: Point,
64    start_nanos: Cell<Option<u64>>,
65    registration: RefCell<Option<cranpose_core::internal::FrameCallbackRegistration>>,
66    frame_clock: cranpose_core::internal::FrameClock,
67}
68
69impl LongPressWatcher {
70    fn arm(self: &Rc<Self>) {
71        let weak: Weak<Self> = Rc::downgrade(self);
72        let registration = self.frame_clock.with_frame_nanos(move |now| {
73            let Some(watcher) = weak.upgrade() else {
74                return;
75            };
76            watcher.tick(now);
77        });
78        *self.registration.borrow_mut() = Some(registration);
79        crate::request_render_invalidation();
80    }
81
82    fn tick(self: Rc<Self>, now: u64) {
83        self.registration.borrow_mut().take();
84        let Some(press) = self.controller.press() else {
85            return;
86        };
87        let moved = (press.position.x - self.start.x)
88            .abs()
89            .max((press.position.y - self.start.y).abs());
90        if (press.start.x - self.start.x).abs() > 0.5
91            || (press.start.y - self.start.y).abs() > 0.5
92            || moved > TEXT_LONG_PRESS_SLOP
93        {
94            return;
95        }
96        let start = match self.start_nanos.get() {
97            Some(value) => value,
98            None => {
99                self.start_nanos.set(Some(now));
100                now
101            }
102        };
103        if now.saturating_sub(start) < TEXT_LONG_PRESS_MS * 1_000_000 {
104            self.arm();
105            return;
106        }
107        self.controller.claim_gesture();
108        let Some(metrics) = self.controller.metrics() else {
109            return;
110        };
111        let presentation = self.controller.presentation(self.state);
112        let offset = presentation.to_source(window_pos_to_offset(
113            presentation.text(),
114            &self.style,
115            &metrics,
116            self.start,
117            0.0,
118        ));
119        let (word_start, word_end) = self
120            .state
121            .with_text(|text| crate::word_boundaries::find_word_boundaries(text, offset));
122        self.state.edit(|buffer| {
123            buffer.select(TextRange::new(word_start, word_end));
124        });
125        crate::request_render_invalidation();
126    }
127}
128
129/// Local position where a handle's tip should sit for the caret/selection
130/// endpoint at byte `offset`: the bottom of that offset's visual line.
131/// `affinity` decides the line at a shared soft-wrap boundary: selection ENDS,
132/// the cursor handle and the loupe anchor upstream (the line the finger rides),
133/// the selection START anchors downstream (the first highlighted glyph).
134fn handle_tip_local_pos(
135    text: &str,
136    style: &TextStyle,
137    metrics: &TextFieldHandleMetrics,
138    offset: usize,
139    affinity: LineAffinity,
140) -> Point {
141    let offset = offset.min(text.len());
142    let (line_index, line_start) = crate::text_field_modifier_node::caret_visual_line_for_offset(
143        text,
144        style,
145        metrics.wrap_width,
146        offset,
147        affinity,
148    );
149    let caret_x = crate::text::get_cursor_x_for_offset(
150        &AnnotatedString::from(&text[line_start..offset]),
151        style,
152        offset - line_start,
153    );
154    Point {
155        x: metrics.padding_left + caret_x - metrics.scroll_offset,
156        y: metrics.padding_top
157            + line_index as f32 * metrics.line_height
158            + metrics.glyph_box.0
159            + metrics.glyph_box.1,
160    }
161}
162
163fn caret_window_geometry(
164    text: &str,
165    style: &TextStyle,
166    metrics: &TextFieldHandleMetrics,
167    offset: usize,
168    affinity: LineAffinity,
169) -> (Point, Rect) {
170    let tip = handle_tip_local_pos(text, style, metrics, offset, affinity);
171    let bounds = metrics.local_to_window.bounds_for_rect(Rect {
172        x: tip.x,
173        y: tip.y - metrics.glyph_box.1,
174        width: 2.0,
175        height: metrics.glyph_box.1,
176    });
177    (metrics.local_to_window.map_point(tip), bounds)
178}
179
180/// Maps a window-space drag position back to the nearest text byte offset in
181/// the field. `y_bias` is the finger-to-line offset captured when the handle
182/// was grabbed (`grab line bottom − finger y`): adding it back keeps the drag
183/// targeting the line the finger means, whether the grab was on the line
184/// itself (stem/edge) or on the dot hanging outside it — the reference drags
185/// preserve the initial finger-to-line relationship.
186fn window_pos_to_offset(
187    text: &str,
188    style: &TextStyle,
189    metrics: &TextFieldHandleMetrics,
190    window_pos: Point,
191    y_bias: f32,
192) -> usize {
193    let Some(inverse) = metrics.local_to_window.inverse() else {
194        return 0;
195    };
196    let local = inverse.map_point(Point {
197        y: window_pos.y + y_bias,
198        ..window_pos
199    });
200    let local_x = (local.x - metrics.padding_left + metrics.scroll_offset).max(0.0);
201    let local_y = (local.y - 0.5 * metrics.line_height - metrics.padding_top).max(0.0);
202    crate::text::offset_for_position_wrapped(text, style, metrics.wrap_width, local_x, local_y)
203}
204/// Edits text through a retained [`TextFieldState`]. `modifier` controls the
205/// field bounds and input, and `style` controls the text. Use
206/// [`BasicTextFieldWithOptions`] for line limits, cursor color and edit callbacks.
207///
208/// # Example
209///
210/// ```rust
211/// use cranpose_ui::*;
212///
213/// #[composable]
214/// fn NameField() {
215///     let text =
216///         cranpose_core::remember(|| TextFieldState::new("Initial text")).with(|state| *state);
217///     BasicTextField(text, Modifier::empty().padding(8.0), TextStyle::default());
218/// }
219/// ```
220#[composable]
221pub fn BasicTextField(state: TextFieldState, modifier: Modifier, style: TextStyle) -> NodeId {
222    BasicTextFieldWithOptions(
223        state,
224        modifier,
225        BasicTextFieldOptions {
226            text_style: style,
227            ..BasicTextFieldOptions::default()
228        },
229    )
230}
231
232/// Options for customizing BasicTextField appearance and behavior.
233#[derive(Debug, Clone, PartialEq)]
234pub struct BasicTextFieldOptions {
235    /// Text style
236    pub text_style: TextStyle,
237    /// The caret's color. The selection's highlight and handles take
238    /// [`crate::local_text_selection_colors`].
239    pub cursor_color: Color,
240    /// Line limits: SingleLine or MultiLine with optional min/max
241    pub line_limits: TextFieldLineLimits,
242    /// Whether gaining focus opens the software keyboard. Defaults to `true`.
243    ///
244    /// When `false`, programmatic and keyboard-navigation focus leave the
245    /// software keyboard hidden. A pointer tap still explicitly opens it.
246    /// Changing this to `true` while focused also requests the keyboard.
247    /// Changing it to `false` preserves an already visible keyboard.
248    pub show_keyboard_on_focus: bool,
249    /// The software keyboard the field asks for and its action key.
250    pub keyboard_options: KeyboardOptions,
251    /// Runs the keyboard's action key, and Enter in a single-line field.
252    /// Without it the action's default runs: Next and Previous move focus,
253    /// Done hides the software keyboard.
254    pub on_keyboard_action: Option<KeyboardActionHandler>,
255    /// Changes or rejects each edit the person makes, such as a length
256    /// limit or a filter on what can be typed.
257    pub input_transformation: Option<InputTransformation>,
258    /// Changes how the field shows its text without changing the text.
259    /// Make it once, with `remember`: the field lays out again whenever it
260    /// gets a different one.
261    pub output_transformation: Option<OutputTransformation>,
262}
263
264impl Default for BasicTextFieldOptions {
265    fn default() -> Self {
266        Self {
267            text_style: TextStyle::default(),
268            cursor_color: Color(0.0, 0.478, 1.0, 1.0),
269            line_limits: TextFieldLineLimits::default(),
270            show_keyboard_on_focus: true,
271            keyboard_options: KeyboardOptions::default(),
272            on_keyboard_action: None,
273            input_transformation: None,
274            output_transformation: None,
275        }
276    }
277}
278
279/// Scope passed to a basic text field decoration box.
280///
281/// The decoration may place arbitrary composables around the editable content,
282/// but must call [`inner_text_field`](Self::inner_text_field) exactly once.
283#[derive(Clone)]
284pub struct BasicTextFieldDecorationScope {
285    inner: Rc<dyn Fn() -> NodeId>,
286}
287
288impl BasicTextFieldDecorationScope {
289    /// Composes the editable text area and returns its node id. The decoration box must call this
290    /// exactly once.
291    pub fn inner_text_field(&self) -> NodeId {
292        (self.inner)()
293    }
294}
295
296impl PartialEq for BasicTextFieldDecorationScope {
297    fn eq(&self, other: &Self) -> bool {
298        Rc::ptr_eq(&self.inner, &other.inner)
299    }
300}
301
302/// Creates an editable field and lets `decoration_box` place composable labels,
303/// placeholders, icons, buttons, prefixes, or suffixes around it.
304///
305/// As in Compose, the decoration box is the field: `modifier` applies to it,
306/// and it takes the field's pointer input, focus and semantics, so a press
307/// anywhere in it edits the text. The inner field only lays out and draws
308/// the text, as wide as the text unless the decoration stretches it (a
309/// `Box` that propagates its minimum constraints, for one).
310#[composable(no_skip)]
311pub fn BasicTextFieldDecorated<D>(
312    state: TextFieldState,
313    modifier: Modifier,
314    options: BasicTextFieldOptions,
315    decoration_box: D,
316) -> NodeId
317where
318    D: Fn(BasicTextFieldDecorationScope) + 'static,
319{
320    let refs = remember(TextFieldRefs::new).with(TextFieldRefs::clone);
321    let decorator = TextFieldDecoratorElement::new(
322        state,
323        refs.clone(),
324        options.text_style.clone(),
325        options.line_limits,
326        crate::modal::local_modal_depth().current(),
327    );
328    let scope = BasicTextFieldDecorationScope {
329        inner: Rc::new(move || {
330            TextFieldNode(
331                state,
332                Modifier::empty(),
333                options.clone(),
334                Some(refs.clone()),
335                false,
336            )
337        }),
338    };
339    Layout(
340        modifier.then(Modifier::from_dyn_element(modifier_element(decorator))),
341        BoxMeasurePolicy::new(Alignment::TOP_START, true),
342        move || decoration_box(scope.clone()),
343    )
344}
345
346/// Creates an editable text field with custom options.
347///
348/// This is the full version of `BasicTextField` with all configuration options.
349#[composable]
350pub fn BasicTextFieldWithOptions(
351    state: TextFieldState,
352    modifier: Modifier,
353    options: BasicTextFieldOptions,
354) -> NodeId {
355    TextFieldNode(state, modifier, options, None, false)
356}
357
358/// The field's node, and the handles and caret tracking around it. With
359/// `decorator`, the decoration box sharing those refs takes the field's
360/// input, focus and semantics. A `secure` field holds a secret.
361#[composable]
362pub(crate) fn TextFieldNode(
363    state: TextFieldState,
364    modifier: Modifier,
365    options: BasicTextFieldOptions,
366    decorator: Option<TextFieldRefs>,
367    secure: bool,
368) -> NodeId {
369    #[cfg(feature = "localization")]
370    let options = BasicTextFieldOptions {
371        text_style: crate::localization::apply_text_locale(options.text_style),
372        ..options
373    };
374    state.with_text(|_| ());
375    let _selection = state.selection();
376
377    let controller =
378        remember(TextFieldHandleController::new).with(TextFieldHandleController::clone);
379
380    let modal_depth = crate::modal::local_modal_depth().current();
381    let selection_colors = crate::local_text_selection_colors().current();
382    let mut text_field_element = TextFieldElement::new(state, options.text_style.clone())
383        .with_cursor_color(options.cursor_color)
384        .with_selection_color(selection_colors.background_color)
385        .with_line_limits(options.line_limits)
386        .with_show_keyboard_on_focus(options.show_keyboard_on_focus)
387        .with_keyboard(options.keyboard_options, options.on_keyboard_action)
388        .with_input_transformation(options.input_transformation)
389        .with_output_transformation(options.output_transformation)
390        .secure(secure)
391        .with_handle_controller(controller.clone())
392        .with_modal_depth(modal_depth);
393    if let Some(refs) = decorator {
394        text_field_element = text_field_element.decorated_by(refs);
395    }
396
397    let text_field_modifier = modifier_element(text_field_element);
398    let final_modifier = Modifier::from_dyn_element(text_field_modifier);
399    let combined_modifier = modifier.then(final_modifier);
400
401    let node = Layout(combined_modifier, EmptyMeasurePolicy, || {});
402
403    BringCaretIntoView(state, options.text_style.clone(), controller.clone());
404
405    SelectionHandles(
406        state,
407        options.text_style,
408        controller,
409        selection_colors.handle_color,
410        secure,
411    );
412
413    node
414}
415
416#[cfg(test)]
417#[path = "tests/basic_text_field_options_tests.rs"]
418mod options_tests;
419
420/// Window-space rect of the field's caret (the cursor line at byte `offset`),
421/// derived from the field's published handle [`TextFieldHandleMetrics`]. Its top
422/// is the top of the caret's visual line; its height is one line.
423fn caret_window_rect(
424    text: &str,
425    style: &TextStyle,
426    metrics: &TextFieldHandleMetrics,
427    offset: usize,
428) -> Rect {
429    caret_window_geometry(text, style, metrics, offset, LineAffinity::Upstream).1
430}
431
432/// Consumer half of bug 2: while the field is focused, asks the nearest scroll
433/// container (via [`local_bring_into_view_responder`]) to scroll the caret clear
434/// of the on-screen keyboard ([`local_ime_insets`]).
435///
436/// The request is triggered only by focus, caret movement, or a change in the
437/// keyboard inset — never by scrolling — so the user is never yanked back while
438/// deliberately scrolling the field out of view. The caret rect handed to the
439/// responder is always recomputed from the live metrics, so the scroll delta is
440/// correct even as the keyboard animates in.
441#[composable]
442fn BringCaretIntoView(
443    state: TextFieldState,
444    style: TextStyle,
445    controller: TextFieldHandleController,
446) {
447    let Some(metrics) = controller.metrics() else {
448        return;
449    };
450    let ime_bottom = local_ime_insets().current().bottom;
451    let responder = local_bring_into_view_responder().current();
452
453    let previous: Rc<Cell<Option<(usize, usize, i64)>>> =
454        remember(|| Rc::new(Cell::new(None))).with(Rc::clone);
455
456    if !metrics.focused {
457        previous.set(None);
458        return;
459    }
460    let Some(responder) = responder else {
461        return;
462    };
463
464    let presentation = controller.presentation(state);
465    let selection = state.selection();
466
467    let key = (
468        selection.start,
469        selection.end,
470        (ime_bottom * 4.0).round() as i64,
471    );
472    SideEffect(move || {
473        if previous.get() == Some(key) {
474            return;
475        }
476        previous.set(Some(key));
477        let Some(metrics) = controller.metrics_now() else {
478            return;
479        };
480        let caret = caret_window_rect(
481            presentation.text(),
482            &style,
483            &metrics,
484            presentation.to_shown(selection.start),
485        );
486        responder.bring_into_view(caret, ime_bottom);
487    });
488}
489
490/// Emits selection/cursor handles for a focused field entered through any
491/// primary pointer. Keyboard-only focus keeps a clean caret.
492// The handles are drawn in `handle_color`.
493#[composable]
494fn SelectionHandles(
495    state: TextFieldState,
496    style: TextStyle,
497    controller: TextFieldHandleController,
498    handle_color: Color,
499    secure: bool,
500) {
501    let selection = state.selection();
502    let current_range = (selection.min(), selection.max());
503    let active_press = controller.press();
504
505    let menu_open = remember(|| mutableStateOf(true)).with(|state| *state);
506    let caret_menu_open = remember(|| mutableStateOf(false)).with(|state| *state);
507    let caret_menu_offset: Rc<Cell<usize>> =
508        remember(|| Rc::new(Cell::new(0usize))).with(Rc::clone);
509    let previous_range: Rc<Cell<(usize, usize)>> =
510        remember(|| Rc::new(Cell::new(current_range))).with(Rc::clone);
511    {
512        let previous_range = Rc::clone(&previous_range);
513        SideEffect(move || {
514            if previous_range.get() != current_range {
515                previous_range.set(current_range);
516                menu_open.set(true);
517            }
518        });
519    }
520    {
521        let caret_menu_offset = Rc::clone(&caret_menu_offset);
522        let caret_start = selection.start;
523        SideEffect(move || {
524            if caret_menu_open.value()
525                && (!selection.collapsed() || caret_start != caret_menu_offset.get())
526            {
527                caret_menu_open.set(false);
528            }
529        });
530    }
531
532    let Some(metrics) = controller.metrics() else {
533        return;
534    };
535    if !metrics.focused || !metrics.direct_manipulation {
536        return;
537    }
538    // Past the gate the handles are on screen and have to travel with the
539    // field, so from here the scope follows its position too.
540    let Some(metrics) = controller.live_metrics() else {
541        return;
542    };
543
544    let presentation = controller.presentation(state);
545    let text = presentation.text();
546
547    let press_watcher: Rc<Cell<Option<(u32, u32)>>> =
548        remember(|| Rc::new(Cell::new(None))).with(Rc::clone);
549    let press_watcher_ref: Rc<RefCell<Option<Rc<LongPressWatcher>>>> =
550        remember(|| Rc::new(RefCell::new(None))).with(Rc::clone);
551    match active_press {
552        Some(press) => {
553            let key = (press.start.x.to_bits(), press.start.y.to_bits());
554            if press_watcher.get() != Some(key) {
555                press_watcher.set(Some(key));
556                let watcher = Rc::new(LongPressWatcher {
557                    controller: controller.clone(),
558                    state,
559                    style: style.clone(),
560                    start: press.start,
561                    start_nanos: Cell::new(None),
562                    registration: RefCell::new(None),
563                    frame_clock: cranpose_core::with_current_composer(|composer| {
564                        composer.runtime_handle()
565                    })
566                    .frame_clock(),
567                });
568                watcher.arm();
569                *press_watcher_ref.borrow_mut() = Some(watcher);
570            }
571        }
572        None => {
573            press_watcher.set(None);
574            press_watcher_ref.borrow_mut().take();
575        }
576    }
577
578    let drag_pos: MutableState<Option<Point>> =
579        remember(|| mutableStateOf(None::<Point>)).with(|state| *state);
580    let drag_bias: Rc<Cell<Option<HandleGrabOffset>>> =
581        remember(|| Rc::new(Cell::new(None))).with(Rc::clone);
582    let last_dragged: Rc<Cell<Option<HandleKind>>> =
583        remember(|| Rc::new(Cell::new(None))).with(Rc::clone);
584    let menu_anchor_range: Rc<Cell<(usize, usize)>> =
585        remember(|| Rc::new(Cell::new(current_range))).with(Rc::clone);
586    {
587        let last_dragged = Rc::clone(&last_dragged);
588        let menu_anchor_range = Rc::clone(&menu_anchor_range);
589        SideEffect(move || {
590            if menu_anchor_range.get() != current_range {
591                menu_anchor_range.set(current_range);
592                if drag_pos.value().is_none() {
593                    last_dragged.set(None);
594                }
595            }
596        });
597    }
598    let cursor_tip_y: Rc<Cell<f32>> = remember(|| Rc::new(Cell::new(0.0f32))).with(Rc::clone);
599    let start_tip_y: Rc<Cell<f32>> = remember(|| Rc::new(Cell::new(0.0f32))).with(Rc::clone);
600    let end_tip_y: Rc<Cell<f32>> = remember(|| Rc::new(Cell::new(0.0f32))).with(Rc::clone);
601
602    if selection.collapsed() {
603        let (tip, caret_rect) = caret_window_geometry(
604            text,
605            &style,
606            &metrics,
607            presentation.to_shown(selection.start),
608            LineAffinity::Upstream,
609        );
610        let on_drag = drag_caret_closure(state, style.clone(), controller, Rc::clone(&drag_bias));
611        let open_caret_menu = {
612            let caret_menu_offset = Rc::clone(&caret_menu_offset);
613            move || {
614                caret_menu_offset.set(state.selection().start);
615                caret_menu_open.set(true);
616            }
617        };
618        let on_tap = open_caret_menu.clone();
619        let on_long_press = open_caret_menu;
620        let grab_bias = Rc::clone(&drag_bias);
621        let end_bias = Rc::clone(&drag_bias);
622        cursor_tip_y.set(tip.y);
623        let tip_y = Rc::clone(&cursor_tip_y);
624        SelectionHandle(
625            HandleKind::Cursor,
626            tip,
627            caret_rect.height,
628            HANDLE_RADIUS,
629            handle_color,
630            move |pos| {
631                track_handle_grab(&grab_bias, HandleKind::Cursor, tip_y.get(), pos.y);
632                drag_pos.set(Some(pos));
633                on_drag(pos);
634            },
635            move || {
636                drag_pos.set(None);
637                end_bias.set(None);
638                crate::cursor_animation::reset_cursor_blink();
639            },
640            on_long_press,
641            on_tap,
642        );
643
644        if caret_menu_open.value() {
645            let can_paste = clipboard_can_paste();
646            let can_undo = state.can_undo();
647            let can_redo = state.can_redo();
648            let undo_state = state;
649            let redo_state = state;
650            CaretActionMenu(
651                MenuAnchor {
652                    center_x: tip.x,
653                    line_top: caret_rect.y,
654                    line_bottom: caret_rect.y + caret_rect.height,
655                },
656                drag_pos.value().is_none(),
657                can_paste,
658                can_undo,
659                can_redo,
660                move || {
661                    clipboard_paste_into_focus();
662                    caret_menu_open.set(false);
663                },
664                move || {
665                    dispatch_select_all();
666                    caret_menu_open.set(false);
667                },
668                move || {
669                    undo_state.undo();
670                    crate::request_render_invalidation();
671                    caret_menu_open.set(false);
672                },
673                move || {
674                    redo_state.redo();
675                    crate::request_render_invalidation();
676                    caret_menu_open.set(false);
677                },
678            );
679        }
680    } else {
681        let (start, end) = presentation.range_to_shown(selection);
682        let (start_tip, start_rect) =
683            caret_window_geometry(text, &style, &metrics, start, LineAffinity::Downstream);
684        let (end_tip, end_rect) =
685            caret_window_geometry(text, &style, &metrics, end, LineAffinity::Upstream);
686
687        let last_dragged_start = Rc::clone(&last_dragged);
688        let last_dragged_end = Rc::clone(&last_dragged);
689        let on_drag_start = drag_edge_closure(
690            HandleKind::SelectionStart,
691            state,
692            style.clone(),
693            controller.clone(),
694            Rc::clone(&drag_bias),
695        );
696        let grab_bias = Rc::clone(&drag_bias);
697        let end_bias = Rc::clone(&drag_bias);
698        start_tip_y.set(start_tip.y);
699        let start_tip_live = Rc::clone(&start_tip_y);
700        SelectionHandle(
701            HandleKind::SelectionStart,
702            start_tip,
703            start_rect.height,
704            HANDLE_RADIUS,
705            handle_color,
706            move |pos| {
707                track_handle_grab(
708                    &grab_bias,
709                    HandleKind::SelectionStart,
710                    start_tip_live.get(),
711                    pos.y,
712                );
713                last_dragged_start.set(Some(HandleKind::SelectionStart));
714                drag_pos.set(Some(pos));
715                on_drag_start(pos);
716            },
717            move || {
718                drag_pos.set(None);
719                end_bias.set(None);
720            },
721            move || menu_open.set(true),
722            move || menu_open.set(true),
723        );
724
725        let on_drag_end = drag_edge_closure(
726            HandleKind::SelectionEnd,
727            state,
728            style.clone(),
729            controller.clone(),
730            Rc::clone(&drag_bias),
731        );
732        let grab_bias = Rc::clone(&drag_bias);
733        let end_bias = Rc::clone(&drag_bias);
734        end_tip_y.set(end_tip.y);
735        let end_tip_live = Rc::clone(&end_tip_y);
736        SelectionHandle(
737            HandleKind::SelectionEnd,
738            end_tip,
739            end_rect.height,
740            HANDLE_RADIUS,
741            handle_color,
742            move |pos| {
743                track_handle_grab(
744                    &grab_bias,
745                    HandleKind::SelectionEnd,
746                    end_tip_live.get(),
747                    pos.y,
748                );
749                last_dragged_end.set(Some(HandleKind::SelectionEnd));
750                drag_pos.set(Some(pos));
751                on_drag_end(pos);
752            },
753            move || {
754                drag_pos.set(None);
755                end_bias.set(None);
756            },
757            move || menu_open.set(true),
758            move || menu_open.set(true),
759        );
760
761        if menu_open.value() {
762            let can_paste = clipboard_can_paste();
763            let slide_point = if controller.gesture_claimed() {
764                active_press.map(|press| press.position)
765            } else {
766                None
767            };
768            let (center_x, caret_rect) = match last_dragged.get() {
769                Some(HandleKind::SelectionStart) => (start_tip.x, start_rect),
770                Some(HandleKind::SelectionEnd | HandleKind::Cursor) => (end_tip.x, end_rect),
771                None => ((start_tip.x + end_tip.x) * 0.5, start_rect),
772            };
773            TextSelectionMenu(
774                MenuAnchor {
775                    center_x,
776                    line_top: caret_rect.y,
777                    line_bottom: caret_rect.y + caret_rect.height,
778                },
779                drag_pos.value().is_none(),
780                slide_point,
781                !secure,
782                can_paste,
783                move || {
784                    if let Some(text) = dispatch_copy() {
785                        clipboard_write_text(&text);
786                    }
787                    menu_open.set(false);
788                },
789                move || {
790                    if let Some(text) = dispatch_cut() {
791                        clipboard_write_text(&text);
792                    }
793                    menu_open.set(false);
794                },
795                move || {
796                    clipboard_paste_into_focus();
797                    menu_open.set(false);
798                },
799                move || {
800                    dispatch_select_all();
801                    menu_open.set(false);
802                },
803            );
804        }
805    }
806
807    let loupe_target = drag_pos.value().and_then(|finger| {
808        let bias = drag_bias.get().map_or(0.0, |grab| grab.bias());
809        let offset = window_pos_to_offset(text, &style, &metrics, finger, bias);
810        let (_, caret_rect) =
811            caret_window_geometry(text, &style, &metrics, offset, LineAffinity::Upstream);
812        loupe_target_for_drag(finger, caret_rect.y + caret_rect.height, caret_rect.height)
813    });
814    SelectionLoupe(loupe_target);
815}
816
817fn track_handle_grab(
818    drag_bias: &Cell<Option<HandleGrabOffset>>,
819    kind: HandleKind,
820    handle_tip_y: f32,
821    finger_y: f32,
822) -> f32 {
823    let drifts = kind != HandleKind::SelectionStart;
824    let mut grab = drag_bias
825        .get()
826        .unwrap_or_else(|| HandleGrabOffset::begin_for(handle_tip_y, finger_y, drifts));
827    let bias = grab.track(finger_y);
828    drag_bias.set(Some(grab));
829    bias
830}
831
832/// Builds the drag handler for the collapsed cursor handle: moves the caret to
833/// the dragged position. `drag_bias` is the finger-to-line offset captured at
834/// the grab (see [`window_pos_to_offset`]).
835fn drag_caret_closure(
836    state: TextFieldState,
837    style: TextStyle,
838    controller: TextFieldHandleController,
839    drag_bias: Rc<Cell<Option<HandleGrabOffset>>>,
840) -> Rc<dyn Fn(Point)> {
841    Rc::new(move |window_pos: Point| {
842        let Some(metrics) = controller.metrics() else {
843            return;
844        };
845        let presentation = controller.presentation(state);
846        let bias = drag_bias.get().map_or(0.0, |grab| grab.bias());
847        let offset = presentation.to_source(window_pos_to_offset(
848            presentation.text(),
849            &style,
850            &metrics,
851            window_pos,
852            bias,
853        ));
854        state.set_selection(TextRange::new(offset, offset));
855        crate::cursor_animation::suspend_cursor_blink();
856        crate::request_render_invalidation();
857    })
858}
859
860/// Builds the drag handler for a selection start/end handle: extends the
861/// selection to the dragged position while keeping the opposite edge fixed and
862/// never letting the edges cross. `drag_bias` as in [`drag_caret_closure`].
863fn drag_edge_closure(
864    dragged: HandleKind,
865    state: TextFieldState,
866    style: TextStyle,
867    controller: TextFieldHandleController,
868    drag_bias: Rc<Cell<Option<HandleGrabOffset>>>,
869) -> Rc<dyn Fn(Point)> {
870    Rc::new(move |window_pos: Point| {
871        let Some(metrics) = controller.metrics() else {
872            return;
873        };
874        let presentation = controller.presentation(state);
875        let bias = drag_bias.get().map_or(0.0, |grab| grab.bias());
876        let dragged_offset = presentation.to_source(window_pos_to_offset(
877            presentation.text(),
878            &style,
879            &metrics,
880            window_pos,
881            bias,
882        ));
883        let selection = state.selection();
884        let fixed_edge = match dragged {
885            HandleKind::SelectionStart => selection.max(),
886            _ => selection.min(),
887        };
888        let (min, max) = selection_after_handle_drag(
889            dragged,
890            fixed_edge,
891            dragged_offset,
892            state.with_text(str::len),
893        );
894        state.set_selection(TextRange::new(min, max));
895        crate::request_render_invalidation();
896    })
897}
898
899#[cfg(test)]
900#[path = "tests/basic_text_field_tests.rs"]
901mod tests;