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
//! AccordionGallery 原生移植,参考 React Bits © David Haz (DavidHDev)。
//! MIT + Commons Clause,见 THIRD_PARTY_NOTICES。图片与遮罩共用抗锯齿透视圆角平面。

use super::projected_media::ProjectedMedia;
use arc_graphics3d::ProjectedImageParams;
use arc_motion::{ScalarTween, TweenEase, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Typography};
use gpui_kit::{
    App, Bounds, ContentMask, Corners, ElementId, FocusHandle, Hsla, ImageSource,
    ImgResourceLoader, IntoElement, Orientation, ParentElement, Pixels, Point, RenderImage,
    RenderOnce, Role, SharedString, Styled, TestSupportExt as _, TextAlign, TextRun, Window,
    bounds, canvas, div, fill, point, prelude::*, px, size,
};
use std::{cell::RefCell, rc::Rc, sync::Arc};

pub use arc_motion::TweenEase as AccordionGalleryEase;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AccordionGalleryTrigger {
    #[default]
    Hover,
    Click,
}

#[derive(Clone)]
pub struct AccordionGalleryItem {
    pub image: ImageSource,
    pub label: SharedString,
    pub link: Option<SharedString>,
    pub alt: SharedString,
}
impl AccordionGalleryItem {
    pub fn new(image: impl Into<ImageSource>) -> Self {
        Self {
            image: image.into(),
            label: "".into(),
            link: None,
            alt: "".into(),
        }
    }
    pub fn label(mut self, value: impl Into<SharedString>) -> Self {
        self.label = value.into();
        self
    }
    pub fn link(mut self, value: impl Into<SharedString>) -> Self {
        self.link = Some(value.into());
        self
    }
    pub fn alt(mut self, value: impl Into<SharedString>) -> Self {
        self.alt = value.into();
        self
    }
}

#[derive(Clone, Debug)]
pub struct AccordionGalleryConfig {
    pub default_index: usize,
    pub accent_color: Option<Hsla>,
    pub overlay_color: Option<Hsla>,
    pub text_color: Option<Hsla>,
    pub grayscale: bool,
    pub show_labels: bool,
    pub duration: f32,
    pub ease: AccordionGalleryEase,
    pub parallax: f32,
    pub tilt: f32,
    pub stagger: f32,
    pub trigger: AccordionGalleryTrigger,
    pub height: f32,
    pub gap: f32,
    pub radius: f32,
    pub expand_ratio: f32,
    pub orientation: Orientation,
}
impl Default for AccordionGalleryConfig {
    fn default() -> Self {
        Self {
            default_index: 2,
            accent_color: None,
            overlay_color: None,
            text_color: None,
            grayscale: true,
            show_labels: true,
            duration: 0.6,
            ease: TweenEase::Power3Out,
            parallax: 0.5,
            tilt: 8.0,
            stagger: 0.06,
            trigger: AccordionGalleryTrigger::Hover,
            height: 460.0,
            gap: 10.0,
            radius: 16.0,
            expand_ratio: 0.52,
            orientation: Orientation::Horizontal,
        }
    }
}
fn finite(v: f32, default: f32, lo: f32, hi: f32) -> f32 {
    if v.is_finite() {
        v.clamp(lo, hi)
    } else {
        default
    }
}
impl AccordionGalleryConfig {
    fn sanitized(mut self) -> Self {
        self.duration = finite(self.duration, 0.6, 0.0, 10.0);
        self.parallax = finite(self.parallax, 0.5, 0.0, 4.0);
        self.tilt = finite(self.tilt, 8.0, 0.0, 45.0);
        self.stagger = finite(self.stagger, 0.06, 0.0, 2.0);
        self.height = finite(self.height, 460.0, 84.0, 1800.0);
        self.gap = finite(self.gap, 10.0, 0.0, 80.0);
        self.radius = finite(self.radius, 16.0, 0.0, 100.0);
        self.expand_ratio = finite(self.expand_ratio, 0.52, 0.2, 0.9);
        self
    }
    pub fn expanded_grow(&self, count: usize) -> f32 {
        let r = finite(self.expand_ratio, 0.52, 0.2, 0.9);
        if count <= 1 {
            1.0
        } else {
            r * (count - 1) as f32 / (1.0 - r)
        }
    }
}

