use std::{cell::RefCell, rc::Rc};
use arc_motion::{arc_spring_with_options, is_reduced_motion, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography};
use gpui_kit::{
AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, RenderOnce,
Role, SharedString, Styled, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ImageCompareOrientation {
#[default]
Horizontal,
Vertical,
}
pub fn image_compare_rubber(distance: f32, limit: f32) -> f32 {
if distance == 0.0 || limit <= 0.0 {
return 0.0;
}
distance.signum() * (1.0 - 1.0 / (distance.abs() * 0.55 / limit + 1.0)) * limit
}
pub fn clamp_compare_position(pos: f32) -> f32 {
pos.clamp(0.0, 100.0)
}
fn paint_split_chevrons(cx: f32, cy: f32, vertical: bool, color: Hsla, window: &mut Window) {
let mut paint_pair = |dx1: f32, dy1: f32, dx2: f32, dy2: f32, dx3: f32, dy3: f32| {
let mut pb = PathBuilder::stroke(px(1.7));
pb.move_to(point(px(cx + dx1), px(cy + dy1)));
pb.line_to(point(px(cx + dx2), px(cy + dy2)));
pb.line_to(point(px(cx + dx3), px(cy + dy3)));
if let Ok(p) = pb.build() {
window.paint_path(p, color);
}
};
if vertical {
paint_pair(-3.5, -3.5, 0.0, -7.0, 3.5, -3.5);
paint_pair(-3.5, 3.5, 0.0, 7.0, 3.5, 3.5);
} else {
paint_pair(-3.5, -3.5, -7.0, 0.0, -3.5, 3.5);
paint_pair(3.5, -3.5, 7.0, 0.0, 3.5, 3.5);
}
}
type LayerBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
type PositionCallback = Rc<dyn Fn(f32, &mut Window, &mut App)>;
#[derive(Clone)]
struct ImageCompareInternal {
position: f32,
dragging: bool,
rubber_pct: f32,
frame_bounds: Option<Bounds<Pixels>>,
focus_handle: FocusHandle,
}
#[derive(IntoElement)]
pub struct ImageCompare {
id: ElementId,
before: LayerBuilder,
after: LayerBuilder,
position_override: Option<f32>,
default_position: f32,
orientation: ImageCompareOrientation,
labels: Option<(SharedString, SharedString)>,
height_px: f32,
on_position_change: Option<PositionCallback>,
}
impl ImageCompare {
pub fn new(
id: impl Into<ElementId>,
before: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
after: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
) -> Self {
Self {
id: id.into(),
before: Rc::new(before),
after: Rc::new(after),
position_override: None,
default_position: 50.0,
orientation: ImageCompareOrientation::Horizontal,
labels: Some((SharedString::from("Before"), SharedString::from("After"))),
height_px: 300.0,
on_position_change: None,
}
}
pub fn position(mut self, position: f32) -> Self {
self.position_override = Some(clamp_compare_position(position));
self
}
pub fn default_position(mut self, position: f32) -> Self {
self.default_position = clamp_compare_position(position);
self
}
pub fn orientation(mut self, orientation: ImageCompareOrientation) -> Self {
self.orientation = orientation;
self
}
pub fn labels(
mut self,
before: impl Into<SharedString>,
after: impl Into<SharedString>,
) -> Self {
self.labels = Some((before.into(), after.into()));
self
}
pub fn hide_labels(mut self) -> Self {
self.labels = None;
self
}
pub fn height(mut self, height_px: f32) -> Self {
self.height_px = height_px.max(120.0);
self
}
pub fn on_position_change(mut self, cb: impl Fn(f32, &mut Window, &mut App) + 'static) -> Self {
self.on_position_change = Some(Rc::new(cb));
self
}
}
impl RenderOnce for ImageCompare {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let reduced = is_reduced_motion(cx);
let vertical = matches!(self.orientation, ImageCompareOrientation::Vertical);
let controlled = self.position_override.is_some();
let state_cell = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), SharedString::from("ic-state")),
cx,
|_, cx| {
Rc::new(RefCell::new(ImageCompareInternal {
position: self.default_position,
dragging: false,
rubber_pct: 0.0,
frame_bounds: None,
focus_handle: cx.focus_handle(),
}))
},
)
.read(cx)
.clone();
let (target_pos, dragging, rubber_pct, bounds_opt, focus_handle) = {
let mut st = state_cell.borrow_mut();
if let Some(ov) = self.position_override {
st.position = ov;
}
(
st.position,
st.dragging,
st.rubber_pct,
st.frame_bounds,
st.focus_handle.clone(),
)
};
let animated_pos = if dragging || reduced {
(target_pos + rubber_pct).clamp(-4.0, 104.0)
} else {
arc_spring_with_options(
(self.id.clone(), "ic-pos"),
target_pos,
SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
window,
cx,
)
.value
.clamp(0.0, 100.0)
};
let frame_w = bounds_opt
.map(|b| f32::from(b.size.width))
.unwrap_or(560.0)
.max(1.0);
let frame_h = bounds_opt
.map(|b| f32::from(b.size.height))
.unwrap_or(self.height_px)
.max(1.0);
let split_px = if vertical {
(animated_pos / 100.0) * frame_h
} else {
(animated_pos / 100.0) * frame_w
};
let clamped_split = split_px.clamp(0.0, if vertical { frame_h } else { frame_w });
let (handle_w, handle_h) = if dragging {
if vertical { (36.0, 52.0) } else { (52.0, 36.0) }
} else {
(40.0, 40.0)
};
let handle_x = if vertical {
frame_w * 0.5 - handle_w * 0.5
} else {
clamped_split.clamp(24.0, (frame_w - 24.0).max(24.0)) - handle_w * 0.5
};
let handle_y = if vertical {
clamped_split.clamp(24.0, (frame_h - 24.0).max(24.0)) - handle_h * 0.5
} else {
frame_h * 0.5 - handle_h * 0.5
};
let before_label_opacity = ((clamped_split - 76.0) / 36.0).clamp(0.0, 1.0);
let after_room = if vertical {
frame_h - clamped_split - 76.0
} else {
frame_w - clamped_split - 76.0
};
let after_label_opacity = (after_room / 36.0).clamp(0.0, 1.0);
let st_down = state_cell.clone();
let cb_down = self.on_position_change.clone();
let fh_down = focus_handle.clone();
let st_key = state_cell.clone();
let cb_key = self.on_position_change.clone();
let st_canvas = state_cell.clone();
let cb_move = self.on_position_change.clone();
let st_move = state_cell.clone();
let st_up = state_cell.clone();
let before_el = (self.before)(window, cx);
let after_el = (self.after)(window, cx);
let before_layer = if vertical {
div()
.absolute()
.left(px(0.0))
.top(px(0.0))
.w(px(frame_w))
.h(px(clamped_split))
.overflow_hidden()
.child(div().w(px(frame_w)).h(px(frame_h)).child(before_el))
} else {
div()
.absolute()
.left(px(0.0))
.top(px(0.0))
.w(px(clamped_split))
.h(px(frame_h))
.overflow_hidden()
.child(div().w(px(frame_w)).h(px(frame_h)).child(before_el))
};
let divider_line = if vertical {
div()
.absolute()
.left(px(0.0))
.top(px(clamped_split - 1.0))
.w_full()
.h(px(2.0))
.bg(colors.surface_raised)
} else {
div()
.absolute()
.left(px(clamped_split - 1.0))
.top(px(0.0))
.w(px(2.0))
.h_full()
.bg(colors.surface_raised)
};
let chevron_col = colors.foreground;
let handle_knob = div()
.absolute()
.left(px(handle_x))
.top(px(handle_y))
.w(px(handle_w))
.h(px(handle_h))
.rounded(Radii::PILL)
.bg(colors.surface_raised)
.border_1()
.border_color(colors.border)
.shadow(Shadows::raised(theme.mode))
.child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let cx_p = f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
let cy_p = f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
paint_split_chevrons(cx_p, cy_p, vertical, chevron_col, window);
},
)
.w_full()
.h_full(),
);
let mut frame = div()
.id(self.id.clone())
.relative()
.w_full()
.h(px(self.height_px))
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.overflow_hidden()
.cursor(if vertical {
gpui_kit::CursorStyle::ResizeUpDown
} else {
gpui_kit::CursorStyle::ResizeLeftRight
})
.track_focus(&focus_handle)
.role(Role::Slider)
.on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
window.focus(&fh_down, cx);
let mut st = st_down.borrow_mut();
if ev.click_count >= 2 {
if !controlled {
st.position = 50.0;
}
st.dragging = false;
st.rubber_pct = 0.0;
if let Some(cb) = &cb_down {
cb(50.0, window, cx);
}
window.refresh();
return;
}
st.dragging = true;
if let Some(b) = st.frame_bounds {
let raw = if vertical {
(f32::from(ev.position.y - b.origin.y) / f32::from(b.size.height).max(1.0))
* 100.0
} else {
(f32::from(ev.position.x - b.origin.x) / f32::from(b.size.width).max(1.0))
* 100.0
};
let clamped = clamp_compare_position(raw);
if !controlled {
st.position = clamped;
}
st.rubber_pct = 0.0;
if let Some(cb) = &cb_down {
cb(clamped, window, cx);
}
}
window.refresh();
})
.on_key_down(move |ev: &KeyDownEvent, window, cx| {
let step = if ev.keystroke.modifiers.shift {
10.0
} else {
1.0
};
let key = ev.keystroke.key.as_str();
let mut st = st_key.borrow_mut();
let cur = st.position;
let next = match key {
"left" | "up" => clamp_compare_position(cur - step),
"right" | "down" => clamp_compare_position(cur + step),
"pageup" => clamp_compare_position(cur - 10.0),
"pagedown" => clamp_compare_position(cur + 10.0),
"home" => 0.0,
"end" => 100.0,
_ => return,
};
if (next - cur).abs() > 1e-4 {
if !controlled {
st.position = next;
}
if let Some(cb) = &cb_key {
cb(next, window, cx);
}
window.refresh();
}
})
.child(div().w_full().h_full().child(after_el))
.child(before_layer)
.child(
canvas(
move |bounds, _, _| {
st_canvas.borrow_mut().frame_bounds = Some(bounds);
},
move |_, _, window, _| {
let st_m = st_move.clone();
let cb_m = cb_move.clone();
window.on_mouse_event(move |ev: &MouseMoveEvent, _, window, cx| {
let mut st = st_m.borrow_mut();
if !st.dragging {
return;
}
let Some(b) = st.frame_bounds else {
return;
};
let axis_px = if vertical {
f32::from(b.size.height).max(1.0)
} else {
f32::from(b.size.width).max(1.0)
};
let raw_pct = if vertical {
(f32::from(ev.position.y - b.origin.y) / axis_px) * 100.0
} else {
(f32::from(ev.position.x - b.origin.x) / axis_px) * 100.0
};
let clamped = clamp_compare_position(raw_pct);
let over_px = ((raw_pct - clamped) / 100.0) * axis_px;
st.rubber_pct = if reduced {
0.0
} else {
(image_compare_rubber(over_px, 9.0) / axis_px) * 100.0
};
if !controlled {
st.position = clamped;
}
if let Some(cb) = &cb_m {
cb(clamped, window, cx);
}
window.refresh();
});
let st_u = st_up.clone();
window.on_mouse_event(move |_: &MouseUpEvent, _, window, _| {
let mut st = st_u.borrow_mut();
if st.dragging {
st.dragging = false;
st.rubber_pct = 0.0;
window.refresh();
}
});
},
)
.absolute()
.inset_0(),
)
.child(divider_line)
.child(handle_knob);
if let Some((before_lbl, after_lbl)) = self.labels {
let chip_bg = colors.surface_raised.opacity(0.88);
frame = frame
.child(
div()
.absolute()
.left(Spacing::S3)
.top(Spacing::S3)
.px(Spacing::S2)
.py(px(3.0))
.rounded(Radii::PILL)
.bg(chip_bg)
.border_1()
.border_color(colors.border)
.opacity(before_label_opacity)
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.foreground)
.child(before_lbl),
)
.child(
div()
.absolute()
.right(Spacing::S3)
.when(vertical, |this| this.bottom(Spacing::S3))
.when(!vertical, |this| this.top(Spacing::S3))
.px(Spacing::S2)
.py(px(3.0))
.rounded(Radii::PILL)
.bg(chip_bg)
.border_1()
.border_color(colors.border)
.opacity(after_label_opacity)
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.foreground)
.child(after_lbl),
);
}
frame
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rubber_band_is_monotonic_and_bounded_by_limit() {
let a = image_compare_rubber(10.0, 9.0);
let b = image_compare_rubber(200.0, 9.0);
assert!(a > 0.0 && a < b && b < 9.0);
assert!((image_compare_rubber(-50.0, 9.0) + image_compare_rubber(50.0, 9.0)).abs() < 1e-5);
assert_eq!(clamp_compare_position(-12.0), 0.0);
assert_eq!(clamp_compare_position(140.0), 100.0);
}
}