use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};
use gpui::{px, Pixels, Point, ScrollHandle};
use crate::render;
use crate::tree;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Align {
Start,
Center,
End,
Nearest,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Behavior {
Auto,
Instant,
Smooth,
}
impl Behavior {
fn smooth_for(self, id: u32) -> bool {
match self {
Behavior::Instant => false,
Behavior::Smooth => true,
Behavior::Auto => tree::read_tree(|t| {
t.node(id)
.and_then(|n| n.computed.as_ref())
.and_then(|cs| cs.extras.scroll_smooth)
})
.unwrap_or(false),
}
}
}
struct Glide {
from: Point<Pixels>,
to: Point<Pixels>,
start: Instant,
duration: Duration,
last: Point<Pixels>,
}
impl Glide {
fn new(from: Point<Pixels>, to: Point<Pixels>) -> Self {
let distance = f32::from((to.x - from.x).abs()).max(f32::from((to.y - from.y).abs()));
Glide {
from,
to,
start: Instant::now(),
duration: glide_duration(distance),
last: from,
}
}
fn at(&self, now: Instant) -> (Point<Pixels>, bool) {
let t = now.saturating_duration_since(self.start).as_secs_f32()
/ self.duration.as_secs_f32().max(f32::EPSILON);
if t >= 1.0 {
return (self.to, true);
}
let e = ease_in_out(t);
let lerp = |a: Pixels, b: Pixels| a + (b - a) * e;
(
Point {
x: lerp(self.from.x, self.to.x),
y: lerp(self.from.y, self.to.y),
},
false,
)
}
}
fn glide_duration(distance: f32) -> Duration {
Duration::from_secs_f32((distance.sqrt() * 15.0).clamp(150.0, 500.0) / 1000.0)
}
fn ease_in_out(t: f32) -> f32 {
if t < 0.5 {
4.0 * t * t * t
} else {
1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Info {
pub(crate) left: f32,
pub(crate) top: f32,
pub(crate) scroll_width: f32,
pub(crate) scroll_height: f32,
pub(crate) stale: bool,
}
thread_local! {
static PENDING: RefCell<HashSet<u32>> = RefCell::new(HashSet::new());
static AT_BUILD: RefCell<HashMap<u32, (f32, f32)>> = RefCell::new(HashMap::new());
static GLIDES: RefCell<HashMap<u32, Glide>> = RefCell::new(HashMap::new());
}
pub(crate) fn note_built(id: u32, handle: &ScrollHandle) {
let o = handle.offset();
AT_BUILD.with(|m| {
m.borrow_mut()
.insert(id, (-f32::from(o.x), -f32::from(o.y)))
});
}
pub(crate) fn unpainted_shift(id: u32) -> (f32, f32) {
if AT_BUILD.with(|m| m.borrow().is_empty()) {
return (0.0, 0.0);
}
let (dx, dy) = scrolled_since_build(id);
let (sx, sy) = crate::sticky::unpainted(id, scrolled_since_build);
(dx + sx, dy + sy)
}
fn scrolled_since_build(id: u32) -> (f32, f32) {
let (mut dx, mut dy) = (0.0f32, 0.0f32);
let mut cur = tree::read_tree(|t| t.node(id).map(|n| n.parent).unwrap_or(0));
for _ in 0..4096 {
if cur == 0 {
break;
}
if let Some(handle) = render::scroll_handle_of(cur) {
let at_build = AT_BUILD
.with(|m| m.borrow().get(&cur).copied())
.unwrap_or((0.0, 0.0));
let now = handle.offset();
dx -= (-f32::from(now.x)) - at_build.0;
dy -= (-f32::from(now.y)) - at_build.1;
}
cur = tree::read_tree(|t| t.node(cur).map(|n| n.parent).unwrap_or(0));
}
(dx, dy)
}
pub(crate) fn gc(live: &dyn Fn(u32) -> bool) {
PENDING.with(|p| p.borrow_mut().retain(|&id| live(id)));
AT_BUILD.with(|m| m.borrow_mut().retain(|&id, _| live(id)));
GLIDES.with(|g| g.borrow_mut().retain(|&id, _| live(id)));
}
pub(crate) fn info(id: u32) -> Option<Info> {
let stale = crate::dom::layout_if_stale(id);
let handle = render::scroll_handle_of(id)?;
Some(info_of(&handle, stale))
}
fn info_of(handle: &ScrollHandle, stale: bool) -> Info {
let offset = handle.offset();
let max = handle.max_offset();
let viewport = handle.bounds().size;
Info {
left: -f32::from(offset.x),
top: -f32::from(offset.y),
scroll_width: f32::from(viewport.width + max.x),
scroll_height: f32::from(viewport.height + max.y),
stale,
}
}
pub(crate) fn set(
id: u32,
left: Option<f32>,
top: Option<f32>,
behavior: Behavior,
) -> Option<Info> {
let (handle, stale) = layout_then_handle(id)?;
let smooth = behavior.smooth_for(id);
let current = smooth
.then(|| glide_target(id))
.flatten()
.unwrap_or_else(|| handle.offset());
let want = Point {
x: left.map_or(current.x, |v| px(-v)),
y: top.map_or(current.y, |v| px(-v)),
};
Some(apply(id, &handle, want, stale, smooth).0)
}
pub(crate) fn by(id: u32, dx: f32, dy: f32, behavior: Behavior) -> Option<Info> {
let (handle, stale) = layout_then_handle(id)?;
let smooth = behavior.smooth_for(id);
let current = smooth
.then(|| glide_target(id))
.flatten()
.unwrap_or_else(|| handle.offset());
let want = Point {
x: current.x - px(dx),
y: current.y - px(dy),
};
Some(apply(id, &handle, want, stale, smooth).0)
}
fn glide_target(id: u32) -> Option<Point<Pixels>> {
GLIDES.with(|g| g.borrow().get(&id).map(|glide| glide.to))
}
fn apply(
id: u32,
handle: &ScrollHandle,
want: Point<Pixels>,
stale: bool,
smooth: bool,
) -> (Info, Point<Pixels>) {
let before = handle.offset();
let max = handle.max_offset();
let clamped = Point {
x: want.x.clamp(-max.x, px(0.)),
y: want.y.clamp(-max.y, px(0.)),
};
GLIDES.with(|g| {
let mut g = g.borrow_mut();
if smooth && clamped != before {
g.insert(id, Glide::new(before, clamped));
} else {
g.remove(&id);
}
});
if !smooth && clamped != before {
handle.set_offset(clamped);
note_moved(id);
}
(info_of(handle, stale), clamped)
}
pub(crate) fn tick() -> bool {
if GLIDES.with(|g| g.borrow().is_empty()) {
return false;
}
let now = Instant::now();
let mut moved = Vec::new();
GLIDES.with(|g| {
g.borrow_mut().retain(|&id, glide| {
let Some(handle) = render::scroll_handle_of(id) else {
return false;
};
if handle.offset() != glide.last {
return false;
}
let (at, done) = glide.at(now);
let max = handle.max_offset();
let at = Point {
x: at.x.clamp(-max.x, px(0.)),
y: at.y.clamp(-max.y, px(0.)),
};
if at != glide.last {
handle.set_offset(at);
glide.last = at;
moved.push(id);
}
!done
})
});
for id in &moved {
note_moved(*id);
}
!moved.is_empty() || GLIDES.with(|g| !g.borrow().is_empty())
}
fn note_moved(id: u32) {
PENDING.with(|p| p.borrow_mut().insert(id));
tree::with_tree(|t| t.touch(id));
}
fn layout_then_handle(id: u32) -> Option<(ScrollHandle, bool)> {
let stale = crate::dom::layout_if_stale(id);
render::scroll_handle_of(id).map(|h| (h, stale))
}
pub(crate) fn into_view(
id: u32,
block: Align,
inline: Align,
behavior: Behavior,
) -> Result<bool, String> {
let stale = crate::dom::layout_if_stale(id);
let shift = unpainted_shift(id);
let Some((mut x, mut y, w, h)) =
render::bounds_of(id).map(|(x, y, w, h)| (x + shift.0, y + shift.1, w, h))
else {
return Err(format!(
"scrollIntoView(): node {id} has no rectangle — it is detached, \
`display: none`, or parked in a <KeepAlive> cache, and a browser \
would not scroll to it either"
));
};
let chain = tree::read_tree(|t| {
let mut out = Vec::new();
let mut cur = t.node(id).map(|n| n.parent).unwrap_or(0);
for _ in 0..4096 {
if cur == 0 {
break;
}
out.push(cur);
cur = t.node(cur).map(|n| n.parent).unwrap_or(0);
}
out
});
let mut scrolled = false;
for ancestor in chain {
let Some(handle) = render::scroll_handle_of(ancestor) else {
continue;
};
let viewport = handle.bounds();
if viewport.size.width <= px(0.) && viewport.size.height <= px(0.) {
continue;
}
let dx = align_delta(
inline,
x,
w,
f32::from(viewport.origin.x),
f32::from(viewport.size.width),
);
let dy = align_delta(
block,
y,
h,
f32::from(viewport.origin.y),
f32::from(viewport.size.height),
);
let before = handle.offset();
let want = Point {
x: before.x - px(dx),
y: before.y - px(dy),
};
let smooth = behavior.smooth_for(ancestor);
let (_, after) = apply(ancestor, &handle, want, stale, smooth);
x -= f32::from(before.x - after.x);
y -= f32::from(before.y - after.y);
scrolled |= before != after;
}
let _ = scrolled;
Ok(stale)
}
fn align_delta(
align: Align,
target_start: f32,
target_len: f32,
view_start: f32,
view_len: f32,
) -> f32 {
let target_end = target_start + target_len;
let view_end = view_start + view_len;
match align {
Align::Start => target_start - view_start,
Align::End => target_end - view_end,
Align::Center => (target_start + target_len / 2.0) - (view_start + view_len / 2.0),
Align::Nearest => {
if target_start >= view_start && target_end <= view_end {
0.0
} else if target_start < view_start && target_end > view_end {
0.0
} else if target_start < view_start {
target_start - view_start
} else {
target_end - view_end
}
}
}
}
pub(crate) fn dispatch_pending(window: &mut gpui::Window, cx: &mut gpui::App) -> bool {
let pending: Vec<u32> = PENDING.with(|p| p.borrow_mut().drain().collect());
if pending.is_empty() {
return false;
}
for id in pending {
let Some(handle) = render::scroll_handle_of(id) else {
continue;
};
render::report_scroll(id, &handle, window, cx);
}
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_glide_moves_one_way_and_lands_exactly() {
let from = Point {
x: px(0.),
y: px(-10.),
};
let to = Point {
x: px(0.),
y: px(-410.),
};
let glide = Glide::new(from, to);
assert_eq!(glide.at(glide.start), (from, false));
let mut last = from.y;
let steps = 20;
for step in 1..steps {
let (at, done) = glide.at(glide.start + glide.duration * step / steps);
assert!(!done && at.y < last, "step {step}: {at:?}");
last = at.y;
}
assert_eq!(glide.at(glide.start + glide.duration), (to, true));
assert!(glide_duration(10.) < glide_duration(400.));
}
#[test]
fn the_three_fixed_alignments_are_arithmetic() {
let (t0, tl, v0, vl) = (500.0, 40.0, 100.0, 200.0);
assert_eq!(align_delta(Align::Start, t0, tl, v0, vl), 400.0);
assert_eq!(align_delta(Align::End, t0, tl, v0, vl), 240.0);
assert_eq!(align_delta(Align::Center, t0, tl, v0, vl), 320.0);
}
#[test]
fn nearest_moves_only_the_edge_that_is_out() {
let (v0, vl) = (100.0, 200.0);
assert_eq!(align_delta(Align::Nearest, 150.0, 40.0, v0, vl), 0.0);
assert_eq!(align_delta(Align::Nearest, 40.0, 30.0, v0, vl), -60.0);
assert_eq!(align_delta(Align::Nearest, 400.0, 30.0, v0, vl), 130.0);
assert_eq!(align_delta(Align::Nearest, 0.0, 1000.0, v0, vl), 0.0);
}
#[test]
fn nearest_treats_a_flush_edge_as_visible() {
assert_eq!(align_delta(Align::Nearest, 100.0, 200.0, 100.0, 200.0), 0.0);
assert_eq!(align_delta(Align::Nearest, 100.0, 50.0, 100.0, 200.0), 0.0);
assert_eq!(align_delta(Align::Nearest, 250.0, 50.0, 100.0, 200.0), 0.0);
}
}