Skip to main content

arc_ui/data/
image_compare.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/image-compare/image-compare.tsx` & `.module.css`
3//!
4//! P6 Component #12: `image-compare`
5//!
6//! - Before/After split frame supporting both `Horizontal` (left/right) and `Vertical` (top/bottom)
7//!   orientations, 1:1 pointer dragging anywhere on the frame with iOS-style rubber-band resistance
8//!   past 0% / 100%, edge-softened handle capsule that widens while dragging (`40×40` -> `56×36`),
9//!   corner labels that fade as the divider approaches them, double-click reset to 50%, and
10//!   keyboard stepping (`Arrow` 1%, `Shift+Arrow` / `PageUp` / `PageDown` 10%, `Home` / `End`).
11
12use std::{cell::RefCell, rc::Rc};
13
14use arc_motion::{arc_spring_with_options, is_reduced_motion, spring::SpringOptions};
15use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography};
16use gpui_kit::{
17    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
18    MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, RenderOnce,
19    Role, SharedString, Styled, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
20};
21
22/// Orientation of the split divider.
23#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
24pub enum ImageCompareOrientation {
25    #[default]
26    Horizontal,
27    Vertical,
28}
29
30/// Rubber-band resistance past an edge (`STRETCH = 9px`, matching `image-compare.tsx`).
31pub fn image_compare_rubber(distance: f32, limit: f32) -> f32 {
32    if distance == 0.0 || limit <= 0.0 {
33        return 0.0;
34    }
35    distance.signum() * (1.0 - 1.0 / (distance.abs() * 0.55 / limit + 1.0)) * limit
36}
37
38/// Pure helper clamping divider percentage to `[0.0, 100.0]`.
39pub fn clamp_compare_position(pos: f32) -> f32 {
40    pos.clamp(0.0, 100.0)
41}
42
43fn paint_split_chevrons(cx: f32, cy: f32, vertical: bool, color: Hsla, window: &mut Window) {
44    let mut paint_pair = |dx1: f32, dy1: f32, dx2: f32, dy2: f32, dx3: f32, dy3: f32| {
45        let mut pb = PathBuilder::stroke(px(1.7));
46        pb.move_to(point(px(cx + dx1), px(cy + dy1)));
47        pb.line_to(point(px(cx + dx2), px(cy + dy2)));
48        pb.line_to(point(px(cx + dx3), px(cy + dy3)));
49        if let Ok(p) = pb.build() {
50            window.paint_path(p, color);
51        }
52    };
53    if vertical {
54        // Up chevron
55        paint_pair(-3.5, -3.5, 0.0, -7.0, 3.5, -3.5);
56        // Down chevron
57        paint_pair(-3.5, 3.5, 0.0, 7.0, 3.5, 3.5);
58    } else {
59        // Left chevron
60        paint_pair(-3.5, -3.5, -7.0, 0.0, -3.5, 3.5);
61        // Right chevron
62        paint_pair(3.5, -3.5, 7.0, 0.0, 3.5, 3.5);
63    }
64}
65
66type LayerBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
67type PositionCallback = Rc<dyn Fn(f32, &mut Window, &mut App)>;
68
69#[derive(Clone)]
70struct ImageCompareInternal {
71    position: f32,
72    dragging: bool,
73    rubber_pct: f32,
74    frame_bounds: Option<Bounds<Pixels>>,
75    focus_handle: FocusHandle,
76}
77
78/// Interactive before/after comparison frame with horizontal/vertical split (`image-compare`).
79#[derive(IntoElement)]
80pub struct ImageCompare {
81    id: ElementId,
82    before: LayerBuilder,
83    after: LayerBuilder,
84    position_override: Option<f32>,
85    default_position: f32,
86    orientation: ImageCompareOrientation,
87    labels: Option<(SharedString, SharedString)>,
88    height_px: f32,
89    on_position_change: Option<PositionCallback>,
90}
91
92impl ImageCompare {
93    pub fn new(
94        id: impl Into<ElementId>,
95        before: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
96        after: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
97    ) -> Self {
98        Self {
99            id: id.into(),
100            before: Rc::new(before),
101            after: Rc::new(after),
102            position_override: None,
103            default_position: 50.0,
104            orientation: ImageCompareOrientation::Horizontal,
105            labels: Some((SharedString::from("Before"), SharedString::from("After"))),
106            height_px: 300.0,
107            on_position_change: None,
108        }
109    }
110
111    pub fn position(mut self, position: f32) -> Self {
112        self.position_override = Some(clamp_compare_position(position));
113        self
114    }
115
116    pub fn default_position(mut self, position: f32) -> Self {
117        self.default_position = clamp_compare_position(position);
118        self
119    }
120
121    pub fn orientation(mut self, orientation: ImageCompareOrientation) -> Self {
122        self.orientation = orientation;
123        self
124    }
125
126    pub fn labels(
127        mut self,
128        before: impl Into<SharedString>,
129        after: impl Into<SharedString>,
130    ) -> Self {
131        self.labels = Some((before.into(), after.into()));
132        self
133    }
134
135    pub fn hide_labels(mut self) -> Self {
136        self.labels = None;
137        self
138    }
139
140    pub fn height(mut self, height_px: f32) -> Self {
141        self.height_px = height_px.max(120.0);
142        self
143    }
144
145    pub fn on_position_change(mut self, cb: impl Fn(f32, &mut Window, &mut App) + 'static) -> Self {
146        self.on_position_change = Some(Rc::new(cb));
147        self
148    }
149}
150
151impl RenderOnce for ImageCompare {
152    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
153        let theme = cx.arc_theme().clone();
154        let colors = theme.colors;
155        let reduced = is_reduced_motion(cx);
156        let vertical = matches!(self.orientation, ImageCompareOrientation::Vertical);
157        let controlled = self.position_override.is_some();
158
159        let state_cell = window
160            .use_keyed_state(
161                ElementId::NamedChild(self.id.clone().into(), SharedString::from("ic-state")),
162                cx,
163                |_, cx| {
164                    Rc::new(RefCell::new(ImageCompareInternal {
165                        position: self.default_position,
166                        dragging: false,
167                        rubber_pct: 0.0,
168                        frame_bounds: None,
169                        focus_handle: cx.focus_handle(),
170                    }))
171                },
172            )
173            .read(cx)
174            .clone();
175
176        let (target_pos, dragging, rubber_pct, bounds_opt, focus_handle) = {
177            let mut st = state_cell.borrow_mut();
178            if let Some(ov) = self.position_override {
179                st.position = ov;
180            }
181            (
182                st.position,
183                st.dragging,
184                st.rubber_pct,
185                st.frame_bounds,
186                st.focus_handle.clone(),
187            )
188        };
189
190        let animated_pos = if dragging || reduced {
191            (target_pos + rubber_pct).clamp(-4.0, 104.0)
192        } else {
193            arc_spring_with_options(
194                (self.id.clone(), "ic-pos"),
195                target_pos,
196                SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
197                window,
198                cx,
199            )
200            .value
201            .clamp(0.0, 100.0)
202        };
203
204        let frame_w = bounds_opt
205            .map(|b| f32::from(b.size.width))
206            .unwrap_or(560.0)
207            .max(1.0);
208        let frame_h = bounds_opt
209            .map(|b| f32::from(b.size.height))
210            .unwrap_or(self.height_px)
211            .max(1.0);
212
213        let split_px = if vertical {
214            (animated_pos / 100.0) * frame_h
215        } else {
216            (animated_pos / 100.0) * frame_w
217        };
218        let clamped_split = split_px.clamp(0.0, if vertical { frame_h } else { frame_w });
219
220        // Handle dimensions morph slightly when dragging (`40×40` -> `52×36` or `36×52`).
221        let (handle_w, handle_h) = if dragging {
222            if vertical { (36.0, 52.0) } else { (52.0, 36.0) }
223        } else {
224            (40.0, 40.0)
225        };
226        let handle_x = if vertical {
227            frame_w * 0.5 - handle_w * 0.5
228        } else {
229            clamped_split.clamp(24.0, (frame_w - 24.0).max(24.0)) - handle_w * 0.5
230        };
231        let handle_y = if vertical {
232            clamped_split.clamp(24.0, (frame_h - 24.0).max(24.0)) - handle_h * 0.5
233        } else {
234            frame_h * 0.5 - handle_h * 0.5
235        };
236
237        // Labels fade smoothly as the divider approaches them.
238        let before_label_opacity = ((clamped_split - 76.0) / 36.0).clamp(0.0, 1.0);
239        let after_room = if vertical {
240            frame_h - clamped_split - 76.0
241        } else {
242            frame_w - clamped_split - 76.0
243        };
244        let after_label_opacity = (after_room / 36.0).clamp(0.0, 1.0);
245
246        let st_down = state_cell.clone();
247        let cb_down = self.on_position_change.clone();
248        let fh_down = focus_handle.clone();
249
250        let st_key = state_cell.clone();
251        let cb_key = self.on_position_change.clone();
252
253        let st_canvas = state_cell.clone();
254        let cb_move = self.on_position_change.clone();
255        let st_move = state_cell.clone();
256        let st_up = state_cell.clone();
257
258        let before_el = (self.before)(window, cx);
259        let after_el = (self.after)(window, cx);
260
261        let before_layer = if vertical {
262            div()
263                .absolute()
264                .left(px(0.0))
265                .top(px(0.0))
266                .w(px(frame_w))
267                .h(px(clamped_split))
268                .overflow_hidden()
269                .child(div().w(px(frame_w)).h(px(frame_h)).child(before_el))
270        } else {
271            div()
272                .absolute()
273                .left(px(0.0))
274                .top(px(0.0))
275                .w(px(clamped_split))
276                .h(px(frame_h))
277                .overflow_hidden()
278                .child(div().w(px(frame_w)).h(px(frame_h)).child(before_el))
279        };
280
281        let divider_line = if vertical {
282            div()
283                .absolute()
284                .left(px(0.0))
285                .top(px(clamped_split - 1.0))
286                .w_full()
287                .h(px(2.0))
288                .bg(colors.surface_raised)
289        } else {
290            div()
291                .absolute()
292                .left(px(clamped_split - 1.0))
293                .top(px(0.0))
294                .w(px(2.0))
295                .h_full()
296                .bg(colors.surface_raised)
297        };
298
299        let chevron_col = colors.foreground;
300        let handle_knob = div()
301            .absolute()
302            .left(px(handle_x))
303            .top(px(handle_y))
304            .w(px(handle_w))
305            .h(px(handle_h))
306            .rounded(Radii::PILL)
307            .bg(colors.surface_raised)
308            .border_1()
309            .border_color(colors.border)
310            .shadow(Shadows::raised(theme.mode))
311            .child(
312                canvas(
313                    |_, _, _| {},
314                    move |bounds, _, window, _| {
315                        let cx_p = f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
316                        let cy_p = f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
317                        paint_split_chevrons(cx_p, cy_p, vertical, chevron_col, window);
318                    },
319                )
320                .w_full()
321                .h_full(),
322            );
323
324        let mut frame = div()
325            .id(self.id.clone())
326            .relative()
327            .w_full()
328            .h(px(self.height_px))
329            .rounded(Radii::PANEL)
330            .border_1()
331            .border_color(colors.border)
332            .overflow_hidden()
333            .cursor(if vertical {
334                gpui_kit::CursorStyle::ResizeUpDown
335            } else {
336                gpui_kit::CursorStyle::ResizeLeftRight
337            })
338            .track_focus(&focus_handle)
339            .role(Role::Slider)
340            .on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
341                window.focus(&fh_down, cx);
342                let mut st = st_down.borrow_mut();
343                if ev.click_count >= 2 {
344                    if !controlled {
345                        st.position = 50.0;
346                    }
347                    st.dragging = false;
348                    st.rubber_pct = 0.0;
349                    if let Some(cb) = &cb_down {
350                        cb(50.0, window, cx);
351                    }
352                    window.refresh();
353                    return;
354                }
355                st.dragging = true;
356                if let Some(b) = st.frame_bounds {
357                    let raw = if vertical {
358                        (f32::from(ev.position.y - b.origin.y) / f32::from(b.size.height).max(1.0))
359                            * 100.0
360                    } else {
361                        (f32::from(ev.position.x - b.origin.x) / f32::from(b.size.width).max(1.0))
362                            * 100.0
363                    };
364                    let clamped = clamp_compare_position(raw);
365                    if !controlled {
366                        st.position = clamped;
367                    }
368                    st.rubber_pct = 0.0;
369                    if let Some(cb) = &cb_down {
370                        cb(clamped, window, cx);
371                    }
372                }
373                window.refresh();
374            })
375            .on_key_down(move |ev: &KeyDownEvent, window, cx| {
376                let step = if ev.keystroke.modifiers.shift {
377                    10.0
378                } else {
379                    1.0
380                };
381                let key = ev.keystroke.key.as_str();
382                let mut st = st_key.borrow_mut();
383                let cur = st.position;
384                let next = match key {
385                    "left" | "up" => clamp_compare_position(cur - step),
386                    "right" | "down" => clamp_compare_position(cur + step),
387                    "pageup" => clamp_compare_position(cur - 10.0),
388                    "pagedown" => clamp_compare_position(cur + 10.0),
389                    "home" => 0.0,
390                    "end" => 100.0,
391                    _ => return,
392                };
393                if (next - cur).abs() > 1e-4 {
394                    if !controlled {
395                        st.position = next;
396                    }
397                    if let Some(cb) = &cb_key {
398                        cb(next, window, cx);
399                    }
400                    window.refresh();
401                }
402            })
403            // After layer (full background)
404            .child(div().w_full().h_full().child(after_el))
405            // Before layer (clipped)
406            .child(before_layer)
407            // Global pointer listener & bounds capture canvas
408            .child(
409                canvas(
410                    move |bounds, _, _| {
411                        st_canvas.borrow_mut().frame_bounds = Some(bounds);
412                    },
413                    move |_, _, window, _| {
414                        let st_m = st_move.clone();
415                        let cb_m = cb_move.clone();
416                        window.on_mouse_event(move |ev: &MouseMoveEvent, _, window, cx| {
417                            let mut st = st_m.borrow_mut();
418                            if !st.dragging {
419                                return;
420                            }
421                            let Some(b) = st.frame_bounds else {
422                                return;
423                            };
424                            let axis_px = if vertical {
425                                f32::from(b.size.height).max(1.0)
426                            } else {
427                                f32::from(b.size.width).max(1.0)
428                            };
429                            let raw_pct = if vertical {
430                                (f32::from(ev.position.y - b.origin.y) / axis_px) * 100.0
431                            } else {
432                                (f32::from(ev.position.x - b.origin.x) / axis_px) * 100.0
433                            };
434                            let clamped = clamp_compare_position(raw_pct);
435                            let over_px = ((raw_pct - clamped) / 100.0) * axis_px;
436                            st.rubber_pct = if reduced {
437                                0.0
438                            } else {
439                                (image_compare_rubber(over_px, 9.0) / axis_px) * 100.0
440                            };
441                            if !controlled {
442                                st.position = clamped;
443                            }
444                            if let Some(cb) = &cb_m {
445                                cb(clamped, window, cx);
446                            }
447                            window.refresh();
448                        });
449
450                        let st_u = st_up.clone();
451                        window.on_mouse_event(move |_: &MouseUpEvent, _, window, _| {
452                            let mut st = st_u.borrow_mut();
453                            if st.dragging {
454                                st.dragging = false;
455                                st.rubber_pct = 0.0;
456                                window.refresh();
457                            }
458                        });
459                    },
460                )
461                .absolute()
462                .inset_0(),
463            )
464            .child(divider_line)
465            .child(handle_knob);
466
467        if let Some((before_lbl, after_lbl)) = self.labels {
468            let chip_bg = colors.surface_raised.opacity(0.88);
469            frame = frame
470                .child(
471                    div()
472                        .absolute()
473                        .left(Spacing::S3)
474                        .top(Spacing::S3)
475                        .px(Spacing::S2)
476                        .py(px(3.0))
477                        .rounded(Radii::PILL)
478                        .bg(chip_bg)
479                        .border_1()
480                        .border_color(colors.border)
481                        .opacity(before_label_opacity)
482                        .text_size(Typography::TEXT_XS)
483                        .font_medium()
484                        .text_color(colors.foreground)
485                        .child(before_lbl),
486                )
487                .child(
488                    div()
489                        .absolute()
490                        .right(Spacing::S3)
491                        .when(vertical, |this| this.bottom(Spacing::S3))
492                        .when(!vertical, |this| this.top(Spacing::S3))
493                        .px(Spacing::S2)
494                        .py(px(3.0))
495                        .rounded(Radii::PILL)
496                        .bg(chip_bg)
497                        .border_1()
498                        .border_color(colors.border)
499                        .opacity(after_label_opacity)
500                        .text_size(Typography::TEXT_XS)
501                        .font_medium()
502                        .text_color(colors.foreground)
503                        .child(after_lbl),
504                );
505        }
506
507        frame
508    }
509}
510
511#[cfg(test)]
512mod tests {
513    use super::*;
514
515    #[test]
516    fn rubber_band_is_monotonic_and_bounded_by_limit() {
517        let a = image_compare_rubber(10.0, 9.0);
518        let b = image_compare_rubber(200.0, 9.0);
519        assert!(a > 0.0 && a < b && b < 9.0);
520        assert!((image_compare_rubber(-50.0, 9.0) + image_compare_rubber(50.0, 9.0)).abs() < 1e-5);
521        assert_eq!(clamp_compare_position(-12.0), 0.0);
522        assert_eq!(clamp_compare_position(140.0), 100.0);
523    }
524}