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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
//! 原生移植 React Bits BranchedMenu,© David Haz,MIT + Commons Clause。
//! 双层导航,非递归 TreeView;圆弧按弧长截断,所有时间来自共享 MotionClock。
use arc_motion::{
    CubicBezier, ScalarTween, TweenEase, is_reduced_motion, motion_now,
    path::{PathPoint, PolylinePath},
};
use arc_tokens::ActiveArcTheme as _;
use gpui_kit::{
    App, ElementId, FocusHandle, Hsla, IntoElement, ParentElement, RenderOnce, Role, SharedString,
    Styled, TestSupportExt as _, Window, assets::IconName, base::StyledExt as _, canvas, div,
    point, prelude::*, px, svg,
};
use std::{cell::RefCell, collections::BTreeSet, rc::Rc};

#[derive(Clone, Debug)]
pub struct BranchedMenuItem {
    pub value: SharedString,
    pub label: SharedString,
    pub icon: Option<IconName>,
    /// None 为叶子;Some(empty) 仍为可折叠的空分组。
    pub children: Option<Vec<BranchedMenuItem>>,
}
impl BranchedMenuItem {
    pub fn leaf(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
            icon: None,
            children: None,
        }
    }
    pub fn section(
        label: impl Into<SharedString>,
        children: impl IntoIterator<Item = Self>,
    ) -> Self {
        Self {
            value: "".into(),
            label: label.into(),
            icon: None,
            children: Some(children.into_iter().collect()),
        }
    }
    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon = Some(icon);
        self
    }
    fn leaf_value(&self) -> SharedString {
        if self.value.is_empty() {
            self.label.clone()
        } else {
            self.value.clone()
        }
    }
}
#[derive(Clone, Debug)]
pub struct BranchedMenuConfig {
    pub color: Option<Hsla>,
    pub accent_color: Option<Hsla>,
    pub line_color: Option<Hsla>,
    pub width: f32,
    pub row_height: f32,
    pub indent: f32,
    pub trunk: f32,
    pub radius: f32,
    pub line_width: f32,
    pub font_size: f32,
    /// 毫秒,与上游 Props 一致。
    pub draw_duration: f32,
    pub fold_duration: f32,
}
impl Default for BranchedMenuConfig {
    fn default() -> Self {
        Self {
            color: None,
            accent_color: None,
            line_color: None,
            width: 240.,
            row_height: 36.,
            indent: 40.,
            trunk: 14.,
            radius: 10.,
            line_width: 1.5,
            font_size: 14.,
            draw_duration: 400.,
            fold_duration: 300.,
        }
    }
}
impl BranchedMenuConfig {
    fn normalized(&self) -> Self {
        let mut c = self.clone();
        let d = Self::default();
        macro_rules! norm {
            ($f:ident,$lo:expr,$hi:expr) => {
                c.$f = if c.$f.is_finite() {
                    c.$f.clamp($lo, $hi)
                } else {
                    d.$f
                };
            };
        }
        norm!(width, 32., 2000.);
        norm!(row_height, 12., 160.);
        norm!(indent, 12., 300.);
        norm!(trunk, 0., 280.);
        c.indent = c.indent.max(c.trunk + 8.);
        c.trunk = c.trunk.min(c.indent - 8.);
        norm!(radius, 0., 80.);
        c.radius = c
            .radius
            .min((c.row_height / 2. - 2.).max(0.))
            .min((c.indent - 8. - c.trunk).max(0.));
        norm!(line_width, 0.1, 12.);
        norm!(font_size, 8., 60.);
        norm!(draw_duration, 0., 5000.);
        norm!(fold_duration, 0., 5000.);
        c
    }
}
#[derive(Clone, Debug)]
pub struct BranchedMenuSelection {
    pub value: SharedString,
    pub item: BranchedMenuItem,
}
#[derive(Clone, Copy, Debug)]
pub struct BranchedMenuToggle {
    pub index: usize,
    pub open: bool,
}
type SelectHandler = Rc<dyn Fn(&BranchedMenuSelection, &mut Window, &mut App)>;
type ToggleHandler = Rc<dyn Fn(&BranchedMenuToggle, &mut Window, &mut App)>;
struct SectionMotion {
    fold: ScalarTween,
    lines: ScalarTween,
    reaches: Vec<ScalarTween>,
}
struct State {
    open: BTreeSet<usize>,
    active: SharedString,
    shape: Vec<(SharedString, Option<Vec<SharedString>>)>,
    motion: Vec<SectionMotion>,
    focus: Vec<Vec<FocusHandle>>,
    marker: ScalarTween,
    marker_alpha: ScalarTween,
    marker_section: Option<usize>,
    measured_width: f32,
}
fn curve() -> TweenEase {
    TweenEase::CubicBezier(CubicBezier::new(0.23, 1., 0.32, 1.))
}
fn initial_active(items: &[BranchedMenuItem], open: &BTreeSet<usize>) -> SharedString {
    items
        .iter()
        .enumerate()
        .find_map(|(i, item)| {
            if open.contains(&i) {
                item.children
                    .as_ref()
                    .and_then(|v| v.first())
                    .map(|v| v.value.clone())
            } else {
                None
            }
        })
        .unwrap_or_default()
}
/// 与源码相同的竖线 + 四分之一圆弧 + 水平分支;圆弧离散误差小于0.02px。
fn reach(c: &BranchedMenuConfig, k: usize, full: bool) -> PolylinePath {
    let y = 6. + k as f32 * c.row_height + c.row_height / 2.;
    let r = c.radius;
    let mut pts = vec![PathPoint::new(c.trunk, if full { 0. } else { y - r })];
    pts.push(PathPoint::new(c.trunk, y - r));
    for j in 1..=24 {
        let a = j as f32 / 24. * std::f32::consts::FRAC_PI_2;
        pts.push(PathPoint::new(
            c.trunk + r - r * a.cos(),
            y - r + r * a.sin(),
        ));
    }
    pts.push(PathPoint::new(c.indent - 8., y));
    PolylinePath::new(pts)
}
fn paint_path(
    path: &PolylinePath,
    origin: gpui_kit::Point<gpui_kit::Pixels>,
    width: f32,
    color: Hsla,
    window: &mut Window,
) {
    if let Some(builder) = path.to_stroke_builder(origin.x, origin.y, px(width))
        && let Ok(p) = builder.build()
    {
        window.paint_path(p, color);
    }
    // 原生路径的端帽显式画圆,不依赖默认的平头端帽。
    for p in [path.points.first(), path.points.last()]
        .into_iter()
        .flatten()
    {
        window.paint_quad(
            gpui_kit::fill(
                gpui_kit::Bounds::new(
                    origin + point(px(p.x - width / 2.), px(p.y - width / 2.)),
                    gpui_kit::size(px(width), px(width)),
                ),
                color,
            )
            .corner_radii(px(width / 2.)),
        );
    }
}
#[derive(IntoElement)]
pub struct BranchedMenu {
    id: ElementId,
    items: Vec<BranchedMenuItem>,
    config: BranchedMenuConfig,
    default_open: Vec<usize>,
    default_active: SharedString,
    open: Option<Vec<usize>>,
    active: Option<SharedString>,
    on_select: Option<SelectHandler>,
    on_toggle: Option<ToggleHandler>,
}
impl BranchedMenu {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            items: default_items(),
            config: Default::default(),
            default_open: vec![0],
            default_active: "".into(),
            open: None,
            active: None,
            on_select: None,
            on_toggle: None,
        }
    }
    pub fn items(mut self, items: impl IntoIterator<Item = BranchedMenuItem>) -> Self {
        self.items = items.into_iter().collect();
        self
    }
    pub fn config(mut self, c: BranchedMenuConfig) -> Self {
        self.config = c;
        self
    }
    pub fn default_open(mut self, indices: impl IntoIterator<Item = usize>) -> Self {
        self.default_open = indices.into_iter().collect();
        self
    }
    pub fn default_active(mut self, value: impl Into<SharedString>) -> Self {
        self.default_active = value.into();
        self
    }
    pub fn open(mut self, indices: impl IntoIterator<Item = usize>) -> Self {
        self.open = Some(indices.into_iter().collect());
        self
    }
    pub fn active(mut self, value: impl Into<SharedString>) -> Self {
        self.active = Some(value.into());
        self
    }
    pub fn on_select(
        mut self,
        cb: impl Fn(&BranchedMenuSelection, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_select = Some(Rc::new(cb));
        self
    }
    pub fn on_toggle(
        mut self,
        cb: impl Fn(&BranchedMenuToggle, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_toggle = Some(Rc::new(cb));
        self
    }
}
pub fn default_items() -> Vec<BranchedMenuItem> {
    vec![
        BranchedMenuItem::section(
            "Getting started",
            [
                BranchedMenuItem::leaf("install", "Installation"),
                BranchedMenuItem::leaf("quick", "Quick start"),
                BranchedMenuItem::leaf("config", "Configuration"),
                BranchedMenuItem::leaf("theming", "Theming"),
            ],
        ),
        BranchedMenuItem::section(
            "Components",
            [
                BranchedMenuItem::leaf("buttons", "Buttons"),
                BranchedMenuItem::leaf("typography", "Typography"),
                BranchedMenuItem::leaf("overlays", "Overlays"),
                BranchedMenuItem::leaf("toasts", "Toasts"),
            ],
        ),
    ]
}
impl RenderOnce for BranchedMenu {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let c = self.config.normalized();
        let now = motion_now(cx);
        let reduced = is_reduced_motion(cx);
        let colors = cx.arc_theme().colors;
        let ink = c.color.unwrap_or(colors.foreground);
        let accent = c.accent_color.unwrap_or(ink);
        let line = c.line_color.unwrap_or(colors.border_strong);
        let state = window
            .use_keyed_state(
                ElementId::NamedChild(self.id.clone().into(), "state".into()),
                cx,
                |_, _| {
                    let open = self
                        .default_open
                        .iter()
                        .copied()
                        .filter(|&i| self.items.get(i).is_some_and(|v| v.children.is_some()))
                        .collect();
                    let active = if self.default_active.is_empty() {
                        initial_active(&self.items, &open)
                    } else {
                        self.default_active.clone()
                    };
                    Rc::new(RefCell::new(State {
                        open,
                        active,
                        shape: Vec::new(),
                        motion: Vec::new(),
                        focus: Vec::new(),
                        marker: ScalarTween::new(0.),
                        marker_alpha: ScalarTween::new(0.),
                        marker_section: None,
                        measured_width: c.width,
                    }))
                },
            )
            .read(cx)
            .clone();
        let mut s = state.borrow_mut();
        if let Some(open) = &self.open {
            s.open = open.iter().copied().collect();
        }
        if let Some(active) = &self.active {
            s.active = active.clone();
        }
        s.open
            .retain(|&i| self.items.get(i).is_some_and(|v| v.children.is_some()));
        let shape = self
            .items
            .iter()
            .map(|v| {
                (
                    v.leaf_value(),
                    v.children
                        .as_ref()
                        .map(|v| v.iter().map(|v| v.value.clone()).collect()),
                )
            })
            .collect::<Vec<_>>();
        if s.shape != shape {
            // 列表身份改变时重建焦点,不沿用另一个选项的句柄。
            s.motion = self
                .items
                .iter()
                .enumerate()
                .map(|(i, item)| {
                    let open = s.open.contains(&i);
                    SectionMotion {
                        fold: ScalarTween::new(if open { 1. } else { 0. }),
                        lines: ScalarTween::new(if open { 1. } else { 0. }),
                        reaches: item
                            .children
                            .iter()
                            .flatten()
                            .map(|v| ScalarTween::new(if v.value == s.active { 1. } else { 0. }))
                            .collect(),
                    }
                })
                .collect();
            s.focus = self
                .items
                .iter()
                .map(|v| {
                    (0..1 + v.children.as_ref().map_or(0, Vec::len))
                        .map(|_| cx.focus_handle().tab_index(0).tab_stop(true))
                        .collect()
                })
                .collect();
            s.shape = shape;
        }
        let active_section = self.items.iter().position(|item| {
            item.children
                .as_ref()
                .is_some_and(|v| v.iter().any(|v| v.value == s.active))
        });
        let header_h = (c.font_size + 1.) * 1.2 + 18.;
        let mut y = 0.;
        let mut marker_y = 0.;
        let active = s.active.clone();
        let open = s.open.clone();
        let mut moving = false;
        for (i, item) in self.items.iter().enumerate() {
            let on = open.contains(&i);
            let m = &mut s.motion[i];
            m.fold.retarget(
                if on { 1. } else { 0. },
                now,
                c.fold_duration / 1000.,
                0.,
                curve(),
                reduced,
            );
            m.lines.retarget(
                if on { 1. } else { 0. },
                now,
                if on { 0.25 } else { 0.2 },
                if on { 0.1 } else { 0. },
                TweenEase::CubicBezier(CubicBezier::new(0.25, 0.1, 0.25, 1.)),
                reduced,
            );
            for (k, kid) in item.children.iter().flatten().enumerate() {
                m.reaches[k].retarget(
                    if kid.value == active { 1. } else { 0. },
                    now,
                    c.draw_duration / 1000.,
                    0.,
                    curve(),
                    reduced,
                );
            }
            moving |= !m.fold.settled(now)
                || !m.lines.settled(now)
                || m.reaches.iter().any(|v| !v.settled(now));
            if active_section == Some(i) {
                marker_y = y + (header_h - 16.) / 2.;
            }
            y += header_h
                + item
                    .children
                    .as_ref()
                    .map_or(0., |v| 12. + v.len() as f32 * c.row_height)
                    * m.fold.sample(now);
        }
        let shown = active_section.is_some_and(|i| open.contains(&i));
        if active_section == s.marker_section && (s.marker.target() - marker_y).abs() > 0.01 {
            s.marker = ScalarTween::new(marker_y);
        } else {
            s.marker.retarget(marker_y, now, 0.22, 0., curve(), reduced);
            s.marker_section = active_section;
        }
        s.marker_alpha.retarget(
            if shown { 1. } else { 0. },
            now,
            0.15,
            0.,
            TweenEase::CubicBezier(CubicBezier::new(0.25, 0.1, 0.25, 1.)),
            reduced,
        );
        moving |= !s.marker.settled(now) || !s.marker_alpha.settled(now);
        let marker = (s.marker.sample(now), s.marker_alpha.sample(now));
        let family = window.text_style().font_family.clone();
        let mut width: f32 = 14.;
        for item in &self.items {
            let measure = |label: &str, size: f32| {
                cx.svg_renderer()
                    .measure_text_width(
                        label,
                        &gpui_kit::SvgTextFont {
                            family: &family,
                            size,
                            weight: "500",
                            style: "normal",
                        },
                    )
                    .unwrap_or(size * label.chars().count() as f32 * 0.6)
            };
            width = width.max(14. + measure(&item.label, c.font_size + 1.));
            for kid in item.children.iter().flatten() {
                width = width.max(
                    14. + c.indent
                        + measure(&kid.label, c.font_size)
                        + if kid.icon.is_some() { 24. } else { 0. },
                );
            }
        }
        s.measured_width = width.min(c.width);
        let width = s.measured_width;
        let focus = s.focus.clone();
        for (i, handles) in focus.iter().enumerate() {
            let on = open.contains(&i);
            for handle in handles.iter().skip(1) {
                let _ = handle.clone().tab_stop(on);
            }
            if !on && handles.iter().skip(1).any(|h| h.is_focused(window)) {
                window.focus(&handles[0], cx);
            }
        }
        let samples = s
            .motion
            .iter()
            .map(|m| {
                (
                    m.fold.sample(now),
                    m.lines.sample(now),
                    m.reaches.iter().map(|v| v.sample(now)).collect::<Vec<_>>(),
                )
            })
            .collect::<Vec<_>>();
        drop(s);
        if moving {
            window.request_animation_frame();
        }
        let mut root = div()
            .id(self.id.clone())
            .test_support()
            .role(Role::Navigation)
            .aria_label("Branched menu")
            .relative()
            .w(px(width))
            .max_w_full()
            .min_w_0()
            .pl(px(14.))
            .flex()
            .flex_col()
            .text_size(px(c.font_size))
            .text_color(ink);
        root = root.child(
            canvas(
                |_, _, _| (),
                move |bounds, _, window, _| {
                    let h = bounds.size.height.as_f32();
                    if h > 8. {
                        window.paint_quad(gpui_kit::fill(
                            gpui_kit::Bounds::new(
                                bounds.origin + point(px(0.), px(8.)),
                                gpui_kit::size(px(2.), px(h - 8.)),
                            ),
                            gpui_kit::linear_gradient(
                                180.,
                                gpui_kit::linear_color_stop(line, 0.55),
                                gpui_kit::linear_color_stop(line.opacity(0.), 1.),
                            ),
                        ));
                    }
                    window.paint_quad(
                        gpui_kit::fill(
                            gpui_kit::Bounds::new(
                                bounds.origin + point(px(0.), px(marker.0)),
                                gpui_kit::size(px(2.), px(16.)),
                            ),
                            accent.opacity(marker.1),
                        )
                        .corner_radii(px(1.)),
                    );
                },
            )
            .absolute()
            .inset_0(),
        );
        for (i, item) in self.items.iter().enumerate() {
            let on = open.contains(&i);
            let is_section = item.children.is_some();
            let head_active = !is_section && item.leaf_value() == active;
            let st = state.clone();
            let cb = self.on_toggle.clone();
            let select = self.on_select.clone();
            let controlled_open = self.open.is_some();
            let controlled_active = self.active.is_some();
            let entry = item.clone();
            let handles = focus[i].clone();
            let head_focus = focus[i][0].clone();
            let mouse_focus = head_focus.clone();
            let mut head = div()
                .id(ElementId::NamedChild(
                    self.id.clone().into(),
                    format!("head-{i}").into(),
                ))
                .test_support()
                .role(Role::Button)
                .aria_label(item.label.clone())
                .track_focus(&head_focus)
                .tab_stop(true)
                .tab_index(0)
                .h(px(header_h))
                .flex_shrink_0()
                .flex()
                .items_center()
                .cursor_pointer()
                .text_size(px(c.font_size + 1.))
                .font_medium()
                .text_color(if on || head_active {
                    ink
                } else {
                    ink.opacity(0.55)
                })
                .hover(move |style| style.text_color(ink))
                .on_mouse_down(gpui_kit::MouseButton::Left, move |_, window, cx| {
                    window.focus(&mouse_focus, cx)
                })
                .on_click(move |_, window, cx| {
                    if is_section {
                        let next = !st.borrow().open.contains(&i);
                        if !next && handles.iter().skip(1).any(|h| h.is_focused(window)) {
                            window.focus(&handles[0], cx);
                        }
                        if !controlled_open {
                            if next {
                                st.borrow_mut().open.insert(i);
                            } else {
                                st.borrow_mut().open.remove(&i);
                            }
                        }
                        if let Some(cb) = &cb {
                            cb(
                                &BranchedMenuToggle {
                                    index: i,
                                    open: next,
                                },
                                window,
                                cx,
                            );
                        }
                    } else {
                        let value = entry.leaf_value();
                        if !controlled_active {
                            st.borrow_mut().active = value.clone();
                        }
                        if let Some(cb) = &select {
                            cb(
                                &BranchedMenuSelection {
                                    value,
                                    item: entry.clone(),
                                },
                                window,
                                cx,
                            );
                        }
                    }
                    window.refresh();
                })
                .child(item.label.clone());
            if is_section {
                head = head.aria_expanded(on);
            } else {
                head = head.aria_selected(head_active);
            }
            if head_focus.is_focused(window) {
                head = head
                    .bg(colors.accent.opacity(0.1))
                    .border_1()
                    .border_color(colors.accent);
            }
            let mut section = div().flex().flex_col().min_w_0().child(head);
            if let Some(kids) = &item.children {
                let height = 12. + kids.len() as f32 * c.row_height;
                let sample = &samples[i];
                let reaches = sample.2.clone();
                let opacity = sample.1;
                let config = c.clone();
                let count = kids.len();
                let mut body = div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        format!("body-{i}").into(),
                    ))
                    .test_support()
                    .h(px(height * sample.0))
                    .flex_shrink_0()
                    .overflow_hidden()
                    .relative();
                let mut tree = div()
                    .h(px(height))
                    .relative()
                    .pt(px(6.))
                    .pb(px(6.))
                    .flex()
                    .flex_col()
                    .child(
                        canvas(
                            |_, _, _| (),
                            move |bounds, _, window, _| {
                                if count == 0 {
                                    return;
                                }
                                let trunk_end = 6.
                                    + (count - 1) as f32 * config.row_height
                                    + config.row_height / 2.
                                    - config.radius;
                                paint_path(
                                    &PolylinePath::new(vec![
                                        PathPoint::new(config.trunk, 0.),
                                        PathPoint::new(config.trunk, trunk_end),
                                    ]),
                                    bounds.origin,
                                    config.line_width,
                                    line.opacity(opacity),
                                    window,
                                );
                                for k in 0..count {
                                    paint_path(
                                        &reach(&config, k, false),
                                        bounds.origin,
                                        config.line_width,
                                        line.opacity(opacity),
                                        window,
                                    );
                                }
                                for (k, p) in reaches.iter().enumerate() {
                                    if *p > 0. {
                                        paint_path(
                                            &reach(&config, k, true).slice(0., *p),
                                            bounds.origin,
                                            config.line_width,
                                            accent.opacity(opacity),
                                            window,
                                        );
                                    }
                                }
                            },
                        )
                        .absolute()
                        .inset_0(),
                    );
                for (k, kid) in kids.iter().enumerate() {
                    let f = focus[i][k + 1].clone();
                    let mf = f.clone();
                    let selected = kid.value == active;
                    let st = state.clone();
                    let cb = self.on_select.clone();
                    let entry = kid.clone();
                    let controlled = self.active.is_some();
                    let mut row = div()
                        .id(ElementId::NamedChild(
                            self.id.clone().into(),
                            format!("item-{i}-{k}").into(),
                        ))
                        .test_support()
                        .role(Role::Button)
                        .aria_label(kid.label.clone())
                        .aria_selected(selected)
                        .track_focus(&f)
                        .tab_stop(on)
                        .tab_index(0)
                        .h(px(c.row_height))
                        .flex_shrink_0()
                        .pl(px(c.indent))
                        .flex()
                        .items_center()
                        .gap(px(8.))
                        .overflow_hidden()
                        .text_color(if selected { accent } else { ink.opacity(0.55) });
                    if selected {
                        row = row.font_medium();
                    }
                    if on {
                        row = row
                            .cursor_pointer()
                            .hover(move |style| style.text_color(ink))
                            .on_mouse_down(gpui_kit::MouseButton::Left, move |_, window, cx| {
                                window.focus(&mf, cx)
                            })
                            .on_click(move |_, window, cx| {
                                if !controlled {
                                    st.borrow_mut().active = entry.value.clone();
                                }
                                if let Some(cb) = &cb {
                                    cb(
                                        &BranchedMenuSelection {
                                            value: entry.value.clone(),
                                            item: entry.clone(),
                                        },
                                        window,
                                        cx,
                                    );
                                }
                                window.refresh();
                            });
                    }
                    if f.is_focused(window) && on {
                        row = row
                            .bg(colors.accent.opacity(0.1))
                            .border_1()
                            .border_color(colors.accent);
                    }
                    if let Some(icon) = kid.icon {
                        row = row.child(svg().path(icon.path()).size(px(16.)).flex_shrink_0());
                    }
                    tree =
                        tree.child(row.child(div().whitespace_nowrap().child(kid.label.clone())));
                }
                body = body.child(tree);
                section = section.child(body);
            }
            root = root.child(section);
        }
        root
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
    struct Host {
        config: BranchedMenuConfig,
        selected: Vec<SharedString>,
        toggles: Vec<(usize, bool)>,
        controlled: bool,
        empty: bool,
    }
    impl Render for Host {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let mut items = default_items();
            items.push(BranchedMenuItem::leaf("about", "About"));
            items.push(BranchedMenuItem::section("Empty", []));
            let mut menu = BranchedMenu::new("bm-test")
                .items(if self.empty { vec![] } else { items })
                .config(self.config.clone())
                .default_open([0, 1])
                .default_active("quick")
                .on_select(cx.listener(|this, e: &BranchedMenuSelection, _, cx| {
                    this.selected.push(e.value.clone());
                    cx.notify();
                }))
                .on_toggle(cx.listener(|this, e: &BranchedMenuToggle, _, cx| {
                    this.toggles.push((e.index, e.open));
                    cx.notify();
                }));
            if self.controlled {
                menu = menu.open([0]).active("install");
            }
            div().w(px(300.)).child(menu)
        }
    }
    fn id(v: &str) -> ElementId {
        ElementId::NamedChild(ElementId::from("bm-test").into(), v.to_owned().into())
    }
    #[gpui_kit::test]
    fn branched_menu_selection_toggle_keyboard_and_controlled(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
        });
        let (view, cx) = cx.add_window_view(|_, _| Host {
            config: Default::default(),
            selected: vec![],
            toggles: vec![],
            controlled: false,
            empty: false,
        });
        cx.update(|w, cx| {
            w.render_frame(cx);
            assert_eq!(w.find("bm-test").role(), Some(Role::Navigation));
            assert!(w.find(id("body-0")).bounds().size.height > px(0.));
            assert!(w.find(id("body-1")).bounds().size.height > px(0.));
            w.click(id("item-0-0"), cx);
            w.render_frame(cx);
            assert_eq!(view.read(cx).selected.len(), 1);
            w.press("enter", cx);
            w.render_frame(cx);
            assert_eq!(view.read(cx).selected.len(), 2);
            w.press("space", cx);
            w.render_frame(cx);
            assert_eq!(view.read(cx).selected.len(), 3);
            w.click(id("head-0"), cx);
            w.render_frame(cx);
            assert_eq!(view.read(cx).toggles, vec![(0, false)]);
            assert_eq!(w.find(id("body-0")).bounds().size.height, px(0.));
            w.click(id("item-1-2"), cx);
            w.render_frame(cx);
            assert_eq!(view.read(cx).selected.last().unwrap().as_ref(), "overlays");
            w.click(id("head-2"), cx);
            w.render_frame(cx);
            assert_eq!(view.read(cx).selected.last().unwrap().as_ref(), "about");
            view.update(cx, |v, cx| {
                v.controlled = true;
                cx.notify();
            });
            w.render_frame(cx);
            w.click(id("head-0"), cx);
            w.render_frame(cx);
            assert!(w.find(id("body-0")).bounds().size.height > px(0.));
            w.click(id("item-0-1"), cx);
            w.render_frame(cx);
            assert_eq!(view.read(cx).selected.last().unwrap().as_ref(), "quick");
            w.click(id("head-3"), cx);
            w.render_frame(cx);
            view.update(cx, |v, cx| {
                v.empty = true;
                cx.notify();
            });
            w.render_frame(cx);
            assert!(w.find("bm-test").bounds().size.width <= px(300.));
        });
    }
    #[gpui_kit::test]
    fn branched_menu_folded_children_leave_focus_order(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
        });
        let (view, cx) = cx.add_window_view(|_, _| Host {
            config: Default::default(),
            selected: vec![],
            toggles: vec![],
            controlled: false,
            empty: false,
        });
        cx.update(|w, cx| {
            w.render_frame(cx);
            w.click(id("head-0"), cx);
            w.render_frame(cx);
            w.focus_next(cx);
            w.render_frame(cx);
        });
        cx.update(|w, cx| {
            w.press("enter", cx);
            w.render_frame(cx);
            assert_eq!(view.read(cx).toggles, vec![(0, false), (1, false)]);
            assert!(view.read(cx).selected.is_empty());
            install_arc_theme(ThemeMode::Dark, Accent::Neutral, cx);
            w.render_frame(cx);
        });
    }
    #[test]
    fn branched_menu_geometry_and_defaults() {
        let c = BranchedMenuConfig::default().normalized();
        let p = reach(&c, 2, true);
        let y = 6. + 2. * 36. + 18.;
        let expected = y - 10. + std::f32::consts::FRAC_PI_2 * 10. + (32. - 14. - 10.);
        assert!((p.total_length() - expected).abs() < 0.01);
        assert_eq!(p.points.last(), Some(&PathPoint::new(32., y)));
        let half = p.slice(0., 0.5);
        assert!((half.total_length() - p.total_length() * 0.5).abs() < 0.01);
        let items = default_items();
        assert_eq!(
            initial_active(&items, &BTreeSet::from([1])).as_ref(),
            "buttons"
        );
        assert!(initial_active(&items, &BTreeSet::new()).is_empty());
        let bad = BranchedMenuConfig {
            radius: 99.,
            row_height: 12.,
            indent: 12.,
            trunk: 88.,
            width: f32::NAN,
            ..c
        }
        .normalized();
        assert_eq!(bad.width, 240.);
        assert!(bad.radius <= 4.);
        assert!(bad.indent - 8. >= bad.trunk + bad.radius);
    }
    #[test]
    fn branched_menu_interruption_and_reduced() {
        let mut t = ScalarTween::new(0.);
        t.retarget(1., 0., 0.3, 0., curve(), false);
        let p = t.sample(0.1);
        assert!(p > 0. && p < 1.);
        t.retarget(0., 0.1, 0.3, 0., curve(), false);
        assert_eq!(t.sample(0.1), p);
        assert_eq!(t.sample(0.5), 0.);
        t.retarget(1., 0.5, 0.3, 0., curve(), true);
        assert_eq!(t.sample(0.5), 1.);
    }
}