#[derive(Clone)]
struct PanelMotion {
    grow: ScalarTween,
    angle: ScalarTween,
    drift: ScalarTween,
    gray: ScalarTween,
    dim: ScalarTween,
    bar: ScalarTween,
    text: ScalarTween,
}
impl PanelMotion {
    fn new(i: usize, active: usize, count: usize, c: &AccordionGalleryConfig) -> Self {
        let selected = i == active;
        let sign = if i < active { 1.0 } else { -1.0 };
        Self {
            grow: ScalarTween::new(if selected {
                c.expanded_grow(count)
            } else {
                1.0
            }),
            angle: ScalarTween::new(if selected { 0.0 } else { sign * c.tilt }),
            drift: ScalarTween::new(if selected {
                0.0
            } else {
                (active as f32 - i as f32).clamp(-1.5, 1.5) * c.parallax * 0.06
            }),
            gray: ScalarTween::new(if !selected && c.grayscale { 1.0 } else { 0.0 }),
            dim: ScalarTween::new(if selected { 0.0 } else { 0.35 }),
            bar: ScalarTween::new(if selected && c.show_labels { 1.0 } else { 0.0 }),
            text: ScalarTween::new(if selected && c.show_labels { 1.0 } else { 0.0 }),
        }
    }
    fn update(
        &mut self,
        i: usize,
        active: usize,
        count: usize,
        c: &AccordionGalleryConfig,
        now: f64,
        reduced: bool,
    ) {
        let target = Self::new(i, active, count, c);
        for (current, next) in [
            (&mut self.grow, target.grow),
            (&mut self.angle, target.angle),
            (&mut self.drift, target.drift),
            (&mut self.gray, target.gray),
            (&mut self.dim, target.dim),
        ] {
            current.retarget(next.target(), now, c.duration, 0.0, c.ease, reduced);
        }
        let showing = i == active && c.show_labels;
        let duration = c.duration * if showing { 1.0 } else { 0.6 };
        self.bar
            .retarget(target.bar.target(), now, duration, 0.0, c.ease, reduced);
        self.text.retarget(
            target.text.target(),
            now,
            duration,
            if showing { c.stagger } else { 0.0 },
            c.ease,
            reduced,
        );
    }
    fn settled(&self, now: f64) -> bool {
        [
            self.grow, self.angle, self.drift, self.gray, self.dim, self.bar, self.text,
        ]
        .iter()
        .all(|t| t.settled(now))
    }
}
struct GalleryState {
    active: usize,
    panels: Vec<PanelMotion>,
    focus: Vec<FocusHandle>,
    focused: Option<usize>,
    total: f32,
    vertical: bool,
    last_focus: Option<usize>,
    mouse_was_active: bool,
}
type Change = Rc<dyn Fn(&usize, &mut Window, &mut App)>;
type Activate = Rc<dyn Fn(&AccordionGalleryActivation, &mut Window, &mut App)>;
#[derive(Clone, Debug)]
pub struct AccordionGalleryActivation {
    pub index: usize,
    pub link: SharedString,
}

#[derive(IntoElement)]
pub struct AccordionGallery {
    id: ElementId,
    items: Vec<AccordionGalleryItem>,
    config: AccordionGalleryConfig,
    index: Option<usize>,
    on_change: Option<Change>,
    on_activate: Option<Activate>,
}
impl AccordionGallery {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            items: default_items(),
            config: Default::default(),
            index: None,
            on_change: None,
            on_activate: None,
        }
    }
    pub fn items(mut self, items: impl IntoIterator<Item = AccordionGalleryItem>) -> Self {
        self.items = items.into_iter().collect();
        self
    }
    pub fn config(mut self, config: AccordionGalleryConfig) -> Self {
        self.config = config;
        self
    }
    pub fn index(mut self, index: usize) -> Self {
        self.index = Some(index);
        self
    }
    pub fn on_index_change(mut self, cb: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self {
        self.on_change = Some(Rc::new(cb));
        self
    }
    /// 提供回调时由宿主处理链接,否则已展开项激活后调用系统浏览器(仅 http/https)。
    pub fn on_activate(
        mut self,
        cb: impl Fn(&AccordionGalleryActivation, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_activate = Some(Rc::new(cb));
        self
    }
}
pub fn default_items() -> Vec<AccordionGalleryItem> {
    [
        (1015, "Canyon"),
        (1018, "Ridgeline"),
        (1039, "Falls"),
        (1043, "Harbour"),
        (1044, "Skyline"),
    ]
    .into_iter()
    .map(|(id, label)| {
        AccordionGalleryItem::new(format!("https://picsum.photos/id/{id}/900/1200"))
            .label(label)
            .alt(label)
            .link("#")
    })
    .collect()
}
fn select(
    state: &Rc<RefCell<GalleryState>>,
    index: usize,
    controlled: bool,
    cb: &Option<Change>,
    window: &mut Window,
    cx: &mut App,
) {
    if state.borrow().active == index {
        return;
    }
    if !controlled {
        state.borrow_mut().active = index;
    }
    if let Some(cb) = cb {
        cb(&index, window, cx);
    }
    window.refresh();
}

/// 图像平面绕局部中心旋转,再按根容器的 1400px perspective 投影。
#[cfg(test)]
fn project(x: f32, y: f32, w: f32, h: f32, angle: f32, vertical: bool) -> (f32, f32) {
    let a = angle.to_radians();
    let (u, v) = (x - w * 0.5, y - h * 0.5);
    let (rx, ry, z) = if vertical {
        (u, v * a.cos(), -v * a.sin())
    } else {
        (u * a.cos(), v, -u * a.sin())
    };
    let k = 1400.0 / (1400.0 + z);
    (w * 0.5 + rx * k, h * 0.5 + ry * k)
}
#[derive(Clone, Copy)]
struct PaintSpec {
    angle: f32,
    vertical: bool,
    media: f32,
    drift: f32,
    radius: f32,
    dim: f32,
    overlay: Hsla,
}
// 未取得GPU首帧或GPU不可用时只显示原生圆角图片,不再用矩形条带拼轮廓。
fn paint_media_fallback(
    rect: Bounds<Pixels>,
    image: Option<&Arc<RenderImage>>,
    gray: bool,
    spec: PaintSpec,
    window: &mut Window,
) {
    if let Some(image) = image {
        let native = image.size(0);
        let scale = (rect.size.width.as_f32() / native.width.0 as f32)
            .max(rect.size.height.as_f32() / native.height.0 as f32);
        let image_size = size(
            px(native.width.0 as f32 * scale),
            px(native.height.0 as f32 * scale),
        );
        let dest = bounds(
            rect.center() - point(image_size.width * 0.5, image_size.height * 0.5),
            image_size,
        );
        let _ = window.paint_image(
            rect,
            dest,
            Corners::all(px(spec.radius)),
            image.clone(),
            0,
            gray,
        );
    } else {
        window.paint_quad(fill(rect, spec.overlay).corner_radii(px(spec.radius)));
    }
}
fn load_image(
    source: &ImageSource,
    window: &mut Window,
    cx: &mut App,
) -> (Option<Arc<RenderImage>>, bool) {
    match source {
        ImageSource::Resource(resource) => {
            match window.use_asset::<ImgResourceLoader>(resource, cx) {
                Some(Ok(image)) => (Some(image), false),
                Some(Err(_)) => (None, true),
                None => (None, false),
            }
        }
        ImageSource::Render(image) => (Some(image.clone()), false),
        ImageSource::Custom(loader) => match loader(window, cx) {
            Some(Ok(image)) => (Some(image), false),
            Some(Err(_)) => (None, true),
            None => (None, false),
        },
        ImageSource::Image(image) => (image.clone().use_render_image(window, cx), false),
    }
}
impl RenderOnce for AccordionGallery {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let c = self.config.sanitized();
        let count = self.items.len();
        let colors = cx.arc_theme().colors;
        let accent = c.accent_color.unwrap_or(colors.neutral[0]);
        let overlay = c.overlay_color.unwrap_or(colors.neutral[11]);
        let text_color = c.text_color.unwrap_or(colors.neutral[0]);
        let state = window
            .use_keyed_state(
                ElementId::NamedChild(self.id.clone().into(), "state".into()),
                cx,
                |_, _| {
                    Rc::new(RefCell::new(GalleryState {
                        active: c.default_index.min(count.saturating_sub(1)),
                        panels: Vec::new(),
                        focus: Vec::new(),
                        focused: None,
                        total: 800.0,
                        vertical: false,
                        last_focus: None,
                        mouse_was_active: false,
                    }))
                },
            )
            .read(cx)
            .clone();
        let now = motion_now(cx);
        let reduced = is_reduced_motion(cx);
        let newly_focused = {
            let mut s = state.borrow_mut();
            s.active = self.index.unwrap_or(s.active).min(count.saturating_sub(1));
            if s.panels.len() != count {
                s.panels = (0..count)
                    .map(|i| PanelMotion::new(i, s.active, count, &c))
                    .collect();
                s.focus = (0..count)
                    .map(|_| cx.focus_handle().tab_index(0).tab_stop(true))
                    .collect();
            }
            let focused = s.focus.iter().position(|f| f.is_focused(window));
            s.focused = focused;
            let newly_focused = if focused != s.last_focus {
                focused
            } else {
                None
            };
            s.last_focus = focused;
            newly_focused
        };
        let controlled = self.index.is_some();
        if let Some(i) = newly_focused {
            let st = state.clone();
            let cb = self.on_change.clone();
            window.defer(cx, move |window, cx| {
                // 绘制后焦点可能已移走或列表已变化,不恢复过期的选择。
                let still_focused = st
                    .borrow()
                    .focus
                    .get(i)
                    .is_some_and(|f| f.is_focused(window));
                if still_focused {
                    select(&st, i, controlled, &cb, window, cx);
                }
            });
            window.request_animation_frame();
        }
        let vertical = c.orientation == Orientation::Vertical || state.borrow().total < 520.0;
        state.borrow_mut().vertical = vertical;
        let height = if vertical { c.height * 1.6 } else { c.height };
        let mut root = div()
            .id(self.id.clone())
            .test_support()
            .role(Role::List)
            .aria_label("Image accordion gallery")
            .relative()
            .w_full()
            .h(px(height))
            .min_w_0()
            .flex()
            .gap(px(c.gap))
            .when(vertical, |d| d.flex_col());
        if count == 0 {
            return root.child(
                div()
                    .text_color(colors.text_muted)
                    .child("暂无图片 / No images"),
            );
        }
        let total = if vertical {
            height
        } else {
            state.borrow().total
        };
        let media =
            ((total - c.gap * (count.saturating_sub(1)) as f32).max(120.0) * c.expand_ratio * 1.22)
                .max(140.0);
        for (i, item) in self.items.into_iter().enumerate() {
            let active = state.borrow().active;
            let p = {
                let mut s = state.borrow_mut();
                let p = &mut s.panels[i];
                p.update(i, active, count, &c, now, reduced);
                if !p.settled(now) {
                    window.request_animation_frame();
                }
                p.clone()
            };
            let focused = state.borrow().focused == Some(i);
            let focus = state.borrow().focus[i].clone();
            let angle = if reduced || state.borrow().total < 520.0 {
                0.0
            } else {
                p.angle.sample(now)
            };
            let spec = PaintSpec {
                angle,
                vertical,
                media,
                drift: p.drift.sample(now),
                radius: c.radius,
                dim: p.dim.sample(now),
                overlay,
            };
            let (image, mut error) = load_image(&item.image, window, cx);
            let image = image.filter(|image| {
                let valid = image.frame_count() > 0 && {
                    let size = image.size(0);
                    size.width.0 > 0 && size.height.0 > 0
                };
                error |= !valid;
                valid
            });
            let gray = p.gray.sample(now);
            let media_state = ProjectedMedia::state(
                ElementId::NamedChild(self.id.clone().into(), format!("media-{i}").into()),
                window,
                cx,
            );
            let st_hover = state.clone();
            let cb_hover = self.on_change.clone();
            let st_click = state.clone();
            let cb_click = self.on_change.clone();
            let activate = self.on_activate.clone();
            let st_down = state.clone();
            let down_focus = focus.clone();
            let st_key = state.clone();
            let cb_key = self.on_change.clone();
            let link = item.link.clone();
            let label = if item.alt.is_empty() {
                item.label.clone()
            } else {
                item.alt.clone()
            };
            let mut panel = div()
                .id(ElementId::NamedChild(
                    self.id.clone().into(),
                    format!("panel-{i}").into(),
                ))
                .test_support()
                .role(Role::ListItem)
                .aria_label(label)
                .aria_selected(i == active)
                .track_focus(&focus)
                .tab_index(0)
                .tab_stop(true)
                .relative()
                .min_w_0()
                .min_h_0()
                .flex_basis(px(0.0))
                .flex_grow(p.grow.sample(now))
                .cursor_pointer()
                .on_hover(move |hovered, window, cx| {
                    if *hovered && c.trigger == AccordionGalleryTrigger::Hover {
                        select(&st_hover, i, controlled, &cb_hover, window, cx);
                    }
                })
                .on_mouse_down(gpui_kit::MouseButton::Left, move |_, window, cx| {
                    let was_active = st_down.borrow().active == i;
                    st_down.borrow_mut().mouse_was_active = was_active;
                    window.focus(&down_focus, cx);
                })
                .on_click(move |event, window, cx| {
                    let was_active = if matches!(event, gpui_kit::ClickEvent::Mouse(_)) {
                        st_click.borrow().mouse_was_active
                    } else {
                        st_click.borrow().active == i
                    };
                    if !was_active {
                        select(&st_click, i, controlled, &cb_click, window, cx);
                    } else {
                        activate_link(i, &link, &activate, window, cx);
                    }
                })
                .on_key_down(move |event, window, cx| {
                    let next = match event.keystroke.key.as_str() {
                        "right" | "down" => Some((i + 1) % count),
                        "left" | "up" => Some((i + count - 1) % count),
                        "home" => Some(0),
                        "end" => Some(count - 1),
                        _ => None,
                    };
                    if let Some(next) = next {
                        select(&st_key, next, controlled, &cb_key, window, cx);
                        let f = st_key.borrow().focus[next].clone();
                        window.focus(&f, cx);
                        cx.stop_propagation();
                    }
                    // Enter/Space 由 GPUI 的 on_click 键盘激活统一处理,避免 keydown/keyup 双触发。
                })
                .child(
                    canvas(
                        |_, _, _| (),
                        move |rect, _, window, cx| {
                            let overlay: gpui_kit::Rgba = spec.overlay.into();
                            let params = ProjectedImageParams {
                                width: rect.size.width.as_f32(),
                                height: rect.size.height.as_f32(),
                                radius: spec.radius,
                                angle: spec.angle.to_radians(),
                                vertical: spec.vertical,
                                media: spec.media,
                                drift: spec.drift,
                                grayscale: gray,
                                dim: spec.dim,
                                overlay: [overlay.r, overlay.g, overlay.b, overlay.a],
                                scale: window.scale_factor(),
                            };
                            let painted = image.as_ref().is_some_and(|image| {
                                ProjectedMedia::paint(
                                    &media_state,
                                    rect,
                                    image.clone(),
                                    params,
                                    window,
                                    cx,
                                )
                            });
                            if !painted {
                                paint_media_fallback(
                                    rect,
                                    image.as_ref(),
                                    gray > 0.5,
                                    spec,
                                    window,
                                );
                            }
                        },
                    )
                    .absolute()
                    .size_full(),
                );
            let bar = p.bar.sample(now);
            let caption = p.text.sample(now);
            let title = item.label;
            panel = panel.child(
                canvas(
                    |_, _, _| (),
                    move |rect, _, window, cx| {
                        if focused {
                            window.paint_quad(gpui_kit::quad(
                                rect,
                                px(c.radius),
                                Hsla::transparent_black(),
                                gpui_kit::Edges::all(px(2.0)),
                                accent,
                                gpui_kit::BorderStyle::Solid,
                            ));
                        }
                        window.with_content_mask(Some(ContentMask { bounds: rect }), |window| {
                            if error {
                                paint_text(
                                    "图片加载失败".into(),
                                    rect.origin + point(px(12.0), px(14.0)),
                                    text_color,
                                    12.0,
                                    window,
                                    cx,
                                );
                            }
                            if bar > 0.0 {
                                let b = bounds(
                                    rect.origin
                                        + point(
                                            px(20.0 - 14.0 * (1.0 - bar)),
                                            px((rect.size.height.as_f32() - 46.0).max(4.0)),
                                        ),
                                    size(px(3.0), px(26.0)),
                                );
                                window.paint_quad(fill(b, accent.opacity(bar)));
                            }
                            if caption > 0.0 {
                                paint_text(
                                    title,
                                    rect.origin
                                        + point(
                                            px(35.0 - 14.0 * (1.0 - caption)),
                                            px((rect.size.height.as_f32() - 47.0).max(4.0)),
                                        ),
                                    text_color.opacity(caption),
                                    20.0,
                                    window,
                                    cx,
                                );
                            }
                        });
                    },
                )
                .absolute()
                .size_full(),
            );
            root = root.child(panel);
        }
        let st_measure = state;
        root.child(
            canvas(
                move |rect, window, _| {
                    let width = rect.size.width.as_f32();
                    if (st_measure.borrow().total - width).abs() > 0.5 {
                        st_measure.borrow_mut().total = width;
                        window.request_animation_frame();
                    }
                },
                |_, _, _, _| (),
            )
            .absolute()
            .size_full(),
        )
    }
}
fn activate_link(
    index: usize,
    link: &Option<SharedString>,
    cb: &Option<Activate>,
    window: &mut Window,
    cx: &mut App,
) {
    if let Some(link) = link {
        if let Some(cb) = cb {
            cb(
                &AccordionGalleryActivation {
                    index,
                    link: link.clone(),
                },
                window,
                cx,
            );
        } else if link.starts_with("https://") || link.starts_with("http://") {
            cx.open_url(link);
        }
    }
}
fn paint_text(
    text: SharedString,
    origin: Point<Pixels>,
    color: Hsla,
    font_size: f32,
    window: &mut Window,
    cx: &mut App,
) {
    let line = window.text_system().shape_line(
        text.clone(),
        px(font_size),
        &[TextRun {
            len: text.len(),
            font: gpui_kit::font(Typography::body_family()),
            color,
            ..Default::default()
        }],
        None,
    );
    let _ = line.paint(
        origin,
        px(font_size * 1.3),
        TextAlign::Left,
        None,
        window,
        cx,
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, Render, TestAppContext,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };
    struct Host {
        config: AccordionGalleryConfig,
        items: usize,
        changed: usize,
        activated: usize,
        width: f32,
        controlled: Option<usize>,
    }
    impl Render for Host {
        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let image = window
                .use_keyed_state("ag-test-source", cx, |_, _| {
                    Arc::new(RenderImage::new(vec![image::Frame::new(
                        image::RgbaImage::from_pixel(4, 4, image::Rgba([60, 120, 180, 255])),
                    )]))
                })
                .read(cx)
                .clone();
            let items = (0..self.items)
                .map(|i| {
                    AccordionGalleryItem::new(image.clone())
                        .label(format!("Panel {i}"))
                        .link("#")
                })
                .collect::<Vec<_>>();
            div().w(px(self.width)).child(
                AccordionGallery::new("ag-test")
                    .items(items)
                    .config(self.config.clone())
                    .when_some(self.controlled, |gallery, index| gallery.index(index))
                    .on_index_change(cx.listener(|this, i: &usize, _, cx| {
                        this.changed = *i;
                        cx.notify();
                    }))
                    .on_activate(cx.listener(|this, _: &AccordionGalleryActivation, _, cx| {
                        this.activated += 1;
                        cx.notify();
                    })),
            )
        }
    }
    #[gpui_kit::test]
    fn accordion_gallery_click_keyboard_ratio_and_empty(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: AccordionGalleryConfig {
                trigger: AccordionGalleryTrigger::Click,
                ..Default::default()
            },
            items: 5,
            changed: 2,
            activated: 0,
            width: 800.0,
            controlled: None,
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.render_frame(cx);
            let rect = window.find_by_label("Panel 0").bounds();
            let active = window.find_by_label("Panel 2").bounds();
            assert!(active.size.width > rect.size.width * 3.0);
            window.pointer_down(rect.center(), gpui_kit::MouseButton::Left, cx);
            window.pointer_up(rect.center(), gpui_kit::MouseButton::Left, cx);
            window.render_frame(cx);
            window.render_frame(cx);
            assert_eq!(view.read(cx).changed, 0);
            assert_eq!(view.read(cx).activated, 0);
            window.press("right", cx);
            window.render_frame(cx);
            assert_eq!(view.read(cx).changed, 1);
            window.press("enter", cx);
            assert_eq!(view.read(cx).activated, 1);
            window.press("space", cx);
            assert_eq!(view.read(cx).activated, 2);
            window.render_frame(cx);
            let selected = window.find_by_label("Panel 1").bounds();
            window.pointer_down(selected.center(), gpui_kit::MouseButton::Left, cx);
            window.pointer_up(selected.center(), gpui_kit::MouseButton::Left, cx);
            assert_eq!(view.read(cx).activated, 3);
            window.press("end", cx);
            window.render_frame(cx);
            assert_eq!(view.read(cx).changed, 4);
            window.press("right", cx);
            window.render_frame(cx);
            assert_eq!(view.read(cx).changed, 0);
            view.update(cx, |v, cx| {
                v.items = 1;
                v.config.orientation = Orientation::Vertical;
                cx.notify();
            });
            window.render_frame(cx);
            window.render_frame(cx);
            assert!(window.find_by_label("Panel 0").bounds().size.height > px(700.0));
            view.update(cx, |v, cx| {
                v.items = 0;
                cx.notify();
            });
            window.render_frame(cx);
            assert!(window.try_find_by_label("Panel 0").is_none());
        });
    }
    #[gpui_kit::test]
    fn accordion_gallery_hover_focus_controlled_and_resize(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(),
            items: 5,
            changed: 2,
            activated: 0,
            width: 800.0,
            controlled: None,
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.render_frame(cx);
            let panel = window.find_by_label("Panel 4").bounds();
            window.pointer_move(panel.center(), None, cx);
            window.render_frame(cx);
            assert_eq!(view.read(cx).changed, 4);
            // 先移出画廊,避免布局改变重新触发仍悬停的面板。
            window.pointer_move(point(px(900.0), px(800.0)), None, cx);
            // 单组件 Host 没有 Root 的 Tab 绑定,直接调用同一原生焦点遍历入口。
            window.focus_next(cx);
            assert!(window.focused(cx).is_some(), "面板必须注册为原生 Tab stop");
            window.render_frame(cx);
        });
        cx.run_until_parked();
        cx.update(|window, cx| {
            window.render_frame(cx);
            assert_eq!(view.read(cx).changed, 0);
            view.update(cx, |v, cx| {
                v.controlled = Some(2);
                cx.notify();
            });
            window.render_frame(cx);
            window.press("end", cx);
            window.render_frame(cx);
            window.render_frame(cx);
            assert_eq!(view.read(cx).changed, 4);
            let active = window.find_by_label("Panel 2").bounds();
            let last = window.find_by_label("Panel 4").bounds();
            assert!(active.size.width > last.size.width * 3.0);
            view.update(cx, |v, cx| {
                v.width = 480.0;
                cx.notify();
            });
            for _ in 0..3 {
                window.render_frame(cx);
            }
            let first = window.find_by_label("Panel 0").bounds();
            let second = window.find_by_label("Panel 1").bounds();
            assert!(second.top() > first.bottom());
            assert!(window.find("ag-test").bounds().size.height > px(700.0));
            install_arc_theme(ThemeMode::Dark, Accent::Neutral, cx);
            window.render_frame(cx);
        });
    }
    #[test]
    fn accordion_gallery_ratio_and_invalid_config() {
        let c = AccordionGalleryConfig::default();
        let g = c.expanded_grow(5);
        assert!((g / (g + 4.0) - 0.52).abs() < 1e-6);
        assert_eq!(c.expanded_grow(1), 1.0);
        let c = AccordionGalleryConfig {
            height: f32::NAN,
            expand_ratio: 2.0,
            duration: -1.0,
            ..c
        }
        .sanitized();
        assert_eq!(c.height, 460.0);
        assert_eq!(c.expand_ratio, 0.9);
        assert_eq!(c.duration, 0.0);
    }
    #[test]
    fn accordion_gallery_real_perspective_and_rounding() {
        let left = project(0.0, 0.0, 200.0, 460.0, 8.0, false);
        let right = project(200.0, 0.0, 200.0, 460.0, 8.0, false);
        assert!((left.1 - right.1).abs() > 1.0);
        let top = project(0.0, 0.0, 200.0, 460.0, 8.0, true);
        let bottom = project(0.0, 460.0, 200.0, 460.0, 8.0, true);
        assert!((top.0 - bottom.0).abs() > 1.0);
    }
    #[test]
    fn accordion_gallery_switch_preserves_actual_motion() {
        let c = AccordionGalleryConfig::default();
        let mut p = PanelMotion::new(0, 2, 5, &c);
        p.update(0, 0, 5, &c, 0.0, false);
        let grow = p.grow.sample(0.2);
        p.update(0, 1, 5, &c, 0.2, false);
        assert_eq!(p.grow.sample(0.2), grow);
        p.update(0, 1, 5, &c, 0.3, true);
        assert_eq!(p.angle.sample(0.3), 8.0);
    }
}