arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/image-compare/image-compare.tsx` & `.module.css`
//!
//! P6 Component #12: `image-compare`
//!
//! - Before/After split frame supporting both `Horizontal` (left/right) and `Vertical` (top/bottom)
//!   orientations, 1:1 pointer dragging anywhere on the frame with iOS-style rubber-band resistance
//!   past 0% / 100%, edge-softened handle capsule that widens while dragging (`40×40` -> `56×36`),
//!   corner labels that fade as the divider approaches them, double-click reset to 50%, and
//!   keyboard stepping (`Arrow` 1%, `Shift+Arrow` / `PageUp` / `PageDown` 10%, `Home` / `End`).

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,
};

/// Orientation of the split divider.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ImageCompareOrientation {
    #[default]
    Horizontal,
    Vertical,
}

/// Rubber-band resistance past an edge (`STRETCH = 9px`, matching `image-compare.tsx`).
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
}

/// Pure helper clamping divider percentage to `[0.0, 100.0]`.
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 {
        // Up chevron
        paint_pair(-3.5, -3.5, 0.0, -7.0, 3.5, -3.5);
        // Down chevron
        paint_pair(-3.5, 3.5, 0.0, 7.0, 3.5, 3.5);
    } else {
        // Left chevron
        paint_pair(-3.5, -3.5, -7.0, 0.0, -3.5, 3.5);
        // Right chevron
        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,
}

/// Interactive before/after comparison frame with horizontal/vertical split (`image-compare`).
#[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 });

        // Handle dimensions morph slightly when dragging (`40×40` -> `52×36` or `36×52`).
        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
        };

        // Labels fade smoothly as the divider approaches them.
        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();
                }
            })
            // After layer (full background)
            .child(div().w_full().h_full().child(after_el))
            // Before layer (clipped)
            .child(before_layer)
            // Global pointer listener & bounds capture canvas
            .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);
    }
}