Skip to main content

xrack_layout/
viewport.rs

1use crate::{
2    Interaction, LayoutNode, Point, Rect, ScrollBarGeometry, ScrollLayout,
3    scroll_gesture::PanDevice, view_cells::ViewCells,
4};
5use std::{
6    collections::BTreeMap,
7    time::{Duration, Instant},
8};
9use xrack_runtime::{
10    Component, GeometryHandle, Length, Node, Orientation, ScrollAction, ScrollAlignment,
11    ScrollRequest, ViewportHandle, ViewportMotion, is_window_overlay,
12};
13
14pub(crate) type MotionOwners = Vec<(ViewportHandle, [bool; 2])>;
15
16pub(crate) fn record_motion(owners: &mut MotionOwners, item: &LayoutNode, axis: Orientation) {
17    let Some(handle) = item
18        .viewport_handle
19        .as_ref()
20        .filter(|handle| handle.observes_motion())
21    else {
22        return;
23    };
24    record_motion_owner(owners, handle, axis);
25}
26
27pub(crate) fn record_motion_owner(
28    owners: &mut MotionOwners,
29    handle: &ViewportHandle,
30    axis: Orientation,
31) {
32    let index = usize::from(axis == Orientation::Vertical);
33    if let Some((_, axes)) = owners.iter_mut().find(|(owner, _)| owner == handle) {
34        axes[index] = true;
35    } else {
36        let mut axes = [false; 2];
37        axes[index] = true;
38        owners.push((handle.clone(), axes));
39    }
40}
41
42#[derive(Clone, Debug, Default)]
43pub(crate) struct MotionState {
44    owners: MotionOwners,
45}
46
47impl MotionState {
48    pub fn update(&mut self, owners: MotionOwners, motion: ViewportMotion) {
49        for (handle, _) in self.owners.drain(..) {
50            if !owners.iter().any(|(owner, _)| owner == &handle) {
51                handle.publish_motion(ViewportMotion::Idle);
52            }
53        }
54        self.owners = owners;
55        self.set_phase(motion);
56    }
57
58    pub fn set_phase(&self, motion: ViewportMotion) {
59        for (handle, _) in &self.owners {
60            handle.publish_motion(motion);
61        }
62    }
63
64    pub fn retain_axes(&mut self, axes: [bool; 2]) {
65        self.owners.retain_mut(|(handle, owned)| {
66            for (owned, axis) in owned.iter_mut().zip(axes) {
67                *owned &= axis;
68            }
69            let keep = owned.contains(&true);
70            if !keep {
71                handle.publish_motion(ViewportMotion::Idle);
72            }
73            keep
74        });
75    }
76
77    pub fn contains(&self, handle: &ViewportHandle) -> bool {
78        self.owners.iter().any(|(owner, _)| owner == handle)
79    }
80
81    pub fn clear(&mut self) {
82        self.set_phase(ViewportMotion::Idle);
83        self.owners.clear();
84    }
85
86    pub fn reconcile(&mut self, layout: &LayoutNode, device: PanDevice) {
87        fn live(
88            item: &LayoutNode,
89            handle: &ViewportHandle,
90            axes: [bool; 2],
91            device: PanDevice,
92        ) -> bool {
93            if !item.visible || !item.enabled {
94                return false;
95            }
96            if item.viewport_handle.as_ref() == Some(handle) {
97                let bounds = item.clip_rect(item.bounds);
98                bounds.width > 0.0
99                    && bounds.height > 0.0
100                    && [Orientation::Horizontal, Orientation::Vertical]
101                        .into_iter()
102                        .zip(axes)
103                        .any(|(axis, moved)| {
104                            moved
105                                && item.accepts_pan(axis, device)
106                                && item
107                                    .scroll_on(axis)
108                                    .is_some_and(|scroll| scroll.max_offset > 0.0)
109                        })
110            } else {
111                item.children
112                    .iter()
113                    .any(|child| live(child, handle, axes, device))
114            }
115        }
116        self.owners.retain(|(handle, axes)| {
117            let keep = live(layout, handle, *axes, device);
118            if !keep {
119                handle.publish_motion(ViewportMotion::Idle);
120            }
121            keep
122        });
123    }
124}
125
126#[derive(Clone, Debug)]
127pub(crate) struct UserScrollChange {
128    target: ViewportHandle,
129    before: [Option<f32>; 2],
130}
131
132impl UserScrollChange {
133    pub(crate) fn record(
134        changes: &mut Vec<Self>,
135        item: &LayoutNode,
136        axis: Orientation,
137        offset: f32,
138    ) {
139        let Some(target) = item
140            .viewport_handle
141            .as_ref()
142            .filter(|handle| handle.observes_user_scroll())
143        else {
144            return;
145        };
146        let index = usize::from(axis == Orientation::Vertical);
147        if let Some(change) = changes.iter_mut().find(|change| &change.target == target) {
148            change.before[index].get_or_insert(offset);
149        } else {
150            let mut before = [None; 2];
151            before[index] = Some(offset);
152            changes.push(Self {
153                target: target.clone(),
154                before,
155            });
156        }
157    }
158
159    pub(crate) fn commit(
160        changes: &mut Vec<Self>,
161        item: &LayoutNode,
162        axis: Orientation,
163        before: f32,
164        after: f32,
165    ) {
166        item.write_bound_offset(axis, after);
167        Self::record(changes, item, axis, before);
168    }
169}
170
171impl LayoutNode {
172    #[doc(hidden)]
173    pub fn scroll_axis_reversed(&self, axis: Orientation) -> bool {
174        axis == Orientation::Horizontal
175            && (self.horizontal_scroll_reversed
176                || self.table.as_ref().is_some_and(|table| table.mirrored()))
177    }
178
179    #[doc(hidden)]
180    pub fn scroll_viewport(&self, axis: Orientation) -> Rect {
181        if let Some(strip) = self.tab_strip {
182            return strip;
183        }
184        self.table.as_deref().map_or_else(
185            || {
186                self.content_bounds
187                    .as_deref()
188                    .copied()
189                    .unwrap_or(self.bounds)
190            },
191            |table| match axis {
192                Orientation::Horizontal => table.scrollable_body(),
193                Orientation::Vertical => table.rows_area(),
194            },
195        )
196    }
197
198    pub(crate) fn bound_offset(&self, axis: Orientation) -> Option<f32> {
199        self.viewport_handle.as_ref()?.bound_offset(axis)
200    }
201
202    pub(crate) fn write_bound_offset(&self, axis: Orientation, offset: f32) {
203        if let Some(handle) = &self.viewport_handle {
204            handle.write_bound_offset(axis, offset);
205        }
206    }
207}
208
209/// Delivery is tied to the component instance that consumed the input.
210pub struct ScrollDelivery {
211    target: ViewportHandle,
212    path: Vec<usize>,
213    event: &'static str,
214}
215
216impl ScrollDelivery {
217    pub fn apply(&self, component: &mut impl Component, scene: &Node) -> bool {
218        scene.at_path(&self.path).is_some_and(|node| {
219            node.viewport_handle.as_ref() == Some(&self.target)
220                && (self.event != "refresh-requested" || node.can_pull_to_refresh())
221                && component.dispatch_at(scene, &self.path, self.event)
222        })
223    }
224}
225
226struct ScrollActivity {
227    viewport: Option<ViewportHandle>,
228    axis: Orientation,
229    offset: f32,
230    until: Option<Instant>,
231}
232
233#[derive(Default)]
234pub struct LayoutObservers {
235    present: Vec<ViewportHandle>,
236    geometry: BTreeMap<usize, GeometryHandle>,
237    scroll_controls: Vec<(Vec<usize>, GeometryHandle)>,
238    scroll_activity: BTreeMap<usize, ScrollActivity>,
239}
240
241pub type ViewportObservers = LayoutObservers;
242
243impl LayoutObservers {
244    pub fn sync(&mut self, scene: &Node, layout: &LayoutNode) {
245        fn publish(
246            node: &Node,
247            item: &LayoutNode,
248            parent: Rect,
249            viewports: &mut Vec<ViewportHandle>,
250            geometry: &mut BTreeMap<usize, GeometryHandle>,
251            scroll_controls: &mut Vec<(Vec<usize>, GeometryHandle)>,
252            path: &mut Vec<usize>,
253        ) {
254            if let Some(handle) = &node.range_position_handle {
255                handle.publish_direction(item.layout_direction);
256            }
257            if let Some(handle) = &node.viewport_handle
258                && item.visible
259            {
260                let viewport = viewport(item);
261                let offset = |axis| item.scroll_on(axis).map_or(0.0, |scroll| scroll.offset);
262                handle.publish(
263                    Length(-f64::from(offset(Orientation::Horizontal))),
264                    Length(-f64::from(offset(Orientation::Vertical))),
265                    Length(f64::from(viewport.width)),
266                    Length(f64::from(viewport.height)),
267                );
268                if node.kind == "ScrollView" {
269                    let mut width = Length::default();
270                    let mut height = Length::default();
271                    for bar in item.scroll_bars(node) {
272                        match bar.orientation {
273                            Orientation::Horizontal => height = Length(f64::from(bar.track.height)),
274                            Orientation::Vertical => width = Length(f64::from(bar.track.width)),
275                        }
276                    }
277                    handle.publish_scroll_bar_extent(width, height);
278                }
279                for axis in [Orientation::Horizontal, Orientation::Vertical] {
280                    let rect = item.scroll_viewport(axis);
281                    let page = match axis {
282                        Orientation::Horizontal => rect.width,
283                        Orientation::Vertical => rect.height,
284                    };
285                    let scroll = item.scroll_on(axis).unwrap_or(ScrollLayout {
286                        offset: 0.0,
287                        max_offset: 0.0,
288                    });
289                    handle.publish_scroll_range(axis, scroll.offset, page, scroll.max_offset);
290                }
291                viewports.push(handle.clone());
292            }
293            if item.visible
294                && (node.geometry_handle.is_some() || node.instance_geometry_handle.is_some())
295            {
296                let rect = item.bounds;
297                let window = item.window_bounds(rect);
298                let available = if xrack_runtime::is_pane(node.kind) {
299                    let inner = crate::linear::Padding::read(node).inner_rect(rect);
300                    [inner.width, inner.height]
301                } else if node.application_window {
302                    item.content_bounds
303                        .as_deref()
304                        .map_or([0.0; 2], |rect| [rect.width, rect.height])
305                } else {
306                    [0.0; 2]
307                };
308                if let Some(handle) = &node.geometry_handle
309                    && matches!(node.kind, "ScrollBar" | "ScrollIndicator")
310                {
311                    let (position, size) = item
312                        .scroll_control_geometry(node)
313                        .map_or((0.0, 0.0), |bar| bar.normalized_thumb());
314                    handle.publish_scroll_thumb(position, size);
315                    scroll_controls.push((path.clone(), handle.clone()));
316                }
317                for handle in node
318                    .geometry_handle
319                    .iter()
320                    .chain(node.instance_geometry_handle.iter())
321                {
322                    handle.publish_with_content(
323                        [
324                            rect.x - parent.x,
325                            rect.y - parent.y,
326                            rect.width,
327                            rect.height,
328                        ],
329                        [window.x, window.y, window.width, window.height],
330                        available,
331                        true,
332                    );
333                    geometry.insert(handle.identity(), handle.clone());
334                }
335            }
336            for (index, child, layout) in item.children_in_scene_order(node) {
337                path.push(index);
338                publish(
339                    child,
340                    layout,
341                    item.bounds,
342                    viewports,
343                    geometry,
344                    scroll_controls,
345                    path,
346                );
347                path.pop();
348            }
349        }
350
351        let mut next = Vec::new();
352        let mut geometry = BTreeMap::new();
353        self.scroll_controls.clear();
354        publish(
355            scene,
356            layout,
357            layout.bounds,
358            &mut next,
359            &mut geometry,
360            &mut self.scroll_controls,
361            &mut Vec::new(),
362        );
363        for handle in self.present.drain(..) {
364            if !next.contains(&handle) {
365                reset(&handle);
366            }
367        }
368        self.present = next;
369        for (id, handle) in std::mem::take(&mut self.geometry) {
370            if !geometry.contains_key(&id) {
371                handle.clear();
372                self.scroll_activity.remove(&id);
373            }
374        }
375        self.geometry = geometry;
376    }
377
378    /// Samples input against the same mounted bars used for hit testing.
379    pub fn sync_scroll_activity(
380        &mut self,
381        scene: &Node,
382        layout: &LayoutNode,
383        input: &Interaction,
384        now: Instant,
385    ) {
386        for (path, handle) in &self.scroll_controls {
387            if !handle.observes_scroll_interaction() {
388                continue;
389            }
390            let id = handle.identity();
391            let Some((node, bar)) =
392                scene
393                    .at_path(path)
394                    .zip(layout.at_path(path))
395                    .and_then(|(node, item)| {
396                        let bar = item.scroll_control_geometry(node)?;
397                        (node.geometry_handle.as_ref() == Some(handle)
398                            && item.enabled
399                            && bar.scrollable())
400                        .then_some((node, bar))
401                    })
402            else {
403                self.scroll_activity.remove(&id);
404                handle.publish_scroll_interaction(false, false, false);
405                continue;
406            };
407            let viewport = node.scroll_target.clone();
408            let axis = bar.orientation;
409            let offset = bar.scroll.offset;
410            let sample = self
411                .scroll_activity
412                .entry(id)
413                .or_insert_with(|| ScrollActivity {
414                    viewport: viewport.clone(),
415                    axis,
416                    offset,
417                    until: None,
418                });
419            if sample.viewport != viewport || sample.axis != axis {
420                *sample = ScrollActivity {
421                    viewport,
422                    axis,
423                    offset,
424                    until: None,
425                };
426            } else if sample.offset != offset {
427                sample.offset = offset;
428                sample.until = Some(now + Duration::from_millis(180));
429            } else if sample.until.is_some_and(|until| now >= until) {
430                sample.until = None;
431            }
432            let (pressed, hovered) = input.scroll_bar_interaction(scene, layout, path, axis);
433            handle.publish_scroll_interaction(
434                pressed || hovered || sample.until.is_some(),
435                pressed,
436                hovered,
437            );
438        }
439    }
440
441    pub fn scroll_activity_deadline(&self) -> Option<Instant> {
442        self.scroll_activity
443            .values()
444            .filter_map(|sample| sample.until)
445            .min()
446    }
447
448    pub fn clear(&mut self) {
449        self.scroll_controls.clear();
450        self.scroll_activity.clear();
451        for handle in self.present.drain(..) {
452            reset(&handle);
453        }
454        for handle in std::mem::take(&mut self.geometry).into_values() {
455            handle.clear();
456        }
457    }
458}
459
460fn reset(handle: &ViewportHandle) {
461    let zero = Length::default();
462    handle.publish(zero, zero, zero, zero);
463    handle.publish_scroll_bar_extent(zero, zero);
464    for axis in [Orientation::Horizontal, Orientation::Vertical] {
465        handle.publish_scroll_range(axis, 0.0, 0.0, 0.0);
466    }
467}
468
469fn viewport(item: &LayoutNode) -> Rect {
470    item.table.as_ref().map_or_else(
471        || item.scroll_viewport(Orientation::Vertical),
472        |table| table.body,
473    )
474}
475
476fn find_path(node: &Node, handle: &ViewportHandle, path: &mut Vec<usize>) -> bool {
477    if node.viewport_handle.as_ref() == Some(handle) {
478        return true;
479    }
480    for (index, child) in node.materialized_children() {
481        path.push(index);
482        if find_path(child, handle, path) {
483            return true;
484        }
485        path.pop();
486    }
487    false
488}
489
490impl Interaction {
491    /// Queue the same refresh event as a completed pull gesture.
492    #[doc(hidden)]
493    pub fn request_viewport_refresh(
494        &mut self,
495        scene: &Node,
496        layout: &LayoutNode,
497        viewport: &ViewportHandle,
498    ) -> bool {
499        let mut path = Vec::new();
500        if self.refresh_request.is_some()
501            || !find_path(scene, viewport, &mut path)
502            || self.refresh_viewport(scene, layout, &path) != Some(viewport)
503        {
504            return false;
505        }
506        self.refresh_request = Some(viewport.clone());
507        true
508    }
509
510    /// Resolve movement after layout clamps offsets and replaces virtual rows.
511    pub fn take_scroll_events(&mut self, scene: &Node, layout: &LayoutNode) -> Vec<ScrollDelivery> {
512        let mut events: Vec<_> = std::mem::take(&mut self.user_scroll_changes)
513            .into_iter()
514            .filter_map(|change| {
515                let mut path = Vec::new();
516                if !find_path(scene, &change.target, &mut path) {
517                    return None;
518                }
519                let item = layout
520                    .at_path(&path)
521                    .filter(|item| item.visible && item.enabled)?;
522                let moved = [Orientation::Horizontal, Orientation::Vertical]
523                    .into_iter()
524                    .zip(change.before)
525                    .any(|(axis, offset)| {
526                        offset
527                            .zip(item.scroll_on(axis))
528                            .is_some_and(|(offset, scroll)| offset != scroll.offset)
529                    });
530                moved.then_some(ScrollDelivery {
531                    target: change.target,
532                    event: if scene
533                        .at_path(&path)
534                        .is_some_and(|node| node.kind == "Flickable")
535                    {
536                        "flicked"
537                    } else {
538                        "scrolled"
539                    },
540                    path,
541                })
542            })
543            .collect();
544        if let Some(target) = self.refresh_request.take() {
545            let mut path = Vec::new();
546            if find_path(scene, &target, &mut path)
547                && self.refresh_viewport(scene, layout, &path) == Some(&target)
548            {
549                events.push(ScrollDelivery {
550                    target,
551                    path,
552                    event: "refresh-requested",
553                });
554            }
555        }
556        events
557    }
558
559    pub fn clear_scroll_events(&mut self) {
560        self.user_scroll_changes.clear();
561        self.refresh_request = None;
562    }
563
564    pub fn apply_scroll_requests(
565        &mut self,
566        scene: &Node,
567        layout: &LayoutNode,
568        requests: impl IntoIterator<Item = ScrollRequest>,
569    ) -> bool {
570        let mut changed = false;
571        for request in requests {
572            let mut path = Vec::new();
573            if !find_path(scene, &request.target, &mut path) {
574                continue;
575            }
576            let (Some(node), Some(item)) = (
577                scene.at_path(&path),
578                layout.at_path(&path).filter(|item| item.visible),
579            ) else {
580                continue;
581            };
582            match request.action {
583                ScrollAction::CancelFlick => {
584                    changed |= self.cancel_viewport_flick(&request.target);
585                }
586                ScrollAction::ReturnToBounds => {
587                    changed |= self.return_viewport_to_bounds(&request.target);
588                }
589                ScrollAction::To { x, y } => {
590                    for (axis, offset) in [(Orientation::Horizontal, x), (Orientation::Vertical, y)]
591                    {
592                        changed |= self.set_viewport_offset(&path, item, axis, offset.0);
593                    }
594                }
595                ScrollAction::By { dx, dy } => {
596                    for (axis, delta) in
597                        [(Orientation::Horizontal, dx), (Orientation::Vertical, dy)]
598                    {
599                        changed |= self.scroll_viewport_by(&path, item, axis, delta.0);
600                    }
601                }
602                ScrollAction::StepBar {
603                    axis,
604                    step_size,
605                    direction,
606                } => {
607                    if let Some(scroll) = item.scroll_on(axis) {
608                        let viewport = item.scroll_viewport(axis);
609                        let page = match axis {
610                            Orientation::Horizontal => viewport.width,
611                            Orientation::Vertical => viewport.height,
612                        };
613                        let step =
614                            ScrollBarGeometry::viewport_step(page, scroll.max_offset, step_size);
615                        changed |= self.scroll_viewport_by(
616                            &path,
617                            item,
618                            axis,
619                            direction.delta(f64::from(step)),
620                        );
621                    }
622                }
623                ScrollAction::ToChild {
624                    target,
625                    horizontal,
626                    vertical,
627                } => {
628                    let viewport_depth = path.len();
629                    if !find_scroll_child(node, target, &mut path) || path.len() <= viewport_depth {
630                        continue;
631                    }
632                    let Some(item) = layout.at_path(&path).filter(|item| item.visible) else {
633                        continue;
634                    };
635                    let mode = RevealMode::Child {
636                        viewport_depth,
637                        horizontal,
638                        vertical,
639                    };
640                    let plan = plan_scroll(
641                        (scene, layout),
642                        &path,
643                        item.bounds,
644                        mode,
645                        |path, item, axis, layout_offset| {
646                            self.current_viewport_offset(path, item, axis)
647                                .unwrap_or(layout_offset)
648                        },
649                    );
650                    if let Some(plan) = plan {
651                        changed |= self.apply_reveal_plan(layout, &path, plan);
652                    }
653                }
654                ScrollAction::ToIndex { index, alignment } => {
655                    if let Ok(index) = usize::try_from(index) {
656                        changed |= self.position_row(&path, node, item, index, alignment);
657                    }
658                }
659                ScrollAction::ToBusinessKey { key, alignment } => {
660                    if let Some(index) = node
661                        .row_locator
662                        .as_ref()
663                        .and_then(|locator| locator.business_position(key))
664                    {
665                        changed |= self.position_row(&path, node, item, index, alignment);
666                    }
667                }
668                ScrollAction::ToRowKey {
669                    key,
670                    source_index,
671                    alignment,
672                } => {
673                    if let Some(index) = node.displayed_row_for_key(key, source_index) {
674                        changed |= self.position_row(&path, node, item, index, alignment);
675                    }
676                }
677                ScrollAction::ToColumn { column, alignment } => {
678                    changed |= self.position_column(&path, item, column, alignment);
679                }
680                ScrollAction::ToCell {
681                    row,
682                    column,
683                    horizontal,
684                    vertical,
685                } => {
686                    if let Ok(row) = usize::try_from(row) {
687                        changed |= self.position_cell(
688                            &path,
689                            node,
690                            item,
691                            (row, column),
692                            (horizontal, vertical),
693                        );
694                    }
695                }
696                ScrollAction::ToCellAtRowKey {
697                    key,
698                    source_index,
699                    column,
700                    horizontal,
701                    vertical,
702                } => {
703                    if let Some(row) = node.displayed_row_for_key(key, source_index) {
704                        changed |= self.position_cell(
705                            &path,
706                            node,
707                            item,
708                            (row, column),
709                            (horizontal, vertical),
710                        );
711                    }
712                }
713            }
714        }
715        changed
716    }
717
718    fn position_cell(
719        &mut self,
720        path: &[usize],
721        node: &Node,
722        item: &LayoutNode,
723        (row, column): (usize, i64),
724        (horizontal, vertical): (ScrollAlignment, ScrollAlignment),
725    ) -> bool {
726        // Geometry comes from the fresh scene, including column visibility and resizing.
727        if !node
728            .list
729            .zip(item.table.as_ref())
730            .is_some_and(|(list, table)| {
731                row < list.row_count
732                    && usize::try_from(column).is_ok_and(|column| table.is_column_visible(column))
733            })
734        {
735            return false;
736        }
737        let x = self.position_column(path, item, column, horizontal);
738        let y = self.position_row(path, node, item, row, vertical);
739        x || y
740    }
741
742    fn position_row(
743        &mut self,
744        path: &[usize],
745        node: &Node,
746        item: &LayoutNode,
747        index: usize,
748        alignment: ScrollAlignment,
749    ) -> bool {
750        if !node.list.is_some_and(|list| index < list.row_count) {
751            return false;
752        }
753        let view = viewport(item);
754        let cells = ViewCells::new(node, view.width);
755        self.position_axis(
756            path,
757            item,
758            Orientation::Vertical,
759            (cells.top(index) as f32, cells.height(index)),
760            cells.leading_clearance(index, view.height),
761            alignment,
762        )
763    }
764
765    fn position_column(
766        &mut self,
767        path: &[usize],
768        item: &LayoutNode,
769        column: i64,
770        alignment: ScrollAlignment,
771    ) -> bool {
772        let Some((column, table)) = usize::try_from(column).ok().zip(item.table.as_ref()) else {
773            return false;
774        };
775        let Some((start, width)) = table.column_scroll_extent(column) else {
776            return false;
777        };
778        self.position_axis(
779            path,
780            item,
781            Orientation::Horizontal,
782            (start, width),
783            0.0,
784            alignment,
785        )
786    }
787
788    fn position_axis(
789        &mut self,
790        path: &[usize],
791        item: &LayoutNode,
792        axis: Orientation,
793        (start, length): (f32, f32),
794        leading: f32,
795        alignment: ScrollAlignment,
796    ) -> bool {
797        let Some(scroll) = item.scroll_on(axis) else {
798            return false;
799        };
800        let offsets = match axis {
801            Orientation::Horizontal => self.horizontal_scroll_offsets(),
802            Orientation::Vertical => self.scroll_offsets(),
803        };
804        // Earlier commands in this delivery may have moved the same axis already.
805        let current = item
806            .bound_offset(axis)
807            .or_else(|| offsets.get(path).copied())
808            .unwrap_or(scroll.offset);
809        let viewport = item.scroll_viewport(axis);
810        let page = match axis {
811            Orientation::Horizontal => viewport.width,
812            Orientation::Vertical => viewport.height,
813        };
814        if page <= 0.0 {
815            return false;
816        }
817        let offset = position(
818            ScrollLayout::new(current + leading, scroll.max_offset + leading),
819            start,
820            length,
821            page - leading,
822            alignment,
823        );
824        self.set_viewport_offset(path, item, axis, f64::from(offset - leading))
825    }
826}
827
828/// Content viewports can reveal items that already have a stable layout path.
829pub(crate) fn reveals_focus(node: &Node, item: &LayoutNode) -> bool {
830    can_reveal_focus(node)
831        && [Orientation::Horizontal, Orientation::Vertical]
832            .into_iter()
833            .any(|axis| {
834                item.scroll_on(axis)
835                    .is_some_and(|axis| axis.max_offset > 0.0)
836            })
837}
838
839fn can_reveal_focus(node: &Node) -> bool {
840    matches!(node.kind, "ScrollView" | "Flickable")
841        && node.boolean("auto-reveal-focus", node.kind == "ScrollView")
842}
843
844pub(crate) fn plan_keyboard_avoidance(
845    scene: &Node,
846    layout: &LayoutNode,
847    editor: &[usize],
848    mut field: Rect,
849    keyboard: Rect,
850    previous: Option<(&[usize], f32)>,
851    require_visible: bool,
852) -> Option<(Vec<usize>, f32)> {
853    const GAP: f32 = 8.0;
854    let previous = previous.and_then(|(path, offset)| {
855        let item = layout.at_path(path)?;
856        matches!(scene.at_path(path)?.kind, "ScrollView" | "Flickable").then(|| {
857            (
858                path,
859                item.world_transform()
860                    .map_vector(Point { x: 0.0, y: offset })
861                    .y,
862            )
863        })
864    });
865    let applied_shift = |path: &[usize]| {
866        previous
867            .filter(|(owner, _)| path.len() > owner.len() && path.starts_with(owner))
868            .map_or(0.0, |(_, y)| y)
869    };
870    // Always compare against the original position so moving the keyboard
871    // away restores the layout, even if the shifted editor is already visible.
872    field.y -= applied_shift(editor);
873    let overlap = field.intersect(keyboard);
874    if overlap.width <= 0.0 || overlap.height <= 0.0 {
875        return None;
876    }
877    for depth in (0..editor.len()).rev() {
878        let path = &editor[..depth];
879        let node = scene.at_path(path)?;
880        if is_window_overlay(node.kind) {
881            break;
882        }
883        let item = layout.at_path(path)?;
884        if !item.visible || !item.enabled || !can_reveal_focus(node) {
885            continue;
886        }
887        let mut bounds = item.visible_window_bounds(item.scroll_viewport(Orientation::Vertical));
888        bounds.y -= applied_shift(path);
889        let visible = bounds.intersect(field);
890        if require_visible && (visible.width <= 0.0 || visible.height <= 0.0) {
891            continue;
892        }
893        let shifts = [
894            keyboard.y - GAP - field.y - field.height,
895            keyboard.y + keyboard.height + GAP - field.y,
896        ];
897        let shift = shifts
898            .into_iter()
899            .filter(|shift| {
900                field.y + shift >= bounds.y
901                    && field.y + field.height + shift <= bounds.y + bounds.height
902            })
903            .min_by(|left, right| left.abs().total_cmp(&right.abs()));
904        if let Some(shift) = shift
905            && let Some(local) = item.map_delta_from_window(Point { x: 0.0, y: shift })
906            && local.x.abs() < 0.01
907            && local.y.is_finite()
908        {
909            return Some((path.to_vec(), local.y));
910        }
911    }
912    None
913}
914
915pub(crate) struct ScrollPosition {
916    depth: usize,
917    axis: Orientation,
918    offset: f32,
919}
920
921#[derive(Clone, Copy)]
922enum RevealMode {
923    Focus,
924    Child {
925        viewport_depth: usize,
926        horizontal: ScrollAlignment,
927        vertical: ScrollAlignment,
928    },
929}
930
931fn independent_content(node: &Node) -> bool {
932    is_window_overlay(node.kind)
933        || node.is_control_part()
934        || matches!(node.kind, "Menu" | "Tooltip" | "Shortcut")
935}
936
937fn find_scroll_child(node: &Node, target: u64, path: &mut Vec<usize>) -> bool {
938    if independent_content(node) {
939        return false;
940    }
941    if node
942        .geometry_handle
943        .iter()
944        .chain(node.instance_geometry_handle.iter())
945        .any(|handle| handle.matches_scroll_target(target))
946    {
947        return true;
948    }
949    for (index, child) in node.materialized_children() {
950        path.push(index);
951        if find_scroll_child(child, target, path) {
952            return true;
953        }
954        path.pop();
955    }
956    false
957}
958
959pub(crate) fn plan_focus_scroll(
960    scene: &Node,
961    layout: &LayoutNode,
962    path: &[usize],
963    rect: Rect,
964) -> Option<Vec<ScrollPosition>> {
965    plan_scroll(
966        (scene, layout),
967        path,
968        rect,
969        RevealMode::Focus,
970        |_, _, _, offset| offset,
971    )
972}
973
974/// Resolve a complete reveal before changing any bound offsets. Each outer
975/// viewport receives the clipped rectangle produced by its inner viewport.
976fn plan_scroll(
977    (scene, layout): (&Node, &LayoutNode),
978    path: &[usize],
979    mut rect: Rect,
980    mode: RevealMode,
981    current_offset: impl Fn(&[usize], &LayoutNode, Orientation, f32) -> f32,
982) -> Option<Vec<ScrollPosition>> {
983    let focus = matches!(mode, RevealMode::Focus);
984    let scope = match mode {
985        RevealMode::Focus => 0,
986        RevealMode::Child { viewport_depth, .. } => viewport_depth,
987    };
988    let mut ancestors = Vec::with_capacity(path.len() + 1);
989    let (mut node, mut item) = (scene, layout);
990    ancestors.push((node, item));
991    for &index in path {
992        node = node.child_at(index)?;
993        item = item.child_at(index)?;
994        ancestors.push((node, item));
995    }
996    let mut plan = Vec::new();
997    for depth in (scope + 1..ancestors.len()).rev() {
998        let (child, item) = ancestors[depth];
999        if is_window_overlay(child.kind) {
1000            let clipped = item.clip_rect(rect);
1001            return (clipped.width > 0.0 && clipped.height > 0.0).then_some(plan);
1002        }
1003        rect = item.local_transform().map_rect(rect);
1004        let (parent, item) = ancestors[depth - 1];
1005        if !item.visible || focus && !item.enabled || parent.is_control_part() {
1006            return None;
1007        }
1008        let content_viewport = matches!(parent.kind, "ScrollView" | "Flickable");
1009        if if focus {
1010            reveals_focus(parent, item)
1011        } else {
1012            content_viewport
1013        } {
1014            for axis in [Orientation::Horizontal, Orientation::Vertical] {
1015                let Some(scroll) = item
1016                    .scroll_on(axis)
1017                    .filter(|scroll| scroll.max_offset > 0.0)
1018                else {
1019                    continue;
1020                };
1021                let viewport = item.scroll_viewport(axis);
1022                let reversed = item.scroll_axis_reversed(axis);
1023                let before = current_offset(&path[..depth - 1], item, axis, scroll.offset);
1024                shift_rect(&mut rect, axis, reversed, before - scroll.offset);
1025                let (start, length, page) = match axis {
1026                    Orientation::Horizontal => (
1027                        if reversed {
1028                            viewport.x + viewport.width - rect.x - rect.width
1029                        } else {
1030                            rect.x - viewport.x
1031                        },
1032                        rect.width,
1033                        viewport.width,
1034                    ),
1035                    Orientation::Vertical => (rect.y - viewport.y, rect.height, viewport.height),
1036                };
1037                if page <= 0.0 {
1038                    return None;
1039                }
1040                let alignment = match mode {
1041                    RevealMode::Child {
1042                        horizontal,
1043                        vertical,
1044                        ..
1045                    } if depth - 1 == scope => match axis {
1046                        Orientation::Horizontal => horizontal,
1047                        Orientation::Vertical => vertical,
1048                    },
1049                    _ => ScrollAlignment::Contain,
1050                };
1051                let offset = position(
1052                    ScrollLayout::new(before, scroll.max_offset),
1053                    before + start,
1054                    length,
1055                    page,
1056                    alignment,
1057                )
1058                .clamp(0.0, scroll.max_offset);
1059                if offset != before {
1060                    plan.push(ScrollPosition {
1061                        depth: depth - 1,
1062                        axis,
1063                        offset,
1064                    });
1065                    shift_rect(&mut rect, axis, reversed, offset - before);
1066                }
1067            }
1068        }
1069        if content_viewport || item.table.is_some() {
1070            rect = rect.intersect(item.scroll_viewport(Orientation::Vertical));
1071        } else if (parent.kind == "Rectangle" || xrack_runtime::is_pane(parent.kind))
1072            && parent.boolean("clip", false)
1073        {
1074            rect = crate::RoundedClip::content_box(parent, item.bounds).clip_rect(rect);
1075        } else if !item.allows_overflow() {
1076            rect = rect.intersect(item.bounds);
1077        }
1078        if rect.width <= 0.0 || rect.height <= 0.0 {
1079            return None;
1080        }
1081    }
1082    if focus {
1083        rect = layout.clip_rect(rect);
1084    }
1085    (rect.width > 0.0 && rect.height > 0.0).then_some(plan)
1086}
1087
1088fn shift_rect(rect: &mut Rect, axis: Orientation, reversed: bool, delta: f32) {
1089    let displacement = if reversed { delta } else { -delta };
1090    match axis {
1091        Orientation::Horizontal => rect.x += displacement,
1092        Orientation::Vertical => rect.y += displacement,
1093    }
1094}
1095
1096impl Interaction {
1097    pub(crate) fn reveal_focus_in_viewports(
1098        &mut self,
1099        scene: &Node,
1100        layout: &LayoutNode,
1101        path: &[usize],
1102        rect: Rect,
1103    ) -> bool {
1104        let Some(plan) = plan_focus_scroll(scene, layout, path, rect) else {
1105            return false;
1106        };
1107        self.apply_reveal_plan(layout, path, plan)
1108    }
1109
1110    fn apply_reveal_plan(
1111        &mut self,
1112        layout: &LayoutNode,
1113        path: &[usize],
1114        plan: Vec<ScrollPosition>,
1115    ) -> bool {
1116        let mut changed = false;
1117        for request in plan {
1118            let path = &path[..request.depth];
1119            if let Some(item) = layout.at_path(path) {
1120                changed |=
1121                    self.set_viewport_offset(path, item, request.axis, f64::from(request.offset));
1122            }
1123        }
1124        changed
1125    }
1126}
1127
1128fn position(
1129    scroll: ScrollLayout,
1130    top: f32,
1131    height: f32,
1132    viewport: f32,
1133    alignment: ScrollAlignment,
1134) -> f32 {
1135    match alignment {
1136        ScrollAlignment::Beginning => top,
1137        ScrollAlignment::Center => top + (height - viewport) * 0.5,
1138        ScrollAlignment::End => top + height - viewport,
1139        ScrollAlignment::Visible
1140            if top < scroll.offset + viewport && top + height > scroll.offset =>
1141        {
1142            scroll.offset
1143        }
1144        ScrollAlignment::Contain | ScrollAlignment::Visible if height > viewport => top,
1145        ScrollAlignment::Contain | ScrollAlignment::Visible => {
1146            scroll.revealing(top, height, viewport).offset
1147        }
1148    }
1149}