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
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/split-button/split-button.tsx` & `.module.css`
//!
//! P2 Component #4: `split-button`
//!
//! - One joined control with two halves: primary action button + trailing chevron menu trigger.
//! - Primary press scales the whole pill (`0.97`, backdrop canvas); menu trigger press answers in
//!   color only so the anchored menu always measures a still trigger rect.
//! - Variants: `Primary` (`ControlHeights::MD`, `Radii::CONTROL`, `foreground` surface) and
//!   `Secondary` (`ControlHeights::SM`, `Radii::PILL`, `surface` fill with `border`).
//! - Floating menu: `ArcPresence` (`y: -5px -> 0`, `130ms` exit), staggered items (`35ms` capped
//!   at 4), rotating `0° -> 180°` chevron (`PathBuilder` + `motion.spring.snappy`), keyboard
//!   navigation (`ArrowDown`/`ArrowUp`/`Enter`/`Escape`), destructive styling, and outside dismiss.

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

use arc_motion::{
    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, TransformOrigin, arc_spring,
    arc_spring_with_options, is_reduced_motion, motion_now, scaled_bounds, spring::SpringOptions,
};
use arc_tokens::{
    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SplitButtonTokens as T,
    Typography, oklab_mix,
};
use gpui_kit::{
    Anchor, App, BorderStyle, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement,
    KeyDownEvent, MouseButton, MouseDownEvent, ParentElement, PathBuilder, RenderOnce, Role,
    SharedString, Styled, TestSupportExt as _, Window, anchored, assets::IconName,
    base::Button as BaseButton, canvas, deferred, div, point, prelude::*, px, quad, svg,
};

type ActionCallback = Rc<dyn Fn(&(), &mut Window, &mut App)>;

/// Visual style for [`SplitButton`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum SplitButtonVariant {
    #[default]
    Primary,
    Secondary,
}

/// One menu item inside a [`SplitButton`] dropdown.
#[derive(Clone)]
pub struct SplitButtonAction {
    pub label: SharedString,
    pub icon: Option<IconName>,
    pub disabled: bool,
    pub destructive: bool,
    pub on_select: Option<ActionCallback>,
}

impl SplitButtonAction {
    pub fn new(label: impl Into<SharedString>) -> Self {
        Self {
            label: label.into(),
            icon: None,
            disabled: false,
            destructive: false,
            on_select: None,
        }
    }

    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon = Some(icon);
        self
    }

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

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

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

#[derive(Clone)]
struct SplitButtonInternal {
    open: bool,
    opened_at_secs: f64,
    highlighted: Option<usize>,
    primary_hovered: bool,
    primary_pressed: bool,
    trigger_hovered: bool,
    trigger_pressed: bool,
    last_key: SharedString,
    morph_armed_until_secs: f64,
    label_changed_at_secs: f64,
    measured_slot_width: Rc<RefCell<f32>>,
    has_measured: Rc<RefCell<bool>>,
    group_bounds: Rc<RefCell<Option<gpui_kit::Bounds<gpui_kit::Pixels>>>>,
    menu_bounds: Rc<RefCell<Option<gpui_kit::Bounds<gpui_kit::Pixels>>>>,
    focus_handle: FocusHandle,
    trigger_focus: FocusHandle,
    label: SharedString,
    previous_label: SharedString,
    icon: Option<IconName>,
    previous_icon: Option<IconName>,
    icon_changed_at_secs: f64,
}

impl SplitButtonInternal {
    fn new(
        initial_key: SharedString,
        label: SharedString,
        icon: Option<IconName>,
        now: f64,
        focus_handle: FocusHandle,
        trigger_focus: FocusHandle,
    ) -> Self {
        Self {
            open: false,
            opened_at_secs: now - 10.0,
            highlighted: None,
            primary_hovered: false,
            primary_pressed: false,
            trigger_hovered: false,
            trigger_pressed: false,
            last_key: initial_key,
            morph_armed_until_secs: f64::NEG_INFINITY,
            label_changed_at_secs: now - 10.0,
            measured_slot_width: Rc::new(RefCell::new(0.0)),
            has_measured: Rc::new(RefCell::new(false)),
            group_bounds: Rc::new(RefCell::new(None)),
            menu_bounds: Rc::new(RefCell::new(None)),
            focus_handle,
            trigger_focus,
            label,
            previous_label: "".into(),
            icon,
            previous_icon: None,
            icon_changed_at_secs: now - 10.0,
        }
    }
}

/// Arc `SplitButton` joining one primary action with a dropdown menu of sibling actions.
#[derive(IntoElement)]
pub struct SplitButton {
    id: ElementId,
    label: SharedString,
    icon: Option<IconName>,
    actions: Vec<SplitButtonAction>,
    variant: SplitButtonVariant,
    disabled: bool,
    on_click: Option<ActionCallback>,
}

impl SplitButton {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            icon: None,
            actions: Vec::new(),
            variant: SplitButtonVariant::Primary,
            disabled: false,
            on_click: None,
        }
    }

    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon = Some(icon);
        self
    }

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

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

    pub fn action(mut self, action: SplitButtonAction) -> Self {
        self.actions.push(action);
        self
    }

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

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

fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
    let rad = angle_deg.to_radians();
    let cos_a = rad.cos();
    let sin_a = rad.sin();
    let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
    let mut builder = PathBuilder::stroke(px(1.75));
    for (i, (lx, ly)) in pts.iter().enumerate() {
        let rx = cx + lx * cos_a - ly * sin_a;
        let ry = cy + lx * sin_a + ly * cos_a;
        let p = point(px(rx), px(ry));
        if i == 0 {
            builder.move_to(p);
        } else {
            builder.line_to(p);
        }
    }
    if let Ok(path) = builder.build() {
        window.paint_path(path, color);
    }
}

/// 与上游一致,仅保留至少两个字符的共同前后缀身份。
fn shared_edges(previous: &str, next: &str) -> (usize, usize) {
    let previous: Vec<_> = previous.chars().collect();
    let next: Vec<_> = next.chars().collect();
    let mut start = previous
        .iter()
        .zip(&next)
        .take_while(|(a, b)| a == b)
        .count();
    let mut end = previous[start..]
        .iter()
        .rev()
        .zip(next[start..].iter().rev())
        .take_while(|(a, b)| a == b)
        .count();
    if start < 2 {
        start = 0;
    }
    if end < 2 {
        end = 0;
    }
    (start, end)
}

fn next_enabled_index(
    actions: &[SplitButtonAction],
    current: Option<usize>,
    step: isize,
) -> Option<usize> {
    if actions.is_empty() {
        return None;
    }
    let len = actions.len() as isize;
    let start = match current {
        Some(idx) => idx as isize,
        None => {
            if step > 0 {
                -1
            } else {
                len
            }
        }
    };
    for offset in 1..=len {
        let idx = (start + step * offset).rem_euclid(len) as usize;
        if !actions[idx].disabled {
            return Some(idx);
        }
    }
    None
}

impl RenderOnce for SplitButton {
    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 now = motion_now(cx);

        let content_key: SharedString = match self.icon {
            Some(icon) => format!("{icon:?}|{}", self.label).into(),
            None => self.label.clone(),
        };

        let state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-split-button-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            SplitButtonInternal::new(
                content_key.clone(),
                self.label.clone(),
                self.icon,
                now,
                cx.focus_handle(),
                cx.focus_handle(),
            )
        });

        {
            let prev = internal.read(cx).last_key.clone();
            if prev != content_key {
                internal.update(cx, |s, _| {
                    s.last_key = content_key.clone();
                    s.morph_armed_until_secs = now + T::MORPH_WINDOW;
                    if s.label != self.label {
                        s.previous_label = s.label.clone();
                        s.label = self.label.clone();
                        s.label_changed_at_secs = now;
                    }
                    if s.icon != self.icon {
                        s.previous_icon = s.icon;
                        s.icon = self.icon;
                        s.icon_changed_at_secs = now;
                    }
                });
            }
        }

        if self.disabled {
            internal.update(cx, |s, _| {
                s.open = false;
                s.highlighted = None;
                s.primary_pressed = false;
                s.trigger_pressed = false;
            });
        }
        let snap = internal.read(cx).clone();
        let is_open = snap.open && !self.disabled;

        // Primary half scales the whole pill to 0.97; trigger half never scales.
        let target_scale = if !self.disabled && !reduced && snap.primary_pressed {
            T::PRESS_SCALE
        } else {
            1.0
        };
        let animated_scale = if reduced {
            1.0
        } else {
            arc_spring(
                (self.id.clone(), "press-scale"),
                target_scale,
                motion.spring.snappy,
                window,
                cx,
            )
        };

        let chevron_deg = if reduced {
            if is_open { 180.0 } else { 0.0 }
        } else {
            arc_spring(
                (self.id.clone(), "chevron-deg"),
                if is_open { 180.0 } else { 0.0 },
                motion.spring.snappy,
                window,
                cx,
            )
        };

        // Label width morph (`motion.spring.morph`).
        let measured_w = *snap.measured_slot_width.borrow();
        let morph_active = !reduced
            && *snap.has_measured.borrow()
            && measured_w > 0.0
            && now <= snap.morph_armed_until_secs;
        let morphed_w = if measured_w > 0.0 && !reduced {
            let sample = arc_spring_with_options(
                (self.id.clone(), "slot-width"),
                measured_w,
                SpringOptions::new(motion.spring.morph),
                window,
                cx,
            );
            if morph_active {
                Some(sample.value)
            } else {
                None
            }
        } else {
            None
        };

        // 字符自然排版负责精确测宽;仅变化的中间段退场/入场,共同前后缀保持可见。
        let label_elapsed = (now - snap.label_changed_at_secs).max(0.0);
        let label_dur = if reduced {
            motion.duration.instant
        } else {
            motion.duration.standard
        }
        .as_secs_f64();
        let (shared_start, shared_end) = shared_edges(&snap.previous_label, &self.label);
        let count = self.label.chars().count();
        let glyphs = self.label.chars().enumerate().map(|(index, ch)| {
            let kept = index < shared_start || index >= count.saturating_sub(shared_end);
            let delay = if reduced || kept {
                0.0
            } else {
                (index as f64 * motion.stagger.char.as_secs_f64()).min(T::GLYPH_DELAY_CAP)
            };
            let t = if kept {
                1.0
            } else {
                ((label_elapsed - delay) / label_dur).clamp(0.0, 1.0) as f32
            };
            if t < 1.0 {
                window.request_animation_frame();
            }
            let e = if reduced {
                t
            } else {
                CubicBezier::from_spec(motion.ease.enter).sample(t)
            };
            let blur = BlurFallback::evaluate(motion.blur.soft * (1.0 - e), reduced);
            div()
                .relative()
                .flex_none()
                .top(if reduced {
                    px(0.0)
                } else {
                    T::ENTER_Y * (1.0 - e)
                })
                .opacity(e * blur.opacity_multiplier)
                .child(SharedString::from(if ch == ' ' {
                    "\u{00a0}".to_owned()
                } else {
                    ch.to_string()
                }))
        });
        let previous = snap.previous_label.clone();
        let old_count = previous.chars().count();
        let exit_progress = (label_elapsed
            / if reduced {
                motion.duration.instant
            } else {
                motion.duration.fast
            }
            .as_secs_f64())
        .clamp(0.0, 1.0) as f32;
        let old_glyphs = previous.chars().enumerate().map(|(index, ch)| {
            let kept = index < shared_start || index >= old_count.saturating_sub(shared_end);
            div()
                .flex_none()
                .opacity(if kept { 0.0 } else { 1.0 - exit_progress })
                .child(SharedString::from(if ch == ' ' {
                    "\u{00a0}".to_owned()
                } else {
                    ch.to_string()
                }))
        });
        let label_el = div()
            .relative()
            .flex_none()
            .whitespace_nowrap()
            .child(div().flex().children(glyphs))
            .when(!previous.is_empty() && exit_progress < 1.0, |this| {
                window.request_animation_frame();
                this.child(
                    div()
                        .absolute()
                        .left_0()
                        .top(if reduced {
                            px(0.0)
                        } else {
                            T::EXIT_Y * exit_progress
                        })
                        .flex()
                        .children(old_glyphs),
                )
            });
        let icon_progress = ((now - snap.icon_changed_at_secs).max(0.0)
            / motion.duration.fast.as_secs_f64())
        .clamp(0.0, 1.0) as f32;
        if icon_progress < 1.0 {
            window.request_animation_frame();
        }

        // Menu presence (`130ms` exit matches split-button.module.css line 41).
        let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), is_open)
            .animate_initial(false)
            .config(ArcPresenceConfig {
                enter_duration: if reduced {
                    motion.duration.instant
                } else {
                    motion.duration.fast
                },
                exit_duration: if reduced {
                    motion.duration.instant
                } else {
                    T::MENU_EXIT
                },
                enter_ease: motion.ease.enter,
                exit_ease: motion.ease.standard,
                fade_on_reduced_motion: true,
            })
            .sample(window, cx);

        let is_secondary = self.variant == SplitButtonVariant::Secondary;
        let radius = if is_secondary {
            Radii::PILL
        } else {
            Radii::CONTROL
        };
        let min_h = if is_secondary {
            ControlHeights::SM
        } else {
            ControlHeights::MD
        };
        // 与上游一致:主按钮箭头半 38px,次按钮 32px。
        let trigger_w = if is_secondary {
            T::SECONDARY_TRIGGER_WIDTH
        } else {
            T::TRIGGER_WIDTH
        };

        let (base_bg, border_color, fg, divider_color, primary_bg, trigger_bg) = if is_secondary {
            let hover_bg = colors.surface_muted;
            let active_bg = oklab_mix(colors.surface_muted, colors.border, 0.45);
            let p_bg = if self.disabled {
                colors.surface
            } else if snap.primary_pressed {
                active_bg
            } else if snap.primary_hovered {
                hover_bg
            } else {
                colors.surface
            };
            let t_bg = if self.disabled {
                colors.surface
            } else if snap.trigger_pressed || is_open {
                active_bg
            } else if snap.trigger_hovered {
                hover_bg
            } else {
                colors.surface
            };
            (
                colors.surface,
                colors.border,
                colors.foreground,
                colors.border_subtle,
                p_bg,
                t_bg,
            )
        } else {
            let hover_bg = oklab_mix(colors.foreground, colors.background, 0.88);
            let active_bg = oklab_mix(colors.foreground, colors.background, 0.80);
            let p_bg = if self.disabled {
                colors.foreground
            } else if snap.primary_pressed {
                active_bg
            } else if snap.primary_hovered {
                hover_bg
            } else {
                colors.foreground
            };
            let t_bg = if self.disabled {
                colors.foreground
            } else if snap.trigger_pressed || is_open {
                active_bg
            } else if snap.trigger_hovered {
                hover_bg
            } else {
                colors.foreground
            };
            (
                colors.foreground,
                colors.foreground,
                colors.background,
                oklab_mix(colors.background, colors.foreground, 0.18),
                p_bg,
                t_bg,
            )
        };

        let icon_el = div()
            .relative()
            .flex_none()
            .size(Spacing::S4)
            .when_some(self.icon, |this, icon| {
                this.child(
                    svg()
                        .path(icon.path())
                        .size_full()
                        .text_color(fg)
                        .opacity(icon_progress),
                )
            })
            .when_some(
                snap.previous_icon.filter(|_| icon_progress < 1.0),
                |this, icon| {
                    this.child(
                        svg()
                            .absolute()
                            .inset_0()
                            .path(icon.path())
                            .size_full()
                            .text_color(fg)
                            .opacity(1.0 - icon_progress),
                    )
                },
            );

        let group_bounds_ref = snap.group_bounds.clone();
        let menu_bounds_for_outside = snap.menu_bounds.clone();
        let group_bounds_for_outside = snap.group_bounds.clone();
        let internal_outside = internal.clone();
        let backdrop = canvas(
            move |rect, _, _| {
                *group_bounds_ref.borrow_mut() = Some(rect);
            },
            move |rect, _, window, _| {
                let paint_rect = scaled_bounds(
                    rect,
                    animated_scale,
                    animated_scale,
                    TransformOrigin::CENTER,
                );
                window.paint_quad(quad(
                    paint_rect,
                    Corners::all(radius.min(paint_rect.size.height * 0.5)),
                    base_bg,
                    // 描边交给外层容器:画布铺在两半下面,边框画在这里会被
                    // 不透明的按钮底色整片盖住,次按钮就只剩一片白。
                    Edges::all(px(0.0)),
                    border_color,
                    BorderStyle::Solid,
                ));

                // Close menu when user clicks outside both the split button and its menu.
                if is_open {
                    let g_ref = group_bounds_for_outside.clone();
                    let m_ref = menu_bounds_for_outside.clone();
                    let st = internal_outside.clone();
                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
                        if !phase.bubble() {
                            return;
                        }
                        let in_group = g_ref.borrow().is_some_and(|b| b.contains(&event.position));
                        let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
                        if !in_group && !in_menu {
                            st.update(cx, |s, _| {
                                s.open = false;
                                s.highlighted = None;
                            });
                            window.refresh();
                        }
                    });
                }
            },
        )
        .absolute()
        .inset_0();

        let slot_w_ref = snap.measured_slot_width.clone();
        let has_m_ref = snap.has_measured.clone();
        let slot_probe = canvas(
            move |rect, window, _| {
                let w = f32::from(rect.size.width);
                let prev = *slot_w_ref.borrow();
                *slot_w_ref.borrow_mut() = w;
                if w > 0.0 {
                    *has_m_ref.borrow_mut() = true;
                }
                if (w - prev).abs() > 0.5 && prev > 0.0 {
                    window.request_animation_frame();
                }
            },
            |_, _, _, _| {},
        )
        .absolute()
        .inset_0();

        let primary_id = ElementId::NamedChild(self.id.clone().into(), "primary".into());
        let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());

        let int_p_hover = internal.clone();
        let int_p_down = internal.clone();
        let int_p_up = internal.clone();
        let int_p_out = internal.clone();
        let int_t_hover = internal.clone();
        let int_t_down = internal.clone();
        let int_t_up = internal.clone();
        let int_t_out = internal.clone();
        let int_t_click = internal.clone();
        let on_click = self.on_click;
        let is_disabled = self.disabled;
        let focus_for_open = snap.focus_handle.clone();
        let actions_for_trigger = self.actions.clone();
        let int_t_key = internal.clone();
        let actions_for_key = self.actions.clone();
        let menu_key_focus = snap.focus_handle.clone();

        let primary_btn = BaseButton::new(primary_id)
            .disabled(self.disabled)
            .accessibility_label(self.label.clone())
            .on_click(move |_, window, cx| {
                if is_disabled {
                    return;
                }
                if let Some(handler) = &on_click {
                    handler(&(), window, cx);
                }
                window.refresh();
            })
            .relative()
            .flex()
            .items_center()
            .justify_center()
            .min_h(min_h)
            .when(is_secondary, |this| {
                this.min_w(T::SECONDARY_MIN_WIDTH)
                    .px(Spacing::S3)
                    .text_size(Typography::TEXT_XS)
            })
            .when(!is_secondary, |this| {
                this.px(Spacing::S4).text_size(Typography::TEXT_SM)
            })
            .flex_none()
            .whitespace_nowrap()
            .rounded_tl((radius - px(1.0)).max(px(0.0)))
            .rounded_bl((radius - px(1.0)).max(px(0.0)))
            .bg(primary_bg)
            .text_color(fg)
            .when(!self.disabled, |this| this.cursor_pointer())
            .on_hover(move |hovered, window, cx| {
                int_p_hover.update(cx, |s, _| {
                    s.primary_hovered = *hovered;
                    if !*hovered {
                        s.primary_pressed = false;
                    }
                });
                window.refresh();
            })
            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                if is_disabled {
                    return;
                }
                int_p_down.update(cx, |s, _| s.primary_pressed = true);
                window.refresh();
            })
            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                int_p_up.update(cx, |s, _| s.primary_pressed = false);
                window.refresh();
            })
            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
                int_p_out.update(cx, |s, _| s.primary_pressed = false);
                window.refresh();
            })
            .child(
                div()
                    .relative()
                    .flex()
                    .items_center()
                    .when_some(morphed_w, |this, w| this.w(px(w)).overflow_hidden())
                    .child(
                        div()
                            .relative()
                            .flex_none()
                            .flex()
                            .flex_row()
                            .items_center()
                            .gap(Spacing::S2)
                            .child(slot_probe)
                            .when(
                                self.icon.is_some()
                                    || (snap.previous_icon.is_some() && icon_progress < 1.0),
                                |this| this.child(icon_el),
                            )
                            .child(label_el),
                    ),
            );

        let trigger_label = SharedString::from(format!("{} more actions", self.label));
        let trigger_btn = BaseButton::new(trigger_id)
            .track_focus(&snap.trigger_focus)
            .disabled(self.disabled)
            .aria_expanded(is_open)
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                let key = event.keystroke.key.as_str();
                if !is_disabled && matches!(key, "down" | "up") && !actions_for_key.is_empty() {
                    let now = motion_now(cx);
                    int_t_key.update(cx, |s, _| {
                        s.open = true;
                        s.opened_at_secs = now;
                        s.highlighted = next_enabled_index(
                            &actions_for_key,
                            None,
                            if key == "up" { -1 } else { 1 },
                        );
                    });
                    window.focus(&menu_key_focus, cx);
                    window.refresh();
                    cx.stop_propagation();
                }
            })
            .accessibility_label(trigger_label)
            .on_click(move |_, window, cx| {
                if is_disabled {
                    return;
                }
                let t_now = motion_now(cx);
                let mut became_open = false;
                int_t_click.update(cx, |s, _| {
                    s.open = !s.open;
                    became_open = s.open;
                    if s.open {
                        s.opened_at_secs = t_now;
                        s.highlighted = next_enabled_index(&actions_for_trigger, None, 1);
                    } else {
                        s.highlighted = None;
                    }
                });
                if became_open {
                    window.focus(&focus_for_open, cx);
                }
                window.refresh();
            })
            .relative()
            .flex()
            .items_center()
            .justify_center()
            .w(trigger_w)
            .flex_none()
            .min_h(min_h)
            .border_l_1()
            .border_color(divider_color)
            .rounded_tr((radius - px(1.0)).max(px(0.0)))
            .rounded_br((radius - px(1.0)).max(px(0.0)))
            .bg(trigger_bg)
            .text_color(fg)
            .when(!self.disabled, |this| this.cursor_pointer())
            .on_hover(move |hovered, window, cx| {
                int_t_hover.update(cx, |s, _| {
                    s.trigger_hovered = *hovered;
                    if !*hovered {
                        s.trigger_pressed = false;
                    }
                });
                window.refresh();
            })
            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                if is_disabled {
                    return;
                }
                int_t_down.update(cx, |s, _| s.trigger_pressed = true);
                window.refresh();
            })
            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                int_t_up.update(cx, |s, _| s.trigger_pressed = false);
                window.refresh();
            })
            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
                int_t_out.update(cx, |s, _| s.trigger_pressed = false);
                window.refresh();
            })
            .child(
                canvas(
                    |_, _, _| {},
                    move |rect, _, window, _| {
                        let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
                        let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
                        paint_rotated_chevron(cx, cy, chevron_deg, fg, window);
                    },
                )
                .size(px(16.0)),
            );

        // Floating menu rendered via `deferred` overlay with staggered item entrance.
        let menu_el = if menu_presence.should_render() && !self.actions.is_empty() {
            let p = menu_presence.progress.clamp(0.0, 1.0);
            let menu_y = if reduced {
                0.0
            } else {
                -f32::from(T::ENTER_Y) * (1.0 - p)
            };
            let menu_elapsed = (now - snap.opened_at_secs).max(0.0);
            let menu_bounds_ref = snap.menu_bounds.clone();
            let menu_probe = canvas(
                move |rect, _, _| {
                    *menu_bounds_ref.borrow_mut() = Some(rect);
                },
                |_, _, _, _| {},
            )
            .absolute()
            .inset_0();

            let int_key = internal.clone();
            let actions_key = self.actions.clone();
            let menu_id = ElementId::NamedChild(self.id.clone().into(), "menu".into());
            let focus_handle = snap.focus_handle.clone();
            let highlighted = snap.highlighted;
            let return_focus = snap.trigger_focus.clone();
            let has_icons = self.actions.iter().any(|a| a.icon.is_some());
            let viewport = window.viewport_size();
            let menu_width =
                T::MENU_MIN_WIDTH.min((viewport.width - Spacing::S3 * 2.0).max(px(0.0)));
            let menu_height =
                ControlHeights::SM * self.actions.len() as f32 + T::MENU_PADDING * 2.0 + px(2.0);
            let target = snap.group_bounds.borrow().unwrap_or_default();
            let above = target.bottom() + Spacing::S1 + menu_height > viewport.height - Spacing::S3
                && target.top() > viewport.height - target.bottom();
            let layer = anchored()
                .anchor(if above {
                    Anchor::BottomRight
                } else {
                    Anchor::TopRight
                })
                .position(point(
                    target
                        .right()
                        .clamp(Spacing::S3 + menu_width, viewport.width - Spacing::S3),
                    if above {
                        target.top() - Spacing::S1 - px(menu_y)
                    } else {
                        target.bottom() + Spacing::S1 + px(menu_y)
                    },
                ))
                .snap_to_window_with_margin(Spacing::S3);

            let item_rows = self.actions.into_iter().enumerate().map(|(idx, action)| {
                let is_hi = highlighted == Some(idx);
                let item_id = ElementId::NamedChild(
                    self.id.clone().into(),
                    SharedString::from(format!("menu-item-{idx}")),
                );
                let stagger_delay = if reduced {
                    0.0
                } else {
                    (idx.min(4) as f64) * motion.stagger.item.as_secs_f64()
                };
                let item_op = if reduced || !is_open {
                    1.0
                } else {
                    let t = ((menu_elapsed - stagger_delay)
                        / motion.duration.standard.as_secs_f64())
                    .clamp(0.0, 1.0) as f32;
                    if t < 1.0 {
                        window.request_animation_frame();
                    }
                    CubicBezier::from_spec(motion.ease.enter).sample(t)
                };

                let int_hi = internal.clone();
                let int_sel = internal.clone();
                let on_select = action.on_select.clone();
                let item_disabled = action.disabled;
                let item_inert = item_disabled || !is_open;
                let item_return_focus = snap.trigger_focus.clone();
                let item_fg = if action.destructive {
                    colors.danger
                } else {
                    colors.foreground
                };
                let hi_bg = if action.destructive {
                    oklab_mix(colors.danger, colors.surface, 0.08)
                } else {
                    colors.surface_muted
                };

                div()
                    .id(item_id)
                    .test_support()
                    .role(Role::MenuItem)
                    .aria_label(action.label.clone())
                    .flex()
                    .flex_row()
                    .items_center()
                    .gap(T::ITEM_GAP)
                    .min_h(ControlHeights::SM)
                    .px(T::ITEM_PADDING)
                    .rounded(Radii::PANEL - Spacing::S1 - px(2.0))
                    .text_size(Typography::TEXT_SM)
                    .text_color(item_fg)
                    .bg(if is_hi && !item_disabled {
                        hi_bg
                    } else {
                        Hsla::transparent_black()
                    })
                    .opacity(if item_disabled { 0.45 } else { item_op })
                    .when(!item_disabled, |this| this.cursor_pointer())
                    .on_hover(move |hovered, window, cx| {
                        if item_inert {
                            return;
                        }
                        int_hi.update(cx, |s, _| {
                            if *hovered {
                                s.highlighted = Some(idx);
                            } else if s.highlighted == Some(idx) {
                                s.highlighted = None;
                            }
                        });
                        window.refresh();
                    })
                    .on_click(move |_, window, cx| {
                        if item_inert {
                            return;
                        }
                        int_sel.update(cx, |s, _| {
                            s.open = false;
                            s.highlighted = None;
                        });
                        window.focus(&item_return_focus, cx);
                        if let Some(cb) = &on_select {
                            cb(&(), window, cx);
                        }
                        cx.stop_propagation();
                        window.refresh();
                    })
                    .when(has_icons, |this| {
                        this.child(div().flex_none().size(Spacing::S4).when_some(
                            action.icon,
                            |this, icon| {
                                this.child(svg().path(icon.path()).size_full().text_color(item_fg))
                            },
                        ))
                    })
                    .child(action.label)
            });

            Some(
                deferred(
                    layer.child(
                        div()
                            .id(menu_id)
                            .test_support()
                            .track_focus(&focus_handle)
                            .role(Role::Menu)
                            .w(menu_width)
                            .max_h((viewport.height - Spacing::S3 * 2.0).max(ControlHeights::SM))
                            .overflow_y_scroll()
                            .p(T::MENU_PADDING)
                            .rounded(Radii::PANEL)
                            .border_1()
                            .border_color(colors.border)
                            .bg(colors.surface_raised)
                            .shadow(Shadows::floating(theme.mode))
                            .opacity(p)
                            .flex()
                            .flex_col()
                            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                                if !int_key.read(cx).open {
                                    return;
                                }
                                let key = event.keystroke.key.as_str();
                                if matches!(key, "escape" | "down" | "up" | "enter" | "space") {
                                    cx.stop_propagation();
                                }
                                match key {
                                    "escape" => {
                                        window.focus(&return_focus, cx);
                                        int_key.update(cx, |s, _| {
                                            s.open = false;
                                            s.highlighted = None;
                                        });
                                        window.refresh();
                                    }
                                    "down" => {
                                        int_key.update(cx, |s, _| {
                                            s.highlighted =
                                                next_enabled_index(&actions_key, s.highlighted, 1);
                                        });
                                        window.refresh();
                                    }
                                    "up" => {
                                        int_key.update(cx, |s, _| {
                                            s.highlighted =
                                                next_enabled_index(&actions_key, s.highlighted, -1);
                                        });
                                        window.refresh();
                                    }
                                    "enter" | "space" => {
                                        let sel = int_key.read(cx).highlighted;
                                        if let Some(idx) = sel
                                            && let Some(act) = actions_key.get(idx)
                                            && !act.disabled
                                        {
                                            int_key.update(cx, |s, _| {
                                                s.open = false;
                                                s.highlighted = None;
                                            });
                                            window.focus(&return_focus, cx);
                                            if let Some(cb) = &act.on_select {
                                                cb(&(), window, cx);
                                            }
                                            window.refresh();
                                        }
                                    }
                                    _ => {}
                                }
                            })
                            .child(menu_probe)
                            .children(item_rows),
                    ),
                )
                .with_priority(1),
            )
        } else {
            None
        };

        div()
            .id(self.id)
            .relative()
            .flex()
            .flex_row()
            .items_stretch()
            .flex_none()
            .rounded(radius)
            // 外轮廓画在容器上,而不是画在垫底的画布上:画布与两半同尺寸,
            // 描边会被按钮自己的底色覆盖,次按钮就看不到边界。
            .border_1()
            .border_color(border_color)
            // 禁用态整块降透明度:只降文字会让黑色主按钮看起来仍然可用。
            .when(self.disabled, |this| this.opacity(0.52))
            .child(backdrop)
            .child(primary_btn)
            .child(trigger_btn)
            .when_some(menu_el, |this, menu| this.child(menu))
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::Cell, rc::Rc};

    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, MouseButton, Render, Role, TestAppContext, div,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    struct SplitHost {
        primary_clicks: Rc<Cell<usize>>,
        menu_clicks: Rc<Cell<usize>>,
    }

    impl Render for SplitHost {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let p_clicks = self.primary_clicks.clone();
            let m_clicks = self.menu_clicks.clone();
            div().p(Spacing::S6).child(
                SplitButton::new("merge-split", "Merge pull request")
                    .on_click(cx.listener(move |_, _, _, _| {
                        p_clicks.set(p_clicks.get() + 1);
                    }))
                    .actions([
                        SplitButtonAction::new("Squash and merge").on_select(cx.listener(
                            move |_, _, _, _| {
                                m_clicks.set(m_clicks.get() + 1);
                            },
                        )),
                        SplitButtonAction::new("Rebase and merge").disabled(true),
                    ]),
            )
        }
    }

    #[test]
    fn split_button_character_identity_and_navigation() {
        assert_eq!(shared_edges("Copy page", "Copied"), (3, 0));
        assert_eq!(shared_edges("压缩合并", "变基合并"), (0, 2));
        let actions = [
            SplitButtonAction::new("a"),
            SplitButtonAction::new("b").disabled(true),
            SplitButtonAction::new("close").destructive(true),
        ];
        assert_eq!(next_enabled_index(&actions, Some(0), -1), Some(2));
        assert_eq!(next_enabled_index(&actions, Some(2), 1), Some(0));
        assert_eq!(next_enabled_index(&actions, Some(0), 1), Some(2));
    }

    #[gpui_kit::test]
    fn split_button_keyboard_escape_returns_to_trigger(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });
        let menu_clicks = Rc::new(Cell::new(0));
        let (_, cx) = cx.add_window_view(|_, _| SplitHost {
            primary_clicks: Rc::new(Cell::new(0)),
            menu_clicks: menu_clicks.clone(),
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            let t = window
                .find_by_label("Merge pull request more actions")
                .bounds()
                .center();
            window.pointer_down(t, MouseButton::Left, cx);
            window.pointer_up(t, MouseButton::Left, cx);
            window.render_frame(cx);
        });
        cx.simulate_keystrokes("escape");
        cx.update(|window, cx| {
            window.render_frame(cx);
        });
        // Escape 后再次以箭头键展开,只有焦点归还 trigger 才能工作。
        cx.simulate_keystrokes("down");
        cx.update(|window, cx| {
            window.render_frame(cx);
            assert_eq!(
                window.find_by_label("Squash and merge").role(),
                Some(Role::MenuItem)
            );
        });
        cx.simulate_keystrokes("down enter");
        cx.run_until_parked();
        assert_eq!(menu_clicks.get(), 1, "跳过禁用项并循环回首项,只执行一次");
    }

    struct EdgeHost {
        disabled: bool,
    }
    impl Render for EdgeHost {
        fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div()
                .w(window.viewport_size().width)
                .h(window.viewport_size().height)
                .flex()
                .items_end()
                .justify_end()
                .p(Spacing::S1)
                .child(
                    SplitButton::new("edge-split", "Edge")
                        .disabled(self.disabled)
                        .actions([
                            SplitButtonAction::new("Alternative"),
                            SplitButtonAction::new("Close").destructive(true),
                        ]),
                )
        }
    }

    #[gpui_kit::test]
    fn split_button_menu_avoids_edges_and_can_reenable(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Dark, Accent::Violet, cx);
        });
        let (view, cx) = cx.add_window_view(|_, _| EdgeHost { disabled: false });
        cx.update(|window, cx| {
            window.render_frame(cx);
            let t = window.find_by_label("Edge more actions").bounds().center();
            window.pointer_down(t, MouseButton::Left, cx);
            window.pointer_up(t, MouseButton::Left, cx);
            window.render_frame(cx);
            let item = window.find_by_label("Alternative").bounds();
            assert!(
                item.bottom() <= t.y,
                "底部空间不足时应向上打开: item={item:?}, trigger={t:?}, viewport={:?}",
                window.viewport_size()
            );
            assert!(item.left() >= Spacing::S3);
            assert!(item.right() <= window.viewport_size().width - Spacing::S3);
            view.update(cx, |this, cx| {
                this.disabled = true;
                cx.notify();
            });
            window.render_frame(cx);
            view.update(cx, |this, cx| {
                this.disabled = false;
                cx.notify();
            });
            window.render_frame(cx);
            let t = window.find_by_label("Edge more actions").bounds().center();
            window.pointer_down(t, MouseButton::Left, cx);
            window.pointer_up(t, MouseButton::Left, cx);
            window.render_frame(cx);
            assert!(window.find_by_label("Alternative").bounds().bottom() <= t.y);
        });
    }

    #[gpui_kit::test]
    fn split_button_primary_and_menu_selection_work(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });
        let primary_clicks = Rc::new(Cell::new(0usize));
        let menu_clicks = Rc::new(Cell::new(0usize));
        let (_view, cx) = cx.add_window_view(|_, _| SplitHost {
            primary_clicks: primary_clicks.clone(),
            menu_clicks: menu_clicks.clone(),
        });

        cx.update(|window, cx| {
            window.render_frame(cx);
            let primary = window.find_by_label("Merge pull request");
            assert_eq!(primary.role(), Some(Role::Button));
            let pos = primary.bounds().center();
            window.pointer_down(pos, MouseButton::Left, cx);
            window.pointer_up(pos, MouseButton::Left, cx);
            assert_eq!(primary_clicks.get(), 1);

            // Open menu via chevron trigger
            let trigger = window.find_by_label("Merge pull request more actions");
            let t_pos = trigger.bounds().center();
            window.pointer_down(t_pos, MouseButton::Left, cx);
            window.pointer_up(t_pos, MouseButton::Left, cx);
            window.render_frame(cx);

            let item = window.find_by_label("Squash and merge");
            assert_eq!(item.role(), Some(Role::MenuItem));
            let i_pos = item.bounds().center();
            window.pointer_down(i_pos, MouseButton::Left, cx);
            window.pointer_up(i_pos, MouseButton::Left, cx);
            assert_eq!(menu_clicks.get(), 1);
        });
    }
}