use std::collections::HashMap; use std::ops::Range; use crate::engine::input::{InputState, WidgetId, ZLayer}; use crate::engine::theme::YmPalette; use crate::engine::types::{css_rgba, DisplayList, Rect, Vec2}; /// Persistent vertical & horizontal scroll state with smooth clamping, /// wheel scrolling, scrollbar thumb drag, and programmatic `scroll_to` (for Search AI arrows!). #[derive(Debug, Clone)] pub struct ScrollState { pub offset: Vec2, pub target: Vec2, pub content_size: Vec2, pub viewport: Rect, dragging_v: bool, dragging_h: bool, drag_start_offset: f32, drag_start_pointer: f32, scrollbar_alpha: f32, last_scroll_time: f64, } impl Default for ScrollState { fn default() -> Self { Self::new() } } impl ScrollState { pub fn new() -> Self { Self { offset: Vec2::ZERO, target: Vec2::ZERO, content_size: Vec2::ZERO, viewport: Rect::ZERO, dragging_v: false, dragging_h: false, drag_start_offset: 0.0, drag_start_pointer: 0.0, scrollbar_alpha: 0.0, last_scroll_time: -10.0, } } #[inline] pub fn max_offset(&self) -> Vec2 { Vec2::new( (self.content_size.x - self.viewport.w).max(0.0), (self.content_size.y - self.viewport.h).max(0.0), ) } /// Smoothly scroll vertically to `y` (clamped to valid range). pub fn scroll_to_y(&mut self, y: f32) { let max_y = self.max_offset().y; self.target.y = y.clamp(0.0, max_y); } /// Smoothly scroll horizontally to `x` (clamped to valid range). /// Used by Search AI prompt carousel `<` / `>` arrows! pub fn scroll_to_x(&mut self, x: f32) { let max_x = self.max_offset().x; self.target.x = x.clamp(0.0, max_x); } /// Alias for programmatic horizontal/vertical scroll (`scroll_to`). pub fn scroll_to(&mut self, offset: Vec2) { let max = self.max_offset(); self.target = Vec2::new(offset.x.clamp(0.0, max.x), offset.y.clamp(0.0, max.y)); } /// Relative smooth horizontal scroll (e.g., `± viewport.w * 0.5` for Search AI `<` `>` arrows!). pub fn scroll_by_x(&mut self, dx: f32) { self.scroll_to_x(self.target.x + dx); } /// Relative smooth vertical scroll. pub fn scroll_by_y(&mut self, dy: f32) { self.scroll_to_y(self.target.y + dy); } /// Instant vertical jump (e.g., reset scroll to top on page navigation). pub fn jump_to_y(&mut self, y: f32) { let max_y = self.max_offset().y; let clamped = y.clamp(0.0, max_y); self.offset.y = clamped; self.target.y = clamped; } /// Instant horizontal jump. pub fn jump_to_x(&mut self, x: f32) { let max_x = self.max_offset().x; let clamped = x.clamp(0.0, max_x); self.offset.x = clamped; self.target.x = clamped; } pub fn reset(&mut self) { self.offset = Vec2::ZERO; self.target = Vec2::ZERO; } /// True when horizontal carousel can scroll backward (`<` arrow enabled). #[inline] pub fn can_scroll_left(&self) -> bool { self.target.x > 1.0 } /// True when horizontal carousel can scroll forward (`>` arrow enabled, 10px tolerance per Yandex spec). #[inline] pub fn can_scroll_right(&self) -> bool { self.content_size.x - self.target.x > self.viewport.w + 10.0 } /// Advance smooth interpolation & handle wheel input if hovered on `layer`. /// Returns `true` if animation is still in flight (caller should request repaint). pub fn update( &mut self, input: &InputState, layer: ZLayer, viewport: Rect, vertical: bool, horizontal: bool, ) -> bool { self.viewport = viewport; let mut animating = false; let hovered = input.is_hovered_in(layer, viewport, None); if hovered && (input.wheel_delta.x.abs() > 0.01 || input.wheel_delta.y.abs() > 0.01) { if vertical && input.wheel_delta.y.abs() > 0.01 && (!horizontal || !input.modifiers.shift) { self.target.y -= input.wheel_delta.y; self.last_scroll_time = input.time; } if horizontal { let dx = if input.wheel_delta.x.abs() > 0.01 { -input.wheel_delta.x } else if !vertical || input.modifiers.shift { -input.wheel_delta.y } else { 0.0 }; if dx.abs() > 0.01 { self.target.x += dx; self.last_scroll_time = input.time; } } } // Clamp targets against known content size let max = self.max_offset(); self.target.x = self.target.x.clamp(0.0, max.x); self.target.y = self.target.y.clamp(0.0, max.y); // Smooth exponential approach to target (snappy 60fps glide) let factor = 1.0 - (-18.0 * input.dt).exp(); let dx = self.target.x - self.offset.x; let dy = self.target.y - self.offset.y; if dx.abs() > 0.25 { self.offset.x += dx * factor; animating = true; } else { self.offset.x = self.target.x; } if dy.abs() > 0.25 { self.offset.y += dy * factor; animating = true; } else { self.offset.y = self.target.y; } // Clamp current offset as well in case content shrank self.offset.x = self.offset.x.clamp(0.0, max.x); self.offset.y = self.offset.y.clamp(0.0, max.y); // Fade floating scrollbar smoothly let bar_active = self.dragging_v || self.dragging_h || (input.time - self.last_scroll_time) < 1.1 || (hovered && input.pointer_pos.map_or(false, |p| p.x >= viewport.right() - 16.0)); let alpha_target = if bar_active { 1.0 } else { 0.0 }; let alpha_diff = alpha_target - self.scrollbar_alpha; if alpha_diff.abs() > 0.01 { self.scrollbar_alpha += alpha_diff * (1.0 - (-10.0 * input.dt).exp()); animating = true; } else { self.scrollbar_alpha = alpha_target; } animating } /// Update measured content height and render floating vertical scrollbar with drag support. /// Returns `true` if scrollbar is actively dragging or animating. pub fn finish_vertical( &mut self, dl: &mut DisplayList, input: &mut InputState, layer: ZLayer, pal: &YmPalette, actual_content_height: f32, show_scrollbar: bool, ) -> bool { self.content_size.y = actual_content_height.max(0.0); let max_y = self.max_offset().y; if self.target.y > max_y { self.target.y = max_y; self.offset.y = self.offset.y.min(max_y); } if max_y <= 1.0 || !show_scrollbar { self.dragging_v = false; return false; } let vp = self.viewport; let track_pad = 4.0; let track_h = (vp.h - track_pad * 2.0).max(20.0); let visible_ratio = (vp.h / self.content_size.y).clamp(0.05, 1.0); let thumb_h = (track_h * visible_ratio).clamp(36.0, track_h); let scroll_ratio = (self.offset.y / max_y).clamp(0.0, 1.0); let thumb_y = vp.y + track_pad + (track_h - thumb_h) * scroll_ratio; let bar_w = if self.dragging_v { 7.0 } else { 5.0 }; let thumb_rect = Rect::from_xywh(vp.right() - bar_w - 3.0, thumb_y, bar_w, thumb_h); let hit_rect = Rect::from_xywh(vp.right() - 14.0, thumb_y - 4.0, 14.0, thumb_h + 8.0); let hovered = input.is_hovered_in(layer, hit_rect, None); if hovered && input.left_pressed { self.dragging_v = true; self.drag_start_offset = self.offset.y; self.drag_start_pointer = input.pointer_pos.map_or(0.0, |p| p.y); self.last_scroll_time = input.time; } if self.dragging_v { if input.left_down { if let Some(p) = input.pointer_pos { let dy = p.y - self.drag_start_pointer; let travel = (track_h - thumb_h).max(1.0); let next = (self.drag_start_offset + (dy / travel) * max_y).clamp(0.0, max_y); self.offset.y = next; self.target.y = next; self.last_scroll_time = input.time; } } else { self.dragging_v = false; } } let alpha = if self.dragging_v { 0.55 } else if hovered { 0.40 } else { 0.25 * self.scrollbar_alpha }; if alpha > 0.01 { let a = (alpha * 255.0).round() as u8; let col = if pal.is_dark { css_rgba(255, 255, 255, a) } else { css_rgba(0, 0, 0, a) }; dl.push_rect(thumb_rect, bar_w * 0.5, col); } self.dragging_v } /// Update measured content width and optionally render horizontal scrollbar. pub fn finish_horizontal( &mut self, dl: &mut DisplayList, pal: &YmPalette, actual_content_width: f32, show_scrollbar: bool, ) { self.content_size.x = actual_content_width.max(0.0); let max_x = self.max_offset().x; if self.target.x > max_x { self.target.x = max_x; self.offset.x = self.offset.x.min(max_x); } if max_x <= 1.0 || !show_scrollbar || self.scrollbar_alpha <= 0.02 { return; } let vp = self.viewport; let track_pad = 4.0; let track_w = (vp.w - track_pad * 2.0).max(20.0); let visible_ratio = (vp.w / self.content_size.x).clamp(0.05, 1.0); let thumb_w = (track_w * visible_ratio).clamp(36.0, track_w); let scroll_ratio = (self.offset.x / max_x).clamp(0.0, 1.0); let thumb_x = vp.x + track_pad + (track_w - thumb_w) * scroll_ratio; let bar_h = 4.0; let thumb_rect = Rect::from_xywh(thumb_x, vp.bottom() - bar_h - 2.0, thumb_w, bar_h); let a = (0.25 * self.scrollbar_alpha * 255.0).round() as u8; let col = if pal.is_dark { css_rgba(255, 255, 255, a) } else { css_rgba(0, 0, 0, a) }; dl.push_rect(thumb_rect, bar_h * 0.5, col); } } /// Collection of `ScrollState`s indexed by `WidgetId`, owned by `UiContext`. #[derive(Default)] pub struct ScrollStore { states: HashMap, } impl ScrollStore { pub fn new() -> Self { Self { states: HashMap::with_capacity(32), } } pub fn get(&self, id: WidgetId) -> Option<&ScrollState> { self.states.get(&id) } pub fn get_or_create(&mut self, id: WidgetId) -> &mut ScrollState { self.states.entry(id).or_default() } pub fn scroll_to_x(&mut self, id: WidgetId, x: f32) { self.get_or_create(id).scroll_to_x(x); } pub fn scroll_to_y(&mut self, id: WidgetId, y: f32) { self.get_or_create(id).scroll_to_y(y); } pub fn scroll_by_x(&mut self, id: WidgetId, dx: f32) { self.get_or_create(id).scroll_by_x(dx); } pub fn jump_to_y(&mut self, id: WidgetId, y: f32) { self.get_or_create(id).jump_to_y(y); } pub fn reset(&mut self, id: WidgetId) { if let Some(s) = self.states.get_mut(&id) { s.reset(); } } } /// O(1) virtualized visible row range helper for large track lists (10,000+ liked tracks). /// - `viewport`: clipped scroll viewport rect /// - `list_top_y`: screen-space Y where row 0 starts (already shifted by `-scroll_y`!) /// - `row_height`: fixed row height (e.g. `TRACK_ROW_HEIGHT = 56.0`) /// - `total_rows`: total number of items /// - `overscan`: extra rows above/below viewport for smooth scrolling (e.g. `2`) pub fn visible_row_range( viewport: Rect, list_top_y: f32, row_height: f32, total_rows: usize, overscan: usize, ) -> Range { if total_rows == 0 || row_height <= 0.0 || viewport.is_empty() { return 0..0; } let rel_top = viewport.top() - list_top_y; let rel_bottom = viewport.bottom() - list_top_y; if rel_bottom <= 0.0 { return 0..0; } let first = if rel_top > 0.0 { (rel_top / row_height).floor() as usize } else { 0 }; let last = (rel_bottom / row_height).ceil() as usize; let start = first.saturating_sub(overscan).min(total_rows); let end = last.saturating_add(overscan).min(total_rows); start..end }