Skip to main content

strata/runtime/
selection.rs

1//! Text input layout synchronization, caret offset calculation, and caret rendering.
2
3use super::*;
4
5#[derive(Debug, Clone)]
6pub(crate) struct VisualTextLine {
7    pub start_char: usize,
8    pub end_char: usize,
9    pub next_start: usize,
10    pub y: f32,
11    pub ends_hard: bool,
12}
13
14impl AppRuntime {
15    /// Resets the caret blink cycle so the insertion caret is immediately solid and visible.
16    #[inline]
17    pub fn reset_caret_blink(&mut self) {
18        self.caret_blink_epoch = self.now();
19        self.last_caret_blink_state = true;
20    }
21
22    /// Polls caret blink cycle at the current runtime clock and returns true if blink state toggled.
23    #[inline]
24    pub fn poll_caret_blink(&mut self) -> bool {
25        let now = self.now();
26        self.poll_caret_blink_at(now)
27    }
28
29    /// Polls caret blink cycle at an explicit monotonic `Instant` and returns true if blink state toggled.
30    pub fn poll_caret_blink_at(&mut self, now: std::time::Instant) -> bool {
31        if self.active_focus.is_none() {
32            return false;
33        }
34        let elapsed_ms = now.saturating_duration_since(self.caret_blink_epoch).as_millis();
35        let is_blink_on = (elapsed_ms / 530).is_multiple_of(2);
36        if is_blink_on != self.last_caret_blink_state {
37            self.last_caret_blink_state = is_blink_on;
38            true
39        } else {
40            false
41        }
42    }
43
44    /// Returns `true` when the `<input>` identified by `(input_index, input_id, entity_id)`
45    /// currently carries `type="password"` in `self.root_blueprint`.
46    pub(crate) fn input_is_password(
47        &self,
48        input_index: usize,
49        input_id: Option<&str>,
50        entity_id: Option<strata_primitives::EntityId>,
51    ) -> bool {
52        let mut bp_counter = 0;
53        let bp = entity_id
54            .and_then(|eid| self.root_blueprint.find_by_entity_id(eid))
55            .or_else(|| {
56                Self::find_input_blueprint(
57                    &self.root_blueprint,
58                    input_index,
59                    input_id,
60                    &mut bp_counter,
61                )
62            });
63        matches!(
64            bp,
65            Some(NodeBlueprint::Element { tag: Tag::Input, attributes, .. })
66                if Self::is_password_input_attrs(attributes)
67        )
68    }
69
70    /// Returns `true` when `active` currently points to an `<input type="password">`.
71    pub(crate) fn active_input_is_password(&self, active: &ActiveInput) -> bool {
72        self.input_is_password(
73            active.input_index,
74            active.input_id.as_deref(),
75            active.entity_id,
76        )
77    }
78
79    /// Computes `(align_offset, scroll_x, cursor_x_offset)` for a single-line input so the
80    /// active caret remains visible within `content_w`.
81    pub(crate) fn compute_input_text_metrics(
82        text: &str,
83        cursor_idx: usize,
84        prev_scroll_x: f32,
85        content_w: f32,
86        text_align: strata_style::types::TextAlign,
87        font_size: f32,
88        line_height: f32,
89        is_mono: bool,
90        font_family: strata_primitives::AtomId,
91    ) -> (f32, f32, f32) {
92        let total_chars = text.chars().count();
93        let clamped_cursor = cursor_idx.min(total_chars);
94        let (full_w, _) = strata_layout::text::measure_text_bounds_with_family(
95            text,
96            font_size,
97            line_height,
98            None,
99            is_mono,
100            font_family,
101        );
102        let prefix: String = text.chars().take(clamped_cursor).collect();
103        let (cursor_w, _) = strata_layout::text::measure_text_bounds_with_family(
104            &prefix,
105            font_size,
106            line_height,
107            None,
108            is_mono,
109            font_family,
110        );
111
112        let caret_w = 2.0f32;
113        let visible_w = (content_w - caret_w).max(0.0);
114        if content_w <= 0.0 || full_w <= visible_w {
115            let align_offset = match text_align {
116                strata_style::types::TextAlign::Center => ((content_w - full_w) / 2.0).max(0.0),
117                strata_style::types::TextAlign::Right => (content_w - full_w).max(0.0),
118                _ => 0.0,
119            };
120            return (align_offset, 0.0, cursor_w);
121        }
122
123        let max_scroll_x = (full_w - visible_w).max(0.0);
124        let mut next_scroll_x = prev_scroll_x;
125        if cursor_w < next_scroll_x {
126            next_scroll_x = cursor_w;
127        } else if cursor_w > next_scroll_x + visible_w {
128            next_scroll_x = cursor_w - visible_w;
129        }
130        (0.0, next_scroll_x.clamp(0.0, max_scroll_x), cursor_w)
131    }
132
133    pub(crate) fn find_layout_for_focus<'a>(
134        root_blueprint: &NodeBlueprint,
135        layout_root: &'a LayoutNode,
136        target_idx: usize,
137        target_id: Option<&str>,
138        entity_id: Option<strata_primitives::EntityId>,
139    ) -> Option<&'a LayoutNode> {
140        if let Some(eid) = entity_id {
141            if let Some(found) = layout_root.find_by_entity_id(eid) {
142                return Some(found);
143            }
144        }
145        let mut current_idx = 0;
146        Self::find_input_layout(
147            root_blueprint,
148            layout_root,
149            target_idx,
150            target_id,
151            &mut current_idx,
152        )
153    }
154
155    pub(crate) fn find_layout_for_focus_mut<'a>(
156        root_blueprint: &NodeBlueprint,
157        layout_root: &'a mut LayoutNode,
158        target_idx: usize,
159        target_id: Option<&str>,
160        entity_id: Option<strata_primitives::EntityId>,
161    ) -> Option<&'a mut LayoutNode> {
162        if let Some(eid) = entity_id {
163            if layout_root.find_by_entity_id(eid).is_some() {
164                return layout_root.find_by_entity_id_mut(eid);
165            }
166        }
167        let mut current_idx = 0;
168        Self::find_input_layout_mut(
169            root_blueprint,
170            layout_root,
171            target_idx,
172            target_id,
173            &mut current_idx,
174        )
175    }
176
177    pub(crate) fn find_layout_path_for_focus(
178        root_blueprint: &NodeBlueprint,
179        layout_root: &LayoutNode,
180        target_idx: usize,
181        target_id: Option<&str>,
182        entity_id: Option<strata_primitives::EntityId>,
183    ) -> Option<Vec<usize>> {
184        fn find_by_entity_path(
185            node: &LayoutNode,
186            eid: strata_primitives::EntityId,
187            path: &mut Vec<usize>,
188            depth: usize,
189        ) -> bool {
190            if depth >= 256 {
191                return false;
192            }
193            if node.entity_id == eid {
194                return true;
195            }
196            for (i, child) in node.children.iter().enumerate() {
197                path.push(i);
198                if find_by_entity_path(child, eid, path, depth + 1) {
199                    return true;
200                }
201                path.pop();
202            }
203            false
204        }
205
206        if let Some(eid) = entity_id {
207            let mut path = Vec::new();
208            if find_by_entity_path(layout_root, eid, &mut path, 0) {
209                return Some(path);
210            }
211        }
212
213        fn find_by_bp_path(
214            blueprint: &NodeBlueprint,
215            layout: &LayoutNode,
216            target_idx: usize,
217            target_id: Option<&str>,
218            counter: &mut usize,
219            path: &mut Vec<usize>,
220            depth: usize,
221        ) -> bool {
222            if depth >= 256 {
223                return false;
224            }
225            match blueprint {
226                NodeBlueprint::Element {
227                    tag,
228                    attributes,
229                    children,
230                    ..
231                } => {
232                    if matches!(tag, Tag::Input | Tag::Textarea) {
233                        let this_idx = *counter;
234                        *counter += 1;
235                        if AppRuntime::input_blueprint_matches_target(
236                            attributes,
237                            this_idx,
238                            target_idx,
239                            target_id,
240                        ) {
241                            return true;
242                        }
243                    }
244                    let mut flat = Vec::new();
245                    for c in children {
246                        AppRuntime::flatten_blueprints(c, &mut flat);
247                    }
248                    for (i, (&child_bp, child_layout)) in
249                        flat.iter().zip(layout.children.iter()).enumerate()
250                    {
251                        path.push(i);
252                        if find_by_bp_path(
253                            child_bp,
254                            child_layout,
255                            target_idx,
256                            target_id,
257                            counter,
258                            path,
259                            depth + 1,
260                        ) {
261                            return true;
262                        }
263                        path.pop();
264                    }
265                    false
266                }
267                NodeBlueprint::Fragment(children) => {
268                    let mut flat = Vec::new();
269                    for c in children {
270                        AppRuntime::flatten_blueprints(c, &mut flat);
271                    }
272                    for (i, (&child_bp, child_layout)) in
273                        flat.iter().zip(layout.children.iter()).enumerate()
274                    {
275                        path.push(i);
276                        if find_by_bp_path(
277                            child_bp,
278                            child_layout,
279                            target_idx,
280                            target_id,
281                            counter,
282                            path,
283                            depth + 1,
284                        ) {
285                            return true;
286                        }
287                        path.pop();
288                    }
289                    false
290                }
291                _ => false,
292            }
293        }
294
295        let mut counter = 0;
296        let mut path = Vec::new();
297        if find_by_bp_path(
298            root_blueprint,
299            layout_root,
300            target_idx,
301            target_id,
302            &mut counter,
303            &mut path,
304            0,
305        ) {
306            Some(path)
307        } else {
308            None
309        }
310    }
311
312    /// Computes vertical distance between visual lines for multiline inputs/textareas,
313    /// matching [`strata_render::compositor::effective_draw_text_line_height`] used by
314    /// Pango Cairo, CPU rasterizer, and GPU text renderers.
315    pub(crate) fn visual_line_step(
316        font_size: f32,
317        line_height: f32,
318        _is_mono: bool,
319        _font_family: strata_primitives::AtomId,
320    ) -> f32 {
321        strata_render::compositor::effective_draw_text_line_height(font_size, line_height).max(1.0)
322    }
323
324    #[inline]
325    fn measure_char_slice_width(
326        chars: &[char],
327        start: usize,
328        end: usize,
329        font_size: f32,
330        line_height: f32,
331        is_mono: bool,
332        font_family: strata_primitives::AtomId,
333    ) -> f32 {
334        if start >= end {
335            return 0.0;
336        }
337        let s: String = chars[start..end].iter().collect();
338        strata_layout::text::measure_text_bounds_with_family(
339            &s,
340            font_size,
341            line_height,
342            None,
343            is_mono,
344            font_family,
345        )
346        .0
347    }
348
349    /// Breaks `text` into wrapped visual lines on hard newlines and `max_width` word/char boundaries.
350    pub(crate) fn layout_visual_lines(
351        text: &str,
352        max_width: f32,
353        font_size: f32,
354        line_height: f32,
355        is_mono: bool,
356        font_family: strata_primitives::AtomId,
357    ) -> (Vec<VisualTextLine>, f32) {
358        let line_step = Self::visual_line_step(font_size, line_height, is_mono, font_family);
359        let chars: Vec<char> = text.chars().collect();
360        let total = chars.len();
361        let mut lines = Vec::new();
362        let mut seg_start = 0usize;
363
364        loop {
365            let mut seg_end = seg_start;
366            while seg_end < total && chars[seg_end] != '\n' {
367                seg_end += 1;
368            }
369            let has_newline = seg_end < total;
370
371            if seg_start == seg_end {
372                let y = lines.len() as f32 * line_step;
373                lines.push(VisualTextLine {
374                    start_char: seg_start,
375                    end_char: seg_end,
376                    next_start: seg_end + usize::from(has_newline),
377                    y,
378                    ends_hard: true,
379                });
380            } else {
381                let mut cur = seg_start;
382                while cur < seg_end {
383                    let full_w = Self::measure_char_slice_width(
384                        &chars,
385                        cur,
386                        seg_end,
387                        font_size,
388                        line_height,
389                        is_mono,
390                        font_family,
391                    );
392                    if max_width <= 0.0 || full_w <= max_width {
393                        let y = lines.len() as f32 * line_step;
394                        lines.push(VisualTextLine {
395                            start_char: cur,
396                            end_char: seg_end,
397                            next_start: seg_end + usize::from(has_newline),
398                            y,
399                            ends_hard: true,
400                        });
401                        cur = seg_end;
402                    } else {
403                        let mut lo = cur + 1;
404                        let mut hi = seg_end;
405                        let mut best = cur + 1;
406                        while lo <= hi {
407                            let mid = lo + (hi - lo) / 2;
408                            let w = Self::measure_char_slice_width(
409                                &chars,
410                                cur,
411                                mid,
412                                font_size,
413                                line_height,
414                                is_mono,
415                                font_family,
416                            );
417                            if w <= max_width {
418                                best = mid;
419                                lo = mid + 1;
420                            } else {
421                                if mid == 0 {
422                                    break;
423                                }
424                                hi = mid - 1;
425                            }
426                        }
427
428                        let ws_pos = if best < seg_end {
429                            (cur..best).rfind(|&i| matches!(chars[i], ' ' | '\t'))
430                        } else {
431                            None
432                        };
433                        let (content_end, next_cur) = if let Some(ws) = ws_pos {
434                            if ws > cur {
435                                (ws, ws + 1)
436                            } else {
437                                (cur, cur + 1)
438                            }
439                        } else {
440                            (best, best)
441                        };
442                        let y = lines.len() as f32 * line_step;
443                        lines.push(VisualTextLine {
444                            start_char: cur,
445                            end_char: content_end,
446                            next_start: next_cur,
447                            y,
448                            ends_hard: false,
449                        });
450                        cur = next_cur;
451                    }
452                }
453            }
454
455            if !has_newline {
456                break;
457            }
458            seg_start = seg_end + 1;
459        }
460
461        (lines, line_step)
462    }
463
464    pub(crate) fn visual_line_index_for_cursor(lines: &[VisualTextLine], cursor_idx: usize) -> usize {
465        lines
466            .iter()
467            .position(|l| {
468                if l.ends_hard {
469                    cursor_idx >= l.start_char && cursor_idx <= l.end_char
470                } else {
471                    cursor_idx >= l.start_char && cursor_idx < l.next_start
472                }
473            })
474            .unwrap_or_else(|| lines.len().saturating_sub(1))
475    }
476
477    pub(crate) fn visual_cursor_location(
478        chars: &[char],
479        lines: &[VisualTextLine],
480        cursor_idx: usize,
481        font_size: f32,
482        line_height: f32,
483        is_mono: bool,
484        font_family: strata_primitives::AtomId,
485    ) -> (usize, f32) {
486        let line_idx = Self::visual_line_index_for_cursor(lines, cursor_idx);
487        let line = &lines[line_idx];
488        let clamped = cursor_idx.clamp(line.start_char, line.end_char);
489        let x = Self::measure_char_slice_width(
490            chars,
491            line.start_char,
492            clamped,
493            font_size,
494            line_height,
495            is_mono,
496            font_family,
497        );
498        (line_idx, x)
499    }
500
501    #[inline]
502    pub(crate) fn compute_multiline_scroll_y(
503        cursor_line_y: f32,
504        line_step: f32,
505        total_h: f32,
506        viewport_h: f32,
507        prev_scroll_y: f32,
508    ) -> f32 {
509        if viewport_h <= 0.0 || total_h <= viewport_h {
510            return 0.0;
511        }
512        let max_scroll = (total_h - viewport_h).max(0.0);
513        let mut next = prev_scroll_y.clamp(0.0, max_scroll);
514        if cursor_line_y < next {
515            next = cursor_line_y;
516        } else if cursor_line_y + line_step > next + viewport_h {
517            next = cursor_line_y + line_step - viewport_h;
518        }
519        next.clamp(0.0, max_scroll)
520    }
521
522    #[allow(clippy::too_many_arguments)]
523    pub(crate) fn cursor_index_at_input_point(
524        text: &str,
525        is_multiline: bool,
526        px: f32,
527        py: f32,
528        content_x: f32,
529        content_y: f32,
530        content_w: f32,
531        scroll_x: f32,
532        scroll_y: f32,
533        font_size: f32,
534        line_height: f32,
535        is_mono: bool,
536        font_family: strata_primitives::AtomId,
537    ) -> usize {
538        if !is_multiline {
539            let rel_x = if px < content_x {
540                (scroll_x + (px - content_x)).max(0.0)
541            } else if content_w > 0.0 && px > content_x + content_w {
542                100000.0
543            } else {
544                (px - content_x + scroll_x).max(0.0)
545            };
546            return Self::calculate_exact_char_index_at_offset(
547                text,
548                rel_x,
549                font_size,
550                line_height,
551                is_mono,
552                font_family,
553            );
554        }
555
556        let (lines, line_step) =
557            Self::layout_visual_lines(text, content_w, font_size, line_height, is_mono, font_family);
558        if lines.is_empty() {
559            return 0;
560        }
561        let rel_y = (py - content_y + scroll_y).max(0.0);
562        let target_row = ((rel_y / line_step).floor() as isize)
563            .clamp(0, lines.len().saturating_sub(1) as isize) as usize;
564        let line = &lines[target_row];
565        let rel_x = if px < content_x {
566            0.0
567        } else if content_w > 0.0 && px > content_x + content_w {
568            100000.0
569        } else {
570            (px - content_x).max(0.0)
571        };
572        let chars: Vec<char> = text.chars().collect();
573        let line_slice: String = chars[line.start_char..line.end_char].iter().collect();
574        let col = Self::calculate_exact_char_index_at_offset(
575            &line_slice,
576            rel_x,
577            font_size,
578            line_height,
579            is_mono,
580            font_family,
581        );
582        line.start_char + col
583    }
584
585    pub(crate) fn move_active_input_vertical(
586        &mut self,
587        delta_lines: isize,
588        page_jump: bool,
589        shift: bool,
590    ) {
591        let Some(ref active) = self.active_focus else {
592            return;
593        };
594        let layout_opt = Self::find_layout_for_focus(
595            &self.root_blueprint,
596            &self.layout_root,
597            active.input_index,
598            active.input_id.as_deref(),
599            active.entity_id,
600        );
601        let text = active.state.text.get();
602        if let Some(layout) = layout_opt {
603            let content_box = layout.geometry.content_box;
604            let font_size = layout.style.font_size;
605            let line_height = layout.style.line_height;
606            let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
607            let font_family = layout.style.font_family;
608            let (lines, line_step) = Self::layout_visual_lines(
609                &text,
610                content_box.width,
611                font_size,
612                line_height,
613                is_mono,
614                font_family,
615            );
616            if !lines.is_empty() {
617                let chars: Vec<char> = text.chars().collect();
618                let cur_idx = active.state.cursor_index.get().min(chars.len());
619                let (cur_line, caret_x) = Self::visual_cursor_location(
620                    &chars,
621                    &lines,
622                    cur_idx,
623                    font_size,
624                    line_height,
625                    is_mono,
626                    font_family,
627                );
628                let step = if page_jump {
629                    let visible_lines = (content_box.height / line_step).floor().max(1.0) as isize;
630                    delta_lines.signum() * visible_lines
631                } else {
632                    delta_lines
633                };
634                let target_line =
635                    (cur_line as isize + step).clamp(0, lines.len().saturating_sub(1) as isize)
636                        as usize;
637                let target = &lines[target_line];
638                let line_slice: String = chars[target.start_char..target.end_char].iter().collect();
639                let new_col = Self::calculate_exact_char_index_at_offset(
640                    &line_slice,
641                    caret_x,
642                    font_size,
643                    line_height,
644                    is_mono,
645                    font_family,
646                );
647                let new_idx = target.start_char + new_col;
648                if shift {
649                    if active.state.selection_anchor.get().is_none() {
650                        active.state.selection_anchor.set(Some(cur_idx));
651                    }
652                } else {
653                    active.state.selection_anchor.set(None);
654                }
655                active.state.cursor_index.set(new_idx);
656                return;
657            }
658        }
659        if delta_lines < 0 {
660            active.state.move_up(shift);
661        } else {
662            active.state.move_down(shift);
663        }
664    }
665
666    pub(crate) fn move_active_input_line_edge(&mut self, to_end: bool, shift: bool) {
667        let Some(ref active) = self.active_focus else {
668            return;
669        };
670        let layout_opt = Self::find_layout_for_focus(
671            &self.root_blueprint,
672            &self.layout_root,
673            active.input_index,
674            active.input_id.as_deref(),
675            active.entity_id,
676        );
677        if let Some(layout) = layout_opt {
678            let text = active.state.text.get();
679            let content_w = layout.geometry.content_box.width;
680            let font_size = layout.style.font_size;
681            let line_height = layout.style.line_height;
682            let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
683            let font_family = layout.style.font_family;
684            let (lines, _) = Self::layout_visual_lines(
685                &text,
686                content_w,
687                font_size,
688                line_height,
689                is_mono,
690                font_family,
691            );
692            if !lines.is_empty() {
693                let total = text.chars().count();
694                let cur_idx = active.state.cursor_index.get().min(total);
695                let line_idx = Self::visual_line_index_for_cursor(&lines, cur_idx);
696                let new_idx = if to_end {
697                    lines[line_idx].end_char
698                } else {
699                    lines[line_idx].start_char
700                };
701                if shift {
702                    if active.state.selection_anchor.get().is_none() {
703                        active.state.selection_anchor.set(Some(cur_idx));
704                    }
705                } else {
706                    active.state.selection_anchor.set(None);
707                }
708                active.state.cursor_index.set(new_idx);
709                return;
710            }
711        }
712        if to_end {
713            active.state.move_line_end(shift);
714        } else {
715            active.state.move_line_home(shift);
716        }
717    }
718
719    /// Synchronizes the active focused text input's live buffer, clamped scroll offset,
720    /// and styling into the layout tree without snapping a multiline `<textarea>` back to
721    /// the caret (preserving manual wheel/scrollbar scrolling across paints and view updates).
722    pub fn sync_active_input_layout(&mut self) {
723        self.sync_active_input_layout_inner(false);
724    }
725
726    /// Synchronizes the active focused text input's live buffer and styling into the layout
727    /// tree and scrolls the caret into view (used on typing, edits, and caret navigation).
728    pub(crate) fn sync_active_input_layout_and_scroll_caret(&mut self) {
729        self.sync_active_input_layout_inner(true);
730    }
731
732    fn sync_active_input_layout_inner(&mut self, scroll_caret_into_view: bool) {
733        let Some(ref active) = self.active_focus else {
734            return;
735        };
736        let target_idx = active.input_index;
737        let target_id = active.input_id.clone();
738        let target_entity_id = active.entity_id;
739        let is_multiline = active.is_multiline;
740        let is_password =
741            !is_multiline && self.input_is_password(target_idx, target_id.as_deref(), target_entity_id);
742        let text_val = active.state.text.get();
743        let cursor_idx = active.state.cursor_index.get();
744        let prev_scroll_x = active.state.scroll_x.get();
745        let prev_scroll_y = active.state.scroll_y.get();
746        let focus_path = if is_multiline {
747            Self::find_layout_path_for_focus(
748                &self.root_blueprint,
749                &self.layout_root,
750                target_idx,
751                target_id.as_deref(),
752                target_entity_id,
753            )
754        } else {
755            None
756        };
757
758        let layout_match = Self::find_layout_for_focus_mut(
759            &self.root_blueprint,
760            &mut self.layout_root,
761            target_idx,
762            target_id.as_deref(),
763            target_entity_id,
764        );
765
766        let mut next_scroll_x = 0.0f32;
767        let mut next_scroll_y = prev_scroll_y.max(0.0);
768        let mut multiline_max_scroll: Option<f32> = None;
769        if let Some(layout) = layout_match {
770            let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
771            if !text_val.is_empty() {
772                let display_val = if is_password {
773                    Self::mask_password_text(&text_val)
774                } else {
775                    text_val
776                };
777                layout.text = Some(display_val.clone());
778                if let Some(c) = layout.style.caret_color {
779                    layout.style.color = c;
780                }
781                if is_multiline {
782                    let viewport_h = layout.geometry.content_box.height;
783                    if viewport_h > 0.0 {
784                        let (lines, line_step) = Self::layout_visual_lines(
785                            &display_val,
786                            layout.geometry.content_box.width,
787                            layout.style.font_size,
788                            layout.style.line_height,
789                            is_mono,
790                            layout.style.font_family,
791                        );
792                        let total_h = lines.len().max(1) as f32 * line_step;
793                        let max_scroll = (total_h - viewport_h).max(0.0);
794                        multiline_max_scroll = Some(max_scroll);
795                        next_scroll_y = if scroll_caret_into_view {
796                            let line_idx = Self::visual_line_index_for_cursor(&lines, cursor_idx);
797                            let cursor_y = lines.get(line_idx).map(|l| l.y).unwrap_or(0.0);
798                            Self::compute_multiline_scroll_y(
799                                cursor_y,
800                                line_step,
801                                total_h,
802                                viewport_h,
803                                prev_scroll_y,
804                            )
805                        } else {
806                            prev_scroll_y.clamp(0.0, max_scroll)
807                        };
808                    } else {
809                        next_scroll_y = prev_scroll_y.max(0.0);
810                    }
811                    layout.geometry.scroll_offset.x = 0.0;
812                    layout.geometry.scroll_offset.y = next_scroll_y;
813                } else {
814                    let (tw, th) = strata_layout::text::measure_text_bounds_with_family(
815                        &display_val,
816                        layout.style.font_size,
817                        layout.style.line_height,
818                        None,
819                        is_mono,
820                        layout.style.font_family,
821                    );
822                    if layout.geometry.content_box.width <= 0.0 {
823                        layout.geometry.content_box.width = tw;
824                    }
825                    layout.geometry.content_box.height =
826                        th.max(layout.geometry.content_box.height);
827                    let (_, computed_scroll_x, _) = Self::compute_input_text_metrics(
828                        &display_val,
829                        cursor_idx,
830                        prev_scroll_x,
831                        layout.geometry.content_box.width,
832                        layout.style.text_align,
833                        layout.style.font_size,
834                        layout.style.line_height,
835                        is_mono,
836                        layout.style.font_family,
837                    );
838                    next_scroll_x = computed_scroll_x;
839                    next_scroll_y = 0.0;
840                    layout.geometry.scroll_offset.x = next_scroll_x;
841                    layout.geometry.scroll_offset.y = 0.0;
842                }
843            } else {
844                next_scroll_y = 0.0;
845                if is_multiline && layout.geometry.content_box.height > 0.0 {
846                    multiline_max_scroll = Some(0.0);
847                }
848                layout.geometry.scroll_offset.x = 0.0;
849                layout.geometry.scroll_offset.y = 0.0;
850                let mut ph = None;
851                let mut bp_counter = 0;
852                let bp_match = if let Some(eid) = target_entity_id {
853                    self.root_blueprint.find_by_entity_id(eid)
854                } else {
855                    None
856                };
857                let bp_match = bp_match.or_else(|| {
858                    Self::find_input_blueprint(
859                        &self.root_blueprint,
860                        target_idx,
861                        target_id.as_deref(),
862                        &mut bp_counter,
863                    )
864                });
865                if let Some(bp) = bp_match {
866                    if let NodeBlueprint::Element { attributes, .. } = bp {
867                        for attr in attributes {
868                            if let strata_dom::Attribute::Property { key, value } = attr {
869                                if key == "placeholder" && !value.is_empty() {
870                                    ph = Some(value.clone());
871                                }
872                            }
873                        }
874                    }
875                }
876                if let Some(ph_str) = ph {
877                    layout.text = Some(ph_str);
878                    layout.style.color = strata_style::types::Color::new(140, 145, 155, 255);
879                } else {
880                    layout.text = Some(String::new());
881                }
882            }
883        } else if !is_multiline {
884            next_scroll_y = 0.0;
885        }
886
887        if let Some(ref active) = self.active_focus {
888            active.state.scroll_x.set(next_scroll_x);
889            active.state.scroll_y.set(next_scroll_y);
890        }
891
892        if is_multiline {
893            if let (Some(path), Some(max_scroll)) = (focus_path, multiline_max_scroll) {
894                if scroll_caret_into_view
895                    && (next_scroll_y - prev_scroll_y).abs() > 0.01
896                    && self
897                        .active_smooth_scroll
898                        .as_ref()
899                        .is_some_and(|t| t.container_path == path)
900                {
901                    self.active_smooth_scroll = None;
902                }
903                if let Some(ref id) = target_id {
904                    if !id.is_empty() {
905                        self.scroll_offsets_by_id
906                            .insert(id.clone(), (0.0, next_scroll_y));
907                        strata_dom::hooks::set_live_scroll_offset(id, 0.0, next_scroll_y);
908                    }
909                }
910                self.scroll_offsets.insert(path.clone(), (0.0, next_scroll_y));
911                if next_scroll_y > 0.0 {
912                    self.applied_scroll_offsets
913                        .insert(path.clone(), (0.0, next_scroll_y));
914                } else {
915                    self.applied_scroll_offsets.remove(&path);
916                }
917
918                // Keep the `<textarea>`'s interactive scrollbar synchronized when edits change
919                // content height or caret navigation scrolls the textarea.
920                let bar_idx = self.active_scrollbars.iter().position(|b| {
921                    b.path == path
922                        || target_id
923                            .as_deref()
924                            .is_some_and(|id| !id.is_empty() && b.is_id && b.id == id)
925                });
926                let needs_rebuild = match bar_idx {
927                    Some(idx) => {
928                        let bar = &mut self.active_scrollbars[idx];
929                        if (bar.max_scroll_y - max_scroll).abs() > 0.5 {
930                            true
931                        } else {
932                            let clamped = next_scroll_y.clamp(0.0, bar.max_scroll_y);
933                            bar.scroll_y = clamped;
934                            bar.thumb_bounds.y =
935                                if bar.max_scroll_y > 0.0 && bar.available_travel > 0.0 {
936                                    bar.track_bounds.y
937                                        + (clamped / bar.max_scroll_y) * bar.available_travel
938                                } else {
939                                    bar.track_bounds.y
940                                };
941                            false
942                        }
943                    }
944                    None => max_scroll > 0.0,
945                };
946                if needs_rebuild {
947                    self.rebuild_active_scrollbars();
948                }
949            }
950        }
951        self.update_gtk_ime_location();
952    }
953
954    /// Calculates the exact character index from an x offset within a single line using active font metrics and character advances.
955    pub fn calculate_exact_char_index_at_offset(
956        text: &str,
957        rel_x: f32,
958        font_size: f32,
959        line_height: f32,
960        is_mono: bool,
961        font_family: strata_primitives::AtomId,
962    ) -> usize {
963        if rel_x <= 0.0 || text.is_empty() {
964            return 0;
965        }
966        let chars: Vec<char> = text.chars().collect();
967        let total = chars.len();
968
969        let (full_w, _) = strata_layout::text::measure_text_bounds_with_family(
970            text,
971            font_size,
972            line_height,
973            None,
974            is_mono,
975            font_family,
976        );
977        if rel_x >= full_w {
978            return total;
979        }
980
981        let mut prev_w = 0.0f32;
982        for i in 1..=total {
983            let prefix: String = chars[..i].iter().collect();
984            let (w, _) = strata_layout::text::measure_text_bounds_with_family(
985                &prefix,
986                font_size,
987                line_height,
988                None,
989                is_mono,
990                font_family,
991            );
992            let mid = (prev_w + w) / 2.0;
993            if rel_x < mid {
994                return i - 1;
995            } else if rel_x <= w {
996                return i;
997            }
998            prev_w = w;
999        }
1000        total
1001    }
1002
1003    /// Computes caret rectangle and optional scroll update / selection rects for the active input.
1004    fn compute_active_caret_and_selection(
1005        &self,
1006        active: &ActiveInput,
1007        layout: &LayoutNode,
1008        include_selection: bool,
1009    ) -> Option<(strata_layout::Rect, Vec<strata_layout::Rect>, f32, f32)> {
1010        let content_box = layout.geometry.content_box;
1011        if content_box.width <= 0.0 || content_box.height <= 0.0 {
1012            return None;
1013        }
1014
1015        let font_size = layout.style.font_size;
1016        let line_height = layout.style.line_height;
1017        let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
1018        let font_family = layout.style.font_family;
1019        let is_password = !active.is_multiline
1020            && self.input_is_password(active.input_index, active.input_id.as_deref(), active.entity_id);
1021        let raw_text = active.state.text.get();
1022        let text = if is_password {
1023            Self::mask_password_text(&raw_text)
1024        } else {
1025            raw_text
1026        };
1027        let chars: Vec<char> = text.chars().collect();
1028        let total_chars = chars.len();
1029        let cursor_idx = active.state.cursor_index.get().min(total_chars);
1030        let caret_w = 2.0f32;
1031
1032        if active.is_multiline {
1033            let (lines, line_step) = Self::layout_visual_lines(
1034                &text,
1035                content_box.width,
1036                font_size,
1037                line_height,
1038                is_mono,
1039                font_family,
1040            );
1041            let (line_idx, caret_rel_x) = Self::visual_cursor_location(
1042                &chars,
1043                &lines,
1044                cursor_idx,
1045                font_size,
1046                line_height,
1047                is_mono,
1048                font_family,
1049            );
1050            let line_y = lines.get(line_idx).map(|l| l.y).unwrap_or(0.0);
1051            let total_h = lines.len().max(1) as f32 * line_step;
1052            let max_scroll = (total_h - content_box.height).max(0.0);
1053            let scroll_y = active.state.scroll_y.get().clamp(0.0, max_scroll);
1054            let caret_h = line_step.min(content_box.height).max(12.0);
1055            let caret_x = (content_box.x + caret_rel_x)
1056                .clamp(content_box.x, content_box.x + (content_box.width - caret_w).max(0.0));
1057            let caret_y = content_box.y + line_y - scroll_y;
1058            let caret_rect = strata_layout::Rect::new(caret_x, caret_y, caret_w, caret_h);
1059
1060            let mut sel_rects = Vec::new();
1061            if include_selection {
1062                if let Some((start, end)) = active.state.selection_range() {
1063                    let s = start.min(total_chars);
1064                    let e = end.min(total_chars);
1065                    if s < e {
1066                        let sel_h = line_step.min(content_box.height);
1067                        for line in &lines {
1068                            let line_span_end = line.next_start.max(line.end_char);
1069                            if e <= line.start_char && !(s == e) {
1070                                continue;
1071                            }
1072                            if s >= line_span_end && !(s == line.start_char && line.start_char == line.end_char) {
1073                                continue;
1074                            }
1075                            let seg_start = s.max(line.start_char).min(line.end_char);
1076                            let seg_end = e.min(line.end_char).max(seg_start);
1077                            let start_x = Self::measure_char_slice_width(
1078                                &chars,
1079                                line.start_char,
1080                                seg_start,
1081                                font_size,
1082                                line_height,
1083                                is_mono,
1084                                font_family,
1085                            );
1086                            let mut sel_w = Self::measure_char_slice_width(
1087                                &chars,
1088                                seg_start,
1089                                seg_end,
1090                                font_size,
1091                                line_height,
1092                                is_mono,
1093                                font_family,
1094                            );
1095                            if e > line.end_char {
1096                                sel_w += font_size * 0.3;
1097                            }
1098                            if sel_w > 0.0 {
1099                                sel_rects.push(strata_layout::Rect::new(
1100                                    content_box.x + start_x,
1101                                    content_box.y + line.y - scroll_y,
1102                                    sel_w,
1103                                    sel_h,
1104                                ));
1105                            }
1106                        }
1107                    }
1108                }
1109            }
1110
1111            return Some((caret_rect, sel_rects, 0.0, scroll_y));
1112        }
1113
1114        let (align_offset, scroll_x, cursor_w) = Self::compute_input_text_metrics(
1115            &text,
1116            cursor_idx,
1117            active.state.scroll_x.get(),
1118            content_box.width,
1119            layout.style.text_align,
1120            font_size,
1121            line_height,
1122            is_mono,
1123            font_family,
1124        );
1125
1126        let caret_h = (font_size * 1.2).min(content_box.height).max(14.0);
1127        let caret_y = content_box.y + ((content_box.height - caret_h) / 2.0).max(0.0);
1128        let max_caret_x = content_box.x + (content_box.width - caret_w).max(0.0);
1129        let caret_x =
1130            (content_box.x + align_offset + cursor_w - scroll_x).clamp(content_box.x, max_caret_x);
1131        let caret_rect = strata_layout::Rect::new(caret_x, caret_y, caret_w, caret_h);
1132
1133        let mut sel_rects = Vec::new();
1134        if include_selection {
1135            if let Some((start, end)) = active.state.selection_range() {
1136                let start_clamped = start.min(total_chars);
1137                let end_clamped = end.min(total_chars);
1138                if start_clamped < end_clamped {
1139                    let start_w = Self::measure_char_slice_width(
1140                        &chars,
1141                        0,
1142                        start_clamped,
1143                        font_size,
1144                        line_height,
1145                        is_mono,
1146                        font_family,
1147                    );
1148                    let sel_w = Self::measure_char_slice_width(
1149                        &chars,
1150                        start_clamped,
1151                        end_clamped,
1152                        font_size,
1153                        line_height,
1154                        is_mono,
1155                        font_family,
1156                    );
1157                    let sel_h = (font_size * 1.25).min(content_box.height);
1158                    let sel_y = content_box.y + ((content_box.height - sel_h) / 2.0).max(0.0);
1159                    let sel_x = content_box.x + align_offset + start_w - scroll_x;
1160                    sel_rects.push(strata_layout::Rect::new(sel_x, sel_y, sel_w, sel_h));
1161                }
1162            }
1163        }
1164
1165        Some((caret_rect, sel_rects, scroll_x, 0.0))
1166    }
1167
1168    /// Renders the visible insertion caret cursor and selection highlight for the currently focused text input.
1169    pub fn render_active_input_caret(&mut self) {
1170        let Some(ref active) = self.active_focus else {
1171            return;
1172        };
1173
1174        let Some(layout) = Self::find_layout_for_focus(
1175            &self.root_blueprint,
1176            &self.layout_root,
1177            active.input_index,
1178            active.input_id.as_deref(),
1179            active.entity_id,
1180        ) else {
1181            return;
1182        };
1183
1184        let content_box = layout.geometry.content_box;
1185        let text_color = layout.style.color;
1186        let mut caret_color = layout.style.caret_color.unwrap_or(text_color);
1187        if caret_color.a == 0 {
1188            caret_color = strata_style::types::Color::new(236, 233, 225, 255);
1189        }
1190
1191        let Some((caret_rect, sel_rects, scroll_x, _scroll_y)) =
1192            self.compute_active_caret_and_selection(active, layout, true)
1193        else {
1194            return;
1195        };
1196
1197        if !active.is_multiline {
1198            active.state.scroll_x.set(scroll_x);
1199        }
1200
1201        let has_sel = active.state.has_selection();
1202        let elapsed_ms = self.elapsed_since(self.caret_blink_epoch).as_millis();
1203        let is_blink_on = (elapsed_ms / 530).is_multiple_of(2);
1204        let draw_caret = !has_sel && is_blink_on;
1205
1206        if sel_rects.is_empty() && !draw_caret {
1207            return;
1208        }
1209
1210        self.display_list
1211            .push(strata_render::compositor::DrawCommand::PushClip {
1212                bounds: content_box,
1213                radius: strata_style::types::BorderRadius::all(0.0),
1214            });
1215
1216        for sel_bounds in sel_rects {
1217            self.display_list
1218                .push(strata_render::compositor::DrawCommand::DrawRect {
1219                    bounds: sel_bounds,
1220                    color: strata_style::types::Color::rgba(59, 130, 246, 120),
1221                });
1222        }
1223
1224        if draw_caret {
1225            self.display_list
1226                .push(strata_render::compositor::DrawCommand::DrawRect {
1227                    bounds: caret_rect,
1228                    color: caret_color,
1229                });
1230        }
1231
1232        self.display_list
1233            .push(strata_render::compositor::DrawCommand::PopClip);
1234    }
1235
1236    /// Computes the exact bounding box of the active text caret if an input is currently focused.
1237    pub fn active_caret_rect(&self) -> Option<strata_layout::Rect> {
1238        let active = self.active_focus.as_ref()?;
1239        let layout = Self::find_layout_for_focus(
1240            &self.root_blueprint,
1241            &self.layout_root,
1242            active.input_index,
1243            active.input_id.as_deref(),
1244            active.entity_id,
1245        )?;
1246        self.compute_active_caret_and_selection(active, layout, false)
1247            .map(|(caret_rect, _, _, _)| caret_rect)
1248    }
1249
1250    /// Synchronizes the IME candidate window location with the active caret position.
1251    pub fn sync_ime_cursor_location<W: strata_platform::PlatformWindow>(&self, window: &mut W) {
1252        if let Some(rect) = self.active_caret_rect() {
1253            window.set_ime_cursor_location(
1254                rect.x.round() as i32,
1255                rect.y.round() as i32,
1256                rect.width.round() as i32,
1257                rect.height.round() as i32,
1258            );
1259            if let Some(ref active) = self.active_focus {
1260                if self.active_input_is_password(active) {
1261                    window.set_ime_surrounding_text("", 0);
1262                } else {
1263                    window.set_ime_surrounding_text(
1264                        &active.state.text.get(),
1265                        active.state.cursor_index.get() as i32,
1266                    );
1267                }
1268            }
1269        } else {
1270            window.reset_ime();
1271        }
1272    }
1273
1274    /// Directly updates GTK IME context with current caret location if running on Linux GTK.
1275    pub fn update_gtk_ime_location(&self) {
1276        #[cfg(target_os = "linux")]
1277        {
1278            if let Some(rect) = self.active_caret_rect() {
1279                strata_platform::gtk_set_ime_cursor_location(
1280                    rect.x.round() as i32,
1281                    rect.y.round() as i32,
1282                    rect.width.round() as i32,
1283                    rect.height.round() as i32,
1284                );
1285                if let Some(ref active) = self.active_focus {
1286                    if self.active_input_is_password(active) {
1287                        strata_platform::gtk_set_ime_surrounding_text("", 0);
1288                    } else {
1289                        strata_platform::gtk_set_ime_surrounding_text(
1290                            &active.state.text.get(),
1291                            active.state.cursor_index.get() as i32,
1292                        );
1293                    }
1294                }
1295            } else {
1296                strata_platform::gtk_reset_ime();
1297            }
1298        }
1299    }
1300}