Skip to main content

glory_ui/list/
widget.rs

1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::hash::Hash;
4use std::ops::Range;
5use std::rc::Rc;
6
7use glory_core::{Cage, Vary, untracked};
8use glory_render::profile::Phase;
9use glory_render::{
10    Action, Descriptor, Event, EventKind, FocusMode, ItemPosition, Navigation, NodeId, Props, Rect,
11    Role, Semantics, TableMetadata, VirtualPart,
12};
13use glory_style::{Edges, Length, Overflow, Position, Style};
14
15use super::measure::Measurements;
16use super::navigation;
17use super::{Anchor, Cache, DEFAULT_ROW_LIMIT, Error, RowHost, ScrollSpace, check_rows};
18use crate::app::{Error as UiError, Mounted, Result, Scope, WeakScope, Widget};
19use crate::{events, view};
20
21type KeyAt<K> = Rc<dyn Fn(usize) -> K>;
22type Locate<K> = Rc<dyn Fn(&K) -> Option<usize>>;
23type RenderRow<K> = Box<dyn FnMut(Cage<usize>, K) -> Box<dyn Widget>>;
24
25fn check_table_rows(count: usize, offset: Option<&Vary<u32>>) -> Result {
26    if let Some(offset) = offset {
27        let offset = offset.try_get()?;
28        if count > (u32::MAX - offset) as usize {
29            return Err(
30                glory_render::Error::InvalidProps("virtual table coordinates exhausted").into(),
31            );
32        }
33    }
34    Ok(())
35}
36
37#[derive(Clone, Debug, PartialEq)]
38pub struct ListStats {
39    /// This commit accepted physical user scrolling or an explicit list
40    /// navigation command. Measurement, anchoring and programmatic scroll
41    /// acknowledgements alone do not set this flag.
42    pub user_moved: bool,
43    pub range: Range<usize>,
44    pub rows: usize,
45    /// Extra mounted rows outside range, currently at most one focused row.
46    pub pinned: usize,
47    pub measured: usize,
48    pub height_slots: usize,
49    pub height_capacity: usize,
50    pub logical: f64,
51    pub total: f64,
52    pub viewport: Rect,
53}
54
55/// Lazily indexed rows with fixed height or measured height estimates. Factories
56/// receive a reactive index and stable key and run once per mounted key. Only
57/// the render window and one focused key are read. The focused row may stay
58/// mounted outside that window; blur releases it. Ordinary each intentionally
59/// renders everything.
60pub struct List<K: Clone + Eq + Hash + 'static> {
61    table_offset: Option<Vary<u32>>,
62    count: Option<Vary<usize>>,
63    name: Option<Vary<String>>,
64    key: Option<KeyAt<K>>,
65    locate: Option<Locate<K>>,
66    revision: Option<Vary<u64>>,
67    render: Option<RenderRow<K>>,
68    height: f64,
69    row_height: f64,
70    adaptive: bool,
71    measure_limit: usize,
72    overscan: usize,
73    row_limit: usize,
74    limit: f64,
75    position: Option<Vary<f64>>,
76    on_scroll: Option<Box<dyn FnMut(f64)>>,
77    inspect: Option<Box<dyn FnMut(ListStats)>>,
78}
79pub fn list<K: Clone + Eq + Hash + 'static, W: Widget>(
80    count: impl Into<Vary<usize>>,
81    key: impl Fn(usize) -> K + 'static,
82    mut render: impl FnMut(Cage<usize>, K) -> W + 'static,
83) -> List<K> {
84    List {
85        table_offset: None,
86        count: Some(count.into()),
87        name: None,
88        key: Some(Rc::new(key)),
89        locate: None,
90        revision: None,
91        render: Some(Box::new(move |index, key| Box::new(render(index, key)))),
92        height: 600.0,
93        row_height: 24.0,
94        adaptive: false,
95        measure_limit: 1024,
96        overscan: 4,
97        row_limit: DEFAULT_ROW_LIMIT,
98        limit: 1_000_000.0,
99        position: None,
100        on_scroll: None,
101        inspect: None,
102    }
103}
104impl<K: Clone + Eq + Hash> List<K> {
105    /// Windowed structural rows inside an application's semantic Table. The
106    /// scroll root/surface stay generic; callers supply ColumnHeader/Cell content.
107    /// Coordinates include an explicit offset (for example one header row).
108    pub fn table_rows(mut self, offset: impl Into<Vary<u32>>) -> Self {
109        self.table_offset = Some(offset.into());
110        self
111    }
112    pub fn name(mut self, value: impl Into<Vary<String>>) -> Self {
113        self.name = Some(value.into());
114        self
115    }
116    pub fn height(mut self, value: f64) -> Self {
117        self.height = value;
118        self
119    }
120    pub fn row_height(mut self, value: f64) -> Self {
121        self.row_height = value;
122        self.adaptive = false;
123        self
124    }
125    /// Enable real row Resize measurements, using this estimate until known.
126    /// Row wrappers have automatic height and a 1px minimum. The sparse index
127    /// allocates no full-data array; unmeasured/evicted rows use the estimate.
128    pub fn measure(mut self, estimate: f64) -> Self {
129        self.row_height = estimate;
130        self.adaptive = true;
131        self
132    }
133    /// Retained height metadata, independent of UI instances. At least the live
134    /// render window is protected, even if it contains more rows than this limit.
135    pub fn measure_limit(mut self, value: usize) -> Self {
136        self.measure_limit = value;
137        self
138    }
139    /// O(1)/O(log n) stable-key lookup for anchoring across large data edits.
140    /// No source scan is supplied by the framework. Results are validated.
141    pub fn locate(mut self, locate: impl Fn(&K) -> Option<usize> + 'static) -> Self {
142        self.locate = Some(Rc::new(locate));
143        self
144    }
145    /// Explicit data edit version for sources whose key closure is not reactive.
146    /// Ordinary scrolls never relocate cached height metadata.
147    pub fn revision(mut self, value: impl Into<Vary<u64>>) -> Self {
148        self.revision = Some(value.into());
149        self
150    }
151    pub fn overscan(mut self, value: usize) -> Self {
152        self.overscan = value;
153        self
154    }
155    /// Reject an oversized render window before reading keys or mounting rows.
156    /// Includes overscan; at most one additional focused row is allowed. This
157    /// does not truncate visible data or silently change layout geometry.
158    pub fn row_limit(mut self, value: usize) -> Self {
159        self.row_limit = value;
160        self
161    }
162    pub fn scroll_limit(mut self, value: f64) -> Self {
163        self.limit = value;
164        self
165    }
166    /// Programmatic logical offset. on_scroll may echo its reported value back
167    /// into this source without issuing a new seek or cancelling navigation.
168    pub fn position(mut self, value: impl Into<Vary<f64>>) -> Self {
169        self.position = Some(value.into());
170        self
171    }
172    pub fn on_scroll(mut self, callback: impl FnMut(f64) + 'static) -> Self {
173        self.on_scroll = Some(Box::new(callback));
174        self
175    }
176    pub fn inspect(mut self, callback: impl FnMut(ListStats) + 'static) -> Self {
177        self.inspect = Some(Box::new(callback));
178        self
179    }
180}
181
182#[derive(Clone, Copy, PartialEq)]
183struct Viewport {
184    physical: f64,
185    height: f64,
186    width: f64,
187    sequence: u64,
188    ack: Option<glory_render::ScrollAck>,
189    anchor: Option<(NodeId, f64, u64)>,
190}
191#[derive(Clone, Copy)]
192struct Focused {
193    node: Option<NodeId>,
194    sequence: u64,
195}
196struct ScrollState {
197    space: ScrollSpace,
198    total: f64,
199    height: f64,
200    width: f64,
201    logical: f64,
202    native_sequence: u64,
203    desired: Option<f64>,
204    reported: Option<f64>,
205    expected: Option<ExpectedScroll>,
206    bias: f64,
207    physical: f64,
208    ack: Option<glory_render::ScrollAck>,
209    revision: Option<u64>,
210    restore_sequence: u64,
211}
212struct ExpectedScroll {
213    requested: f64,
214    projected: f64,
215}
216struct Row {
217    mounted: Mounted,
218    data: Scope,
219    index: Cage<usize>,
220    item: ItemPosition,
221}
222struct Rows<K> {
223    table_offset: Option<Vary<u32>>,
224    parent: WeakScope,
225    keys: Vec<K>,
226    start: usize,
227    count: usize,
228    render: RenderRow<K>,
229    origin: Cage<f64>,
230    height: f64,
231    adaptive: bool,
232    measurements: Rc<RefCell<Measurements<K>>>,
233    geometry: Cage<u64>,
234    measured: Cage<u64>,
235    error: Option<UiError>,
236}
237impl<K: Clone + Eq + Hash + 'static> RowHost for Rows<K> {
238    type Key = K;
239    type Row = Option<Row>;
240    fn key(&mut self, index: usize) -> K {
241        self.keys[index - self.start].clone()
242    }
243    fn mount(&mut self, index: usize, key: &K) -> Self::Row {
244        let row = (|| {
245            let data = self.parent.upgrade().ok_or(UiError::Gone)?.child()?;
246            let index = data.cage(index);
247            let origin = self.origin;
248            let height = self.height;
249            let adaptive = self.adaptive;
250            let measurements = self.measurements.clone();
251            let geometry = self.geometry;
252            let style = data
253                .bond(move || {
254                    let top = if adaptive {
255                        geometry.get();
256                        measurements
257                            .borrow()
258                            .layout
259                            .heights()
260                            .prefix(index.get())
261                            .expect("live row index")
262                    } else {
263                        index.get() as f64 * height
264                    };
265                    let mut style = Style::new()
266                        .position(Position::Absolute)
267                        .top(Length::Px(top - origin.get()))
268                        .left(Length::Px(0.0))
269                        .width(Length::Percent(100.0));
270                    if adaptive {
271                        style.min_height = Some(Length::Px(1.0));
272                    } else {
273                        style.height = Some(Length::Px(height));
274                    }
275                    style
276                })
277                .with_partial_eq();
278            let body = data.owner().enter(|| (self.render)(index, key.clone()));
279            let item = ItemPosition {
280                index: index.get_untracked(),
281                count: Some(self.count),
282            };
283            let mut wrapper = view()
284                .focus(FocusMode::Programmatic)
285                .backend_options(VirtualPart::Row)
286                .style(style)
287                .fill(body);
288            if let Some(offset) = self.table_offset.clone() {
289                wrapper = wrapper.role(Role::Row).semantics(data.bond(move || {
290                    Some(Box::new(Semantics {
291                        table: Some(TableMetadata::Row {
292                            index: offset.get() + index.get() as u32,
293                        }),
294                        ..Default::default()
295                    }))
296                }));
297            } else {
298                wrapper = wrapper.role(Role::ListItem).item(Some(item));
299            }
300            if adaptive {
301                let measurements = self.measurements.clone();
302                let measured = self.measured;
303                let key = key.clone();
304                wrapper = wrapper.on(events::resize, move |event| {
305                    if let Event::Resize { size, .. } = event
306                        && size.height.is_finite()
307                        && size.height >= 1.0
308                    {
309                        measurements.borrow_mut().queue(
310                            key.clone(),
311                            index.get_untracked(),
312                            size.height,
313                        );
314                        measured.revise(|version| {
315                            *version = version
316                                .checked_add(1)
317                                .expect("measurement revision exhausted")
318                        });
319                    }
320                });
321            }
322            let mounted = wrapper.mount(&data)?;
323            Ok(Row {
324                mounted,
325                data,
326                index,
327                item,
328            })
329        })();
330        match row {
331            Ok(row) => Some(row),
332            Err(error) => {
333                self.error.get_or_insert(error);
334                None
335            }
336        }
337    }
338    fn update(&mut self, index: usize, _: &K, row: &mut Self::Row) {
339        if let Some(row) = row {
340            if row.index.get_untracked() != index {
341                row.index.revise(|value| *value = index);
342            }
343            let item = ItemPosition {
344                index,
345                count: Some(self.count),
346            };
347            if row.item != item && self.table_offset.is_none() {
348                if let Err(error) = row.data.patch(
349                    row.mounted.roots()[0],
350                    glory_render::Patch::Item(glory_render::Change::Set(Some(item))),
351                ) {
352                    self.error.get_or_insert(error);
353                } else {
354                    row.item = item;
355                }
356            }
357        }
358    }
359    fn place(&mut self, row: &Self::Row, before: Option<&Self::Row>) {
360        if let Some(row) = row
361            && let Err(error) = row
362                .mounted
363                .place_before(before.and_then(Option::as_ref).map(|row| &row.mounted))
364        {
365            self.error.get_or_insert(error);
366        }
367    }
368    fn dispose(&mut self, row: Self::Row) {
369        drop(row);
370    }
371}
372
373impl<K: Clone + Eq + Hash + 'static> Widget for List<K> {
374    fn build(&mut self, scope: &Scope) -> Result {
375        let count = self.count.take().ok_or(UiError::Gone)?;
376        let initial = untracked(|| count.try_get())?;
377        let table_offset = self.table_offset.take();
378        check_table_rows(initial, table_offset.as_ref())?;
379        // Only accepted coordinates reach row bindings. An invalid future
380        // offset/count must not overflow a binding after structure reports it.
381        let accepted_table_offset = table_offset
382            .as_ref()
383            .map(|source| scope.cage(untracked(|| source.get())));
384        let height = self.height;
385        let row_height = self.row_height;
386        let overscan = self.overscan;
387        let row_limit = self.row_limit;
388        if row_limit == 0 {
389            return Err(UiError::List(Error::InvalidSize));
390        }
391        let desired = self.position.take();
392        let initial_position = desired
393            .as_ref()
394            .map(|value| untracked(|| value.try_get()))
395            .transpose()?
396            .unwrap_or(0.0);
397        let adaptive = self.adaptive;
398        let measurements = Rc::new(RefCell::new(
399            Measurements::new(initial, row_height, adaptive, self.measure_limit, overscan)
400                .map_err(UiError::List)?,
401        ));
402        let total = measurements.borrow().layout.heights().total();
403        check_rows(
404            measurements
405                .borrow()
406                .layout
407                .window(initial_position, height)
408                .map_err(UiError::List)?
409                .render
410                .len(),
411            row_limit,
412        )
413        .map_err(UiError::List)?;
414        let space = ScrollSpace::new(total, height, self.limit).map_err(UiError::List)?;
415        let extent = scope.cage(space.extent());
416        let origin = scope.cage(0.0);
417        let range = scope.cage(0..0);
418        let geometry = scope.cage(0_u64);
419        let measured = scope.cage(0_u64);
420        let viewport = scope.cage(Viewport {
421            physical: 0.0,
422            height,
423            width: 0.0,
424            sequence: 0,
425            ack: None,
426            anchor: None,
427        });
428        let mut descriptor = Descriptor::new(Props::View);
429        descriptor.style = Style {
430            padding: Some(Edges::all(0.0)),
431            ..Style::new()
432                .height(Length::Px(height))
433                .overflow_y(Overflow::Auto)
434                .scroll_anchor(false)
435        };
436        descriptor.role = if table_offset.is_some() {
437            None
438        } else {
439            Some(Role::List)
440        };
441        descriptor.focus = FocusMode::TabStop;
442        descriptor.options.insert(VirtualPart::Root);
443        let root = scope.create(descriptor)?;
444        if let Some(name) = self.name.take() {
445            let session = Rc::downgrade(&scope.session()?);
446            let mut previous = None;
447            scope.binding(move || {
448                if let Some(session) = session.upgrade() {
449                    let value = name.get();
450                    if previous.as_ref() != Some(&value) {
451                        match session.patch(
452                            root,
453                            glory_render::Patch::Name(glory_render::Change::Set(Some(
454                                value.clone(),
455                            ))),
456                        ) {
457                            Ok(()) => previous = Some(value),
458                            Err(error) => session.report(error),
459                        }
460                    }
461                }
462            });
463        }
464        let content = scope.child_in(root)?;
465        let mut descriptor = Descriptor::new(Props::View);
466        // Overscan or a very tall row must not enlarge the physical scroll
467        // surface. Clip does not create a second focus/scroll owner.
468        descriptor.style = Style::new()
469            .height(Length::Px(space.extent()))
470            .position(Position::Relative)
471            .overflow_x(Overflow::Clip)
472            .overflow_y(Overflow::Clip);
473        descriptor.options.insert(VirtualPart::Surface);
474        let body = content.create(descriptor)?;
475        let focus = scope.cage(Focused {
476            node: None,
477            sequence: 0,
478        });
479        let navigation = Rc::new(RefCell::new(Vec::<navigation::Request>::new()));
480        let requests = navigation.clone();
481        let navigation_revision = scope.cage(0_u64);
482        scope.on(root, events::navigate, move |event| {
483            if let Event::Navigate { from, command } = event {
484                requests
485                    .borrow_mut()
486                    .push(navigation::Request { from, command });
487                navigation_revision.revise(|revision| {
488                    *revision = revision
489                        .checked_add(1)
490                        .expect("navigation revision exhausted")
491                });
492            }
493        })?;
494        let row_parent = content.child_in(body)?;
495        let key_at = self.key.take().ok_or(UiError::Gone)?;
496        let key_count = count.clone();
497        let key = key_at.clone();
498        let data_revision = self.revision.take();
499        let key_revision = data_revision.clone();
500        let keys = scope
501            .bond(move || {
502                if let Some(revision) = &key_revision {
503                    revision.get();
504                }
505                let len = key_count.get();
506                range.with(|range| {
507                    (range.start.min(len)..range.end.min(len))
508                        .map(|index| key(index))
509                        .collect::<Vec<_>>()
510                })
511            })
512            .with_partial_eq();
513        let mut rows = Rows {
514            table_offset: accepted_table_offset.map(Into::into),
515            parent: row_parent.weak(),
516            keys: Vec::new(),
517            start: 0,
518            count: initial,
519            render: self.render.take().ok_or(UiError::Gone)?,
520            origin,
521            height: row_height,
522            adaptive,
523            measurements: measurements.clone(),
524            geometry,
525            measured,
526            error: None,
527        };
528        let mut cache: Cache<K, Option<Row>> = Cache::default();
529        let mut cache_revision = 0_u64;
530        let mut state = ScrollState {
531            space,
532            total,
533            height,
534            width: 0.0,
535            logical: 0.0,
536            native_sequence: 0,
537            desired: None,
538            reported: None,
539            expected: None,
540            bias: 0.,
541            physical: 0.,
542            ack: None,
543            revision: None,
544            restore_sequence: 0,
545        };
546        let mut navigation_target: Option<navigation::Target<K>> = None;
547        let session = Rc::downgrade(&scope.session()?);
548        let weak_scope = scope.weak();
549        let locate = self.locate.take();
550        let mut on_scroll = self.on_scroll.take();
551        let mut inspect = self.inspect.take();
552        scope.retain(row_parent)?;
553        scope.retain(content)?;
554        // One controller computes geometry/anchors before reconciling rows.
555        // Independent observers could first destroy the old positional window,
556        // losing keyed row state during prepend even though it stays visible.
557        scope.structural(move || {
558            let Some(scope) = weak_scope.upgrade() else {
559                return;
560            };
561            let Some(session) = session.upgrade() else {
562                return;
563            };
564            let profile = session.runtime.profile();
565            let _window = profile.as_ref().map(|profile| profile.span(Phase::Window));
566            let result = (|| -> Result {
567                let logical_before = state.logical;
568                let len = count.try_get()?;
569                check_table_rows(len, table_offset.as_ref())?;
570                if let (Some(source), Some(accepted)) = (&table_offset, accepted_table_offset) {
571                    let offset = source.try_get()?;
572                    if accepted.get_untracked() != offset {
573                        accepted.try_revise(|current| *current = offset)?;
574                    }
575                }
576                let input = viewport.get();
577                navigation_revision.get();
578                let requests = std::mem::take(&mut *navigation.borrow_mut());
579                if !requests.is_empty() {
580                    let capabilities = scope.capabilities()?;
581                    if !capabilities.scroll
582                        || (!capabilities.focus
583                            && requests
584                                .iter()
585                                .any(|request| request.command != Navigation::Reveal))
586                    {
587                        return Err(glory_render::Error::Unsupported(
588                            "list navigation requires focus and scroll",
589                        )
590                        .into());
591                    }
592                }
593                let focused_state = focus.get();
594                let focused = focused_state.node;
595                let focused_row = focused
596                    .map(|node| scope.child_containing(body, node))
597                    .transpose()?
598                    .flatten();
599                let mut pin = focused_row.and_then(|node| {
600                    cache.order().iter().find_map(|key| {
601                        cache
602                            .row(key)
603                            .and_then(Option::as_ref)
604                            .filter(|row| row.mounted.roots().contains(&node))
605                            .map(|row| (row.index.get_untracked(), key.clone()))
606                    })
607                });
608                // Track the one off-window source key too. A data edit can
609                // leave every visible key equal while deleting/moving focus.
610                let pin_changed = pin
611                    .as_ref()
612                    .is_some_and(|(index, key)| *index >= len || key_at(*index) != *key);
613                let had_focus = pin.is_some();
614                measured.get();
615                let revision = data_revision.as_ref().map(Vary::try_get).transpose()?;
616                let position = desired.as_ref().map(Vary::try_get).transpose()?;
617                let native_changed = state.native_sequence != input.sequence;
618                let mut user_scrolled = false;
619                let mut user_moved = false;
620                if native_changed {
621                    state.native_sequence = input.sequence;
622                    let previous_physical = state.physical;
623                    state.physical = input.physical;
624                    let mut applied = None;
625                    let mut external = false;
626                    if let Some(ack) = input.ack {
627                        if let Some(expected) = state
628                            .expected
629                            .as_ref()
630                            .filter(|e| e.requested == ack.requested.y)
631                        {
632                            state.bias = expected.projected - ack.y;
633                            applied = Some(ack.y);
634                            state.expected = None;
635                        } else if state.ack != Some(ack) {
636                            external = true;
637                            state.bias = 0.;
638                            state.expected = None;
639                        }
640                        state.ack = Some(ack);
641                    } else if let Some(expected) = state
642                        .expected
643                        .as_ref()
644                        .filter(|e| (input.physical - e.requested).abs() < 0.25)
645                    {
646                        state.bias = expected.projected - input.physical;
647                        applied = Some(input.physical);
648                        state.expected = None;
649                    }
650                    // Accepted coordinates distinguish quantization from real
651                    // movement, even when both reach the same coalesced frame.
652                    // A late/external acknowledged program scroll may cancel
653                    // navigation without being physical user input. A user
654                    // movement coalesced with an acknowledgement differs from
655                    // that acknowledgement's actual coordinate.
656                    user_moved = input.physical
657                        != input
658                            .ack
659                            .map_or(applied.unwrap_or(previous_physical), |ack| ack.y);
660                    if external || input.physical != applied.unwrap_or(previous_physical) {
661                        user_scrolled = true;
662                        state.expected = None;
663                        state.logical = state
664                            .space
665                            .scrolled(input.physical + state.bias)
666                            .map_err(UiError::List)?
667                            .logical;
668                    }
669                }
670                let previous_range = range.get_untracked();
671                let keyed_change = pin_changed
672                    || if adaptive || locate.is_some() {
673                        keys.with(|snapshot| *snapshot != rows.keys)
674                    } else {
675                        false
676                    };
677                let mut metrics = measurements.borrow_mut();
678                let data_changed = len != metrics.layout.heights().len()
679                    || revision != state.revision
680                    || keyed_change;
681                let width_changed = adaptive && state.width > 0.0 && state.width != input.width;
682                let mut anchor = metrics
683                    .layout
684                    .anchor(state.logical)
685                    .map_err(UiError::List)?;
686                let restored = input
687                    .anchor
688                    .filter(|(_, _, sequence)| *sequence != state.restore_sequence);
689                if let Some((row, within, sequence)) = restored {
690                    let index = rows
691                        .keys
692                        .iter()
693                        .enumerate()
694                        .find_map(|(index, key)| {
695                            cache
696                                .row(key)
697                                .and_then(Option::as_ref)
698                                .filter(|row_state| row_state.mounted.roots().contains(&row))
699                                .map(|_| rows.start + index)
700                        })
701                        .ok_or(UiError::List(Error::InvalidAnchor))?;
702                    anchor = Some(Anchor { index, within });
703                    state.restore_sequence = sequence;
704                }
705                let old_key = anchor
706                    .and_then(|anchor| anchor.index.checked_sub(rows.start))
707                    .and_then(|index| rows.keys.get(index))
708                    .cloned();
709                if data_changed || width_changed {
710                    let positions = if data_changed && locate.is_none() {
711                        keys.with(|snapshot| {
712                            snapshot
713                                .iter()
714                                .cloned()
715                                .enumerate()
716                                .map(|(index, key)| (key, previous_range.start + index))
717                                .collect::<HashMap<_, _>>()
718                        })
719                    } else {
720                        HashMap::new()
721                    };
722                    let resolve = |key: &K| -> std::result::Result<Option<usize>, Error> {
723                        let index = if let Some(locate) = &locate {
724                            untracked(|| locate(key))
725                        } else {
726                            positions.get(key).copied()
727                        };
728                        if let Some(index) = index
729                            && (index >= len || untracked(|| key_at(index)) != *key)
730                        {
731                            return Err(Error::InvalidLookup);
732                        }
733                        Ok(index)
734                    };
735                    if data_changed && let Some(old) = anchor {
736                        let located = old_key
737                            .as_ref()
738                            .map(resolve)
739                            .transpose()
740                            .map_err(UiError::List)?
741                            .flatten();
742                        let next = if located.is_some() {
743                            located
744                        } else {
745                            let mut survivor = None;
746                            for key in rows
747                                .keys
748                                .iter()
749                                .skip(old.index.saturating_sub(rows.start).saturating_add(1))
750                            {
751                                if let Some(index) = resolve(key).map_err(UiError::List)? {
752                                    survivor = Some(index);
753                                    break;
754                                }
755                            }
756                            survivor
757                        };
758                        anchor = (len > 0).then_some(Anchor {
759                            index: next.unwrap_or(old.index.min(len.saturating_sub(1))),
760                            within: if located.is_some() { old.within } else { 0.0 },
761                        });
762                    }
763                    metrics
764                        .rebuild(len, overscan, |key| {
765                            if width_changed {
766                                Ok(None)
767                            } else {
768                                resolve(key)
769                            }
770                        })
771                        .map_err(UiError::List)?;
772                }
773                state.revision = revision;
774                state.width = input.width;
775                let mut changed = data_changed || width_changed;
776                if adaptive {
777                    changed |= metrics
778                        .apply(|index, key| untracked(|| key_at(index)) == *key)
779                        .map_err(UiError::List)?;
780                }
781                if (changed || restored.is_some())
782                    && let Some(anchor) = anchor
783                {
784                    state.logical = metrics.layout.restore(anchor).map_err(UiError::List)?;
785                }
786                // Eviction restores estimates outside the live window. Correct
787                // its prefix delta around the same anchor, never scale wheel motion.
788                loop {
789                    let next = metrics
790                        .layout
791                        .window(state.logical, input.height)
792                        .map_err(UiError::List)?;
793                    check_rows(next.render.len(), row_limit).map_err(UiError::List)?;
794                    if !adaptive || !metrics.prune(&next.render).map_err(UiError::List)? {
795                        break;
796                    }
797                    changed = true;
798                    if let Some(anchor) = anchor {
799                        state.logical = metrics.layout.restore(anchor).map_err(UiError::List)?;
800                    }
801                }
802                let total = metrics.layout.heights().total();
803                if changed
804                    || restored.is_some()
805                    || total != state.total
806                    || input.height != state.height
807                {
808                    state.logical = state
809                        .space
810                        .resize(total, input.height, state.logical)
811                        .map_err(UiError::List)?
812                        .logical;
813                    state.total = total;
814                    state.height = input.height;
815                }
816                if position != state.desired {
817                    state.desired = position;
818                    // Controlled on_scroll echoes acknowledge the reported
819                    // value. Re-seeking would undo a measurement correction or
820                    // retire the still-focused navigation intent.
821                    if position != state.reported {
822                        navigation_target = None;
823                        state.bias = 0.;
824                        state.expected = None;
825                    }
826                    if let Some(position) = position.filter(|value| Some(*value) != state.reported)
827                    {
828                        state.logical = state.space.seek(position).map_err(UiError::List)?.logical;
829                    }
830                }
831                if user_scrolled || data_changed {
832                    navigation_target = None;
833                }
834                if let Some(target) = &mut navigation_target
835                    && target.focus_sequence != focused_state.sequence
836                {
837                    if pin.as_ref().is_some_and(|(_, key)| *key == target.key) {
838                        target.focus_sequence = focused_state.sequence;
839                    } else {
840                        // A late row measurement must not scroll for an old
841                        // navigation request after the user moves focus away.
842                        navigation_target = None;
843                    }
844                }
845                if !requests.is_empty() {
846                    // A new logical destination establishes a fresh alignment;
847                    // carrying a previous segment's quantization bias would
848                    // accumulate error across repeated Home/End commands.
849                    let mut cursor = None;
850                    for request in requests {
851                        let current = if let Some((_, index)) = cursor.filter(|(from, _)| {
852                            *from == request.from && request.command != Navigation::Reveal
853                        }) {
854                            Some(index)
855                        } else if let Some(wrapper) = scope.child_containing(body, request.from)? {
856                            let entry = cache.order().iter().find_map(|key| {
857                                cache
858                                    .row(key)
859                                    .and_then(Option::as_ref)
860                                    .filter(|row| row.mounted.roots().contains(&wrapper))
861                                    .map(|row| (key, row.index.get_untracked()))
862                            });
863                            if let Some((key, index)) = entry {
864                                let index = if data_changed {
865                                    if let Some(locate) = &locate {
866                                        untracked(|| locate(key))
867                                    } else if index < len && untracked(|| key_at(index)) == *key {
868                                        Some(index)
869                                    } else {
870                                        None
871                                    }
872                                } else {
873                                    Some(index)
874                                };
875                                if let Some(index) = index
876                                    && (index >= len || untracked(|| key_at(index)) != *key)
877                                {
878                                    return Err(UiError::List(Error::InvalidLookup));
879                                }
880                                index
881                            } else {
882                                None
883                            }
884                        } else {
885                            None
886                        };
887                        if let Some(index) = navigation::target(
888                            &metrics.layout,
889                            current,
890                            state.logical,
891                            input.height,
892                            request.command,
893                        )
894                        .map_err(UiError::List)?
895                        {
896                            state.bias = 0.;
897                            state.expected = None;
898                            cursor = Some((request.from, index));
899                            navigation_target = Some(navigation::Target {
900                                index,
901                                key: untracked(|| key_at(index)),
902                                focus: request.command != Navigation::Reveal,
903                                focus_sequence: focused_state.sequence,
904                            });
905                        }
906                    }
907                }
908                let mut focus_target = None;
909                let navigating = navigation_target
910                    .as_ref()
911                    .is_some_and(|target| target.focus);
912                if let Some(target) = &mut navigation_target {
913                    state.logical = state
914                        .space
915                        .seek(
916                            navigation::reveal(
917                                &metrics.layout,
918                                target.index,
919                                state.logical,
920                                input.height,
921                            )
922                            .map_err(UiError::List)?,
923                        )
924                        .map_err(UiError::List)?
925                        .logical;
926                    if target.focus {
927                        focus_target = Some(target.index);
928                        target.focus = false;
929                    }
930                    // A measured placeholder is not a final size: images,
931                    // fonts and wrapping can resize the same focused row later.
932                    // Keep one adaptive reveal intent until user movement,
933                    // external position/data changes or focus elsewhere.
934                    if !adaptive {
935                        navigation_target = None;
936                    }
937                }
938                let next = metrics
939                    .layout
940                    .window(state.logical, input.height)
941                    .map_err(UiError::List)?;
942                check_rows(next.render.len(), row_limit).map_err(UiError::List)?;
943                let measured_count = metrics.measured();
944                let height_slots = metrics.layout.heights().storage_len();
945                let height_capacity = metrics.layout.heights().storage_capacity();
946                drop(metrics);
947                if changed {
948                    geometry.revise(|version| {
949                        *version = version.checked_add(1).expect("geometry revision exhausted")
950                    });
951                }
952                if previous_range != next.render {
953                    range.revise(|range| *range = next.render.clone());
954                }
955                if extent.get_untracked() != state.space.extent() {
956                    extent.revise(|extent| *extent = state.space.extent());
957                }
958                let projected = state.space.project(state.logical);
959                let physical = (projected - state.bias)
960                    .clamp(0., (state.space.extent() - input.height).max(0.));
961                if physical != projected - state.bias {
962                    state.bias = projected - physical;
963                }
964                // Ignore only arithmetic roundoff from logical/segment
965                // coordinate conversion, never a subpixel height change.
966                let roundoff =
967                    4.0 * f64::EPSILON * projected.abs().max(input.physical.abs()).max(1.0);
968                if scope.capabilities()?.scroll
969                    && scope.is_active(root)?
970                    && ((input.physical - physical).abs() > roundoff
971                        || state
972                            .expected
973                            .as_ref()
974                            .is_some_and(|expected| expected.projected != projected))
975                    && !state
976                        .expected
977                        .as_ref()
978                        .is_some_and(|expected| expected.projected == projected)
979                {
980                    scope.action(Action::ScrollTo {
981                        node: root,
982                        x: 0.0,
983                        // Request the new projection itself. Subtracting the
984                        // previous quantization error would accumulate bias
985                        // across successive fractional measurements.
986                        y: projected,
987                    })?;
988                    state.expected = Some(ExpectedScroll {
989                        requested: projected,
990                        projected,
991                    });
992                }
993                // The same mapping must drive logical scrolling AND painting:
994                // row_top = prefix - segment_origin - bias - host_scroll.
995                // Host readback can differ from the requested projection while
996                // the logical anchor and its exact within-row offset survive.
997                let display_origin = state.space.origin() + state.bias;
998                if origin.get_untracked() != display_origin {
999                    origin.revise(|origin| *origin = display_origin);
1000                }
1001                let keys_changed = keys.with(|snapshot| {
1002                    if rows.start == next.render.start && rows.keys == *snapshot {
1003                        false
1004                    } else {
1005                        rows.start = next.render.start;
1006                        rows.keys.clone_from(snapshot);
1007                        true
1008                    }
1009                });
1010                rows.count = len;
1011                if keys_changed || data_changed {
1012                    cache_revision = cache_revision
1013                        .checked_add(1)
1014                        .expect("list revision exhausted");
1015                }
1016                if data_changed && let Some((index, key)) = &pin {
1017                    let located = if let Some(locate) = &locate {
1018                        untracked(|| locate(key))
1019                    } else if *index < len && untracked(|| key_at(*index)) == *key {
1020                        Some(*index)
1021                    } else {
1022                        // Without an index lookup only this bounded window is
1023                        // searchable. Never scan a large source for old focus.
1024                        rows.keys
1025                            .iter()
1026                            .position(|candidate| candidate == key)
1027                            .map(|at| rows.start + at)
1028                    };
1029                    if let Some(index) = located
1030                        && (index >= len || key_at(index) != *key)
1031                    {
1032                        cache.clear(&mut rows);
1033                        return Err(UiError::List(Error::InvalidLookup));
1034                    }
1035                    pin = located.map(|index| (index, key.clone()));
1036                }
1037                let restore_focus = had_focus && pin.is_none();
1038                let pinned = usize::from(
1039                    pin.as_ref()
1040                        .is_some_and(|(index, _)| !next.render.contains(index)),
1041                );
1042                let reconciled = {
1043                    let mut span = profile
1044                        .as_ref()
1045                        .map(|profile| profile.span(Phase::Reconcile).work(0));
1046                    let result =
1047                        cache.reconcile_pinned(next.render.clone(), cache_revision, pin, &mut rows);
1048                    if let (Some(span), Ok(stats)) = (&mut span, &result) {
1049                        span.set_work(stats.keys_read as u64);
1050                    }
1051                    result
1052                };
1053                if let Err(error) = reconciled {
1054                    // Geometry may already have changed. Do not leave old rows
1055                    // with now-out-of-range indices for the following prop phase.
1056                    cache.clear(&mut rows);
1057                    return Err(UiError::List(error));
1058                }
1059                if let Some(error) = rows.error.take() {
1060                    cache.clear(&mut rows);
1061                    return Err(error);
1062                }
1063                if let Some(index) = focus_target {
1064                    let key = rows
1065                        .keys
1066                        .get(
1067                            index
1068                                .checked_sub(rows.start)
1069                                .ok_or(UiError::List(Error::InvalidAnchor))?,
1070                        )
1071                        .ok_or(UiError::List(Error::InvalidAnchor))?;
1072                    let row = cache
1073                        .row(key)
1074                        .and_then(Option::as_ref)
1075                        .ok_or(UiError::List(Error::InvalidAnchor))?;
1076                    scope.action(Action::Focus(row.mounted.roots()[0]))?;
1077                } else if restore_focus && scope.capabilities()?.focus && scope.is_active(root)? {
1078                    scope.action(Action::Focus(root))?;
1079                }
1080                if (native_changed
1081                    || changed
1082                    || restored.is_some()
1083                    || navigating
1084                    || state.logical != logical_before)
1085                    && state.reported != Some(state.logical)
1086                    && let Some(callback) = &mut on_scroll
1087                {
1088                    state.reported = Some(state.logical);
1089                    untracked(|| callback(state.logical));
1090                }
1091                if let Some(inspect) = &mut inspect {
1092                    untracked(|| {
1093                        inspect(ListStats {
1094                            user_moved: user_moved || navigating,
1095                            range: next.render,
1096                            rows: cache.len(),
1097                            pinned,
1098                            measured: measured_count,
1099                            height_slots,
1100                            height_capacity,
1101                            logical: state.logical,
1102                            total,
1103                            viewport: Rect {
1104                                width: input.width,
1105                                height: input.height,
1106                                ..Rect::default()
1107                            },
1108                        })
1109                    });
1110                }
1111                Ok(())
1112            })();
1113            if let Err(error) = result {
1114                if matches!(
1115                    error,
1116                    UiError::List(Error::RowLimit { .. } | Error::Allocation)
1117                ) {
1118                    // A failed geometry/data edit may invalidate old row
1119                    // indices. Release them after the measurements borrow ends,
1120                    // without ever publishing the oversized source range.
1121                    let focused = focus.get_untracked().node;
1122                    let restore = focused.is_some_and(|node| {
1123                        scope.child_containing(body, node).ok().flatten().is_some()
1124                    });
1125                    cache.clear(&mut rows);
1126                    rows.keys.clear();
1127                    rows.start = 0;
1128                    navigation_target = None;
1129                    if !range.get_untracked().is_empty() {
1130                        range.revise(|range| *range = 0..0);
1131                    }
1132                    if restore
1133                        && scope.capabilities().is_ok_and(|caps| caps.focus)
1134                        && scope.is_active(root).unwrap_or(false)
1135                        && let Err(focus_error) = scope.action(Action::Focus(root))
1136                    {
1137                        session.report(focus_error);
1138                    }
1139                }
1140                session.report(error);
1141            }
1142        });
1143        let session = Rc::downgrade(&scope.session()?);
1144        scope.binding(move || {
1145            if let Some(session) = session.upgrade() {
1146                let style = Style::new()
1147                    .height(Length::Px(extent.get()))
1148                    .position(Position::Relative)
1149                    .overflow_x(Overflow::Clip)
1150                    .overflow_y(Overflow::Clip);
1151                if let Err(error) = session.patch(
1152                    body,
1153                    glory_render::Patch::Style(glory_render::Change::Set(Box::new(style))),
1154                ) {
1155                    session.report(error);
1156                }
1157            }
1158        });
1159        scope.on(root, events::focus_within, move |event| {
1160            if let Event::FocusWithin { node, focused } = event {
1161                let previous = focus.get_untracked();
1162                if focused && previous.node != Some(node) {
1163                    focus.revise(|focus| {
1164                        focus.node = Some(node);
1165                        focus.sequence = focus
1166                            .sequence
1167                            .checked_add(1)
1168                            .expect("focus sequence exhausted");
1169                    });
1170                } else if !focused && previous.node == Some(node) {
1171                    focus.revise(|focus| {
1172                        focus.node = None;
1173                        focus.sequence = focus
1174                            .sequence
1175                            .checked_add(1)
1176                            .expect("focus sequence exhausted");
1177                    });
1178                }
1179            }
1180        })?;
1181        scope.on(root, events::scroll, move |event| {
1182            if let Event::Scroll {
1183                y,
1184                viewport: bounds,
1185                ack,
1186                ..
1187            } = event
1188                && y.is_finite()
1189                && bounds.height.is_finite()
1190                && bounds.height >= 0.0
1191                && bounds.width.is_finite()
1192                && bounds.width >= 0.0
1193            {
1194                let previous = viewport.get_untracked();
1195                let ack = ack.filter(|ack| {
1196                    ack.y.is_finite()
1197                        && ack.y >= 0.
1198                        && ack.requested.y.is_finite()
1199                        && ack.requested.y >= 0.
1200                });
1201                if previous.physical != y
1202                    || previous.height != bounds.height
1203                    || previous.width != bounds.width
1204                    || previous.ack != ack
1205                    || ack.is_some()
1206                {
1207                    viewport.revise(|value| {
1208                        value.physical = y.max(0.0);
1209                        value.height = bounds.height;
1210                        value.width = bounds.width;
1211                        value.ack = ack;
1212                        value.sequence = value
1213                            .sequence
1214                            .checked_add(1)
1215                            .expect("scroll sequence exhausted");
1216                    });
1217                }
1218            }
1219        })?;
1220        scope.on(root, EventKind::Anchor, move |event| {
1221            if let Event::Anchor {
1222                row,
1223                within,
1224                viewport: bounds,
1225            } = event
1226                && within.is_finite()
1227                && within >= 0.0
1228                && bounds.height.is_finite()
1229                && bounds.height >= 0.0
1230                && bounds.width.is_finite()
1231                && bounds.width >= 0.0
1232            {
1233                viewport.revise(|value| {
1234                    let sequence = value
1235                        .anchor
1236                        .map_or(0, |(_, _, sequence)| sequence)
1237                        .checked_add(1)
1238                        .expect("anchor sequence exhausted");
1239                    value.anchor = Some((row, within, sequence));
1240                    value.height = bounds.height;
1241                    value.width = bounds.width;
1242                });
1243            }
1244        })?;
1245        scope.on(root, EventKind::Resize, move |event| {
1246            if let Event::Resize {
1247                viewport: bounds, ..
1248            } = event
1249                && bounds.height.is_finite()
1250                && bounds.height >= 0.0
1251                && bounds.width.is_finite()
1252                && bounds.width >= 0.0
1253            {
1254                let previous = viewport.get_untracked();
1255                if previous.height != bounds.height || previous.width != bounds.width {
1256                    viewport.revise(|value| {
1257                        value.height = bounds.height;
1258                        value.width = bounds.width;
1259                    });
1260                }
1261            }
1262        })?;
1263        Ok(())
1264    }
1265}