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