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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/accordion/accordion.tsx` & `.module.css`
//!
//! P3 Component #10: `accordion`
//!
//! - Single-collapsible vertical disclosure stack (`type="single" collapsible`): clicking an open
//!   header collapses it (`None`); clicking another header opens it while collapsing the previous
//!   one, retargeting mid-flight without snapping.
//! - Panel height follows measured content height on `motion.spring.smooth` (`0.35s, bounce 0`)
//!   with zero overshoot; closed panels leave the tree once collapsed (`height < 0.5px`).
//! - Answer body settles down from `y: -6px` to `0px` with a focus pull (`blur(2px) -> 0px`,
//!   approximated via `BlurFallback::evaluate` on GPUI).
//! - Header chevron (`17×17px`) rotates `0° -> 180°` on `motion.spring.snappy` (`0.22s, bounce 0`).
//! - Supports `AccordionSize::Md` (compact in-card rows, `40px` min-height, `14px` title/body) and
//!   `AccordionSize::Lg` (page-level FAQ rows, `76px` min-height, `18px` title, `16px` answer).
//! - Full keyboard navigation: `ArrowDown` / `ArrowUp` / `Home` / `End` cycle headers; `Enter` /
//!   `Space` toggle the focused item.

use std::{cell::RefCell, rc::Rc};

use arc_motion::{BlurFallback, arc_spring, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, Spacing, Typography};
use gpui_kit::{
    AnyElement, App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
    ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, TestSupportExt as _,
    Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
};

/// Size variant for [`Accordion`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum AccordionSize {
    /// Standard row density (`min-height: 40px`, `14px` question & answer).
    #[default]
    Md,
    /// Page-level FAQ density (`min-height: 76px`, `18px` question, `16px` answer).
    Lg,
}

/// Single item in an [`Accordion`].
pub struct AccordionItem {
    pub title: SharedString,
    pub content: AnyElement,
}

impl AccordionItem {
    pub fn new(title: impl Into<SharedString>, content: impl IntoElement) -> Self {
        Self {
            title: title.into(),
            content: content.into_any_element(),
        }
    }
}

/// Computes the vertical offset (`px`, `-6.0..=0.0`) and opacity multiplier (`0.0..=1.0`,
/// incorporating `BlurFallback` for `blur.subtle = 2px`) for an accordion answer panel at
/// open progress `p` (`0.0..=1.0`).
pub fn accordion_content_sample(progress: f32, reduced: bool) -> (f32, f32) {
    let p = progress.clamp(0.0, 1.0);
    if reduced {
        return (0.0, if p >= 0.5 { 1.0 } else { 0.0 });
    }
    let y = -6.0 * (1.0 - p);
    let blur = BlurFallback::evaluate(px((1.0 - p) * 2.0), false);
    let opacity = (p * blur.opacity_multiplier).clamp(0.0, 1.0);
    (y, opacity)
}

fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
    let rad = angle_deg.to_radians();
    let cos = rad.cos();
    let sin = rad.sin();
    let rot =
        |dx: f32, dy: f32| -> (f32, f32) { (cx + dx * cos - dy * sin, cy + dx * sin + dy * cos) };
    let (x1, y1) = rot(-4.25, -1.75);
    let (xm, ym) = rot(0.0, 2.5);
    let (x2, y2) = rot(4.25, -1.75);

    let mut b = PathBuilder::stroke(px(1.65));
    b.move_to(point(px(x1), px(y1)));
    b.line_to(point(px(xm), px(ym)));
    b.line_to(point(px(x2), px(y2)));
    if let Ok(path) = b.build() {
        window.paint_path(path, color);
    }
}

type ChangeCallback = Rc<dyn Fn(&Option<usize>, &mut Window, &mut App)>;

#[derive(Clone)]
struct AccordionInternal {
    open_index: Option<usize>,
    focused_index: usize,
    hovered_index: Option<usize>,
    measured_heights: Rc<RefCell<Vec<f32>>>,
    focus_handle: FocusHandle,
}

impl AccordionInternal {
    fn new(default_open: Option<usize>, count: usize, focus_handle: FocusHandle) -> Self {
        let initial = default_open.filter(|&idx| idx < count);
        Self {
            open_index: initial,
            focused_index: initial.unwrap_or(0),
            hovered_index: None,
            measured_heights: Rc::new(RefCell::new(vec![72.0; count])),
            focus_handle,
        }
    }
}

/// Arc `Accordion` — single-collapsible disclosure list with spring-driven height, `-6px` focus-pull
/// content settle, and `180°` snappy chevron rotation.
#[derive(IntoElement)]
pub struct Accordion {
    id: ElementId,
    items: Vec<AccordionItem>,
    default_open: Option<usize>,
    open_index: Option<Option<usize>>,
    size: AccordionSize,
    on_change: Option<ChangeCallback>,
}

impl Accordion {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            items: Vec::new(),
            default_open: Some(0),
            open_index: None,
            size: AccordionSize::Md,
            on_change: None,
        }
    }

    pub fn item(mut self, title: impl Into<SharedString>, content: impl IntoElement) -> Self {
        self.items.push(AccordionItem::new(title, content));
        self
    }

    pub fn items(mut self, items: impl IntoIterator<Item = AccordionItem>) -> Self {
        self.items.extend(items);
        self
    }

    /// Sets the initially open item index (`None` starts with all items collapsed).
    pub fn default_open(mut self, index: Option<usize>) -> Self {
        self.default_open = index;
        self
    }

    /// Controlled open item index (`Some(Some(i))` opens `i`, `Some(None)` collapses all).
    pub fn open_index(mut self, open_index: Option<usize>) -> Self {
        self.open_index = Some(open_index);
        self
    }

    pub fn size(mut self, size: AccordionSize) -> Self {
        self.size = size;
        self
    }

    pub fn on_change(
        mut self,
        handler: impl Fn(&Option<usize>, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_change = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for Accordion {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let count = self.items.len();

        let state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-accordion-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            AccordionInternal::new(self.default_open, count, cx.focus_handle())
        });

        {
            let mut heights = internal.read(cx).measured_heights.borrow_mut();
            if heights.len() < count {
                heights.resize(
                    count,
                    match self.size {
                        AccordionSize::Md => 72.0,
                        AccordionSize::Lg => 88.0,
                    },
                );
            }
        }

        let snap = internal.read(cx).clone();
        let active_open = self.open_index.unwrap_or(snap.open_index);
        let size = self.size;

        let (trigger_min_h, trigger_py, trigger_gap, title_size, body_size, body_pr, body_pb) =
            match size {
                AccordionSize::Md => (
                    px(40.0),
                    Spacing::S2,
                    Spacing::S5,
                    Typography::TEXT_SM,
                    Typography::TEXT_SM,
                    Spacing::S8,
                    Spacing::S5,
                ),
                AccordionSize::Lg => (
                    px(76.0),
                    Spacing::S5,
                    Spacing::S8,
                    Typography::TEXT_LG,
                    Typography::TEXT_BASE,
                    Spacing::S12,
                    Spacing::S6,
                ),
            };

        let int_key = internal.clone();
        let on_change_key = self.on_change.clone();

        let mut root = div()
            .id(self.id.clone())
            .test_support()
            .track_focus(&snap.focus_handle)
            .w_full()
            .flex()
            .flex_col()
            .border_t_1()
            .border_color(colors.border)
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if count == 0 {
                    return;
                }
                let key = event.keystroke.key.as_str();
                match key {
                    "down" | "arrowdown" => {
                        int_key.update(cx, |s, _| {
                            s.focused_index = (s.focused_index + 1) % count;
                        });
                        window.refresh();
                    }
                    "up" | "arrowup" => {
                        int_key.update(cx, |s, _| {
                            s.focused_index = (s.focused_index + count - 1) % count;
                        });
                        window.refresh();
                    }
                    "home" => {
                        int_key.update(cx, |s, _| {
                            s.focused_index = 0;
                        });
                        window.refresh();
                    }
                    "end" => {
                        int_key.update(cx, |s, _| {
                            s.focused_index = count - 1;
                        });
                        window.refresh();
                    }
                    "enter" | "space" | " " => {
                        let next = {
                            let cur = int_key.read(cx);
                            let idx = cur.focused_index.min(count - 1);
                            if cur.open_index == Some(idx) {
                                None
                            } else {
                                Some(idx)
                            }
                        };
                        int_key.update(cx, |s, _| {
                            s.open_index = next;
                        });
                        if let Some(h) = &on_change_key {
                            h(&next, window, cx);
                        }
                        window.refresh();
                    }
                    _ => {}
                }
            });

        for (index, item) in self.items.into_iter().enumerate() {
            let is_open = active_open == Some(index);
            let is_hovered = snap.hovered_index == Some(index);
            let target_progress = if is_open { 1.0_f32 } else { 0.0_f32 };
            let progress = if reduced {
                target_progress
            } else {
                arc_spring(
                    (
                        self.id.clone(),
                        SharedString::from(format!("panel-p-{index}")),
                    ),
                    target_progress,
                    motion.spring.smooth,
                    window,
                    cx,
                )
            };
            let chevron_deg = if reduced {
                if is_open { 180.0 } else { 0.0 }
            } else {
                arc_spring(
                    (
                        self.id.clone(),
                        SharedString::from(format!("chevron-deg-{index}")),
                    ),
                    if is_open { 180.0 } else { 0.0 },
                    motion.spring.snappy,
                    window,
                    cx,
                )
            };

            let natural_h = snap
                .measured_heights
                .borrow()
                .get(index)
                .copied()
                .unwrap_or(72.0)
                .max(24.0);
            let animated_h = (natural_h * progress).max(0.0);
            let (content_y, content_alpha) = accordion_content_sample(progress, reduced);

            let title_color = if is_hovered {
                colors.text_secondary
            } else {
                colors.foreground
            };
            let icon_color = if is_open || is_hovered {
                colors.foreground
            } else {
                colors.text_muted
            };

            let int_hover = internal.clone();
            let int_click = internal.clone();
            let on_change_click = self.on_change.clone();
            let focus_click = snap.focus_handle.clone();

            let trigger = div()
                .id(ElementId::NamedChild(
                    self.id.clone().into(),
                    SharedString::from(format!("trigger-{index}")),
                ))
                .test_support()
                .role(Role::Button)
                .aria_label(item.title.clone())
                .aria_expanded(is_open)
                .w_full()
                .min_h(trigger_min_h)
                .py(trigger_py)
                .flex()
                .items_center()
                .justify_between()
                .gap(trigger_gap)
                .cursor_pointer()
                .on_hover(move |hovered, window, cx| {
                    int_hover.update(cx, |s, _| {
                        if *hovered {
                            s.hovered_index = Some(index);
                        } else if s.hovered_index == Some(index) {
                            s.hovered_index = None;
                        }
                    });
                    window.refresh();
                })
                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                    let next = if active_open == Some(index) {
                        None
                    } else {
                        Some(index)
                    };
                    int_click.update(cx, |s, _| {
                        s.open_index = next;
                        s.focused_index = index;
                    });
                    focus_click.focus(window, cx);
                    if let Some(h) = &on_change_click {
                        h(&next, window, cx);
                    }
                    window.refresh();
                })
                .child(
                    div()
                        .flex_1()
                        .text_size(title_size)
                        .font_medium()
                        .text_color(title_color)
                        .child(item.title),
                )
                .child(
                    div().w(px(17.0)).h(px(17.0)).flex_none().child(
                        canvas(
                            |_, _, _| {},
                            move |bounds, _, window, _| {
                                let cx_pt =
                                    f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
                                let cy_pt = f32::from(bounds.origin.y)
                                    + f32::from(bounds.size.height) * 0.5;
                                paint_rotated_chevron(
                                    cx_pt,
                                    cy_pt,
                                    chevron_deg,
                                    icon_color,
                                    window,
                                );
                            },
                        )
                        .size_full(),
                    ),
                );

            let mut row = div()
                .id(ElementId::NamedChild(
                    self.id.clone().into(),
                    SharedString::from(format!("item-{index}")),
                ))
                .test_support()
                .w_full()
                .flex()
                .flex_col()
                .border_b_1()
                .border_color(colors.border)
                .child(trigger);

            if is_open || animated_h > 0.5 {
                let heights_ref = snap.measured_heights.clone();
                let measure_probe = canvas(
                    move |rect, _, _| {
                        let h = f32::from(rect.size.height);
                        if h > 4.0 {
                            let mut list = heights_ref.borrow_mut();
                            if let Some(slot) = list.get_mut(index) {
                                *slot = h;
                            }
                        }
                    },
                    |_, _, _, _| {},
                )
                .absolute()
                .inset_0();

                row = row.child(
                    div()
                        .id(ElementId::NamedChild(
                            self.id.clone().into(),
                            SharedString::from(format!("panel-{index}")),
                        ))
                        .test_support()
                        .w_full()
                        .h(px(animated_h))
                        .overflow_hidden()
                        .opacity(content_alpha)
                        .child(
                            div()
                                .relative()
                                .w_full()
                                .top(px(content_y))
                                .pr(body_pr)
                                .pb(body_pb)
                                .text_size(body_size)
                                .text_color(colors.text_secondary)
                                .child(measure_probe)
                                .child(item.content),
                        ),
                );
            }

            root = root.child(row);
        }

        root
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn accordion_content_sample_moves_from_minus_6px_to_zero() {
        let (y0, a0) = accordion_content_sample(0.0, false);
        assert!((y0 - (-6.0)).abs() < 1e-4);
        assert!(a0.abs() < 1e-4);

        let (ym, am) = accordion_content_sample(0.5, false);
        assert!(ym > -6.0 && ym < 0.0);
        assert!(am > 0.2 && am < 0.8);

        let (y1, a1) = accordion_content_sample(1.0, false);
        assert!(y1.abs() < 1e-4);
        assert!((a1 - 1.0).abs() < 1e-4);
    }

    #[test]
    fn accordion_content_sample_respects_reduced_motion() {
        let (y_closed, a_closed) = accordion_content_sample(0.0, true);
        assert!(y_closed.abs() < 1e-4);
        assert!(a_closed.abs() < 1e-4);

        let (y_open, a_open) = accordion_content_sample(1.0, true);
        assert!(y_open.abs() < 1e-4);
        assert!((a_open - 1.0).abs() < 1e-4);
    }
}