Skip to main content

arc_ui/overlay/
folder_float.rs

1//! FolderFloat:依据用户提供的 React Bits 参考实现原生重写。
2//! 上游 © David Haz,MIT + Commons Clause;参见 THIRD_PARTY_NOTICES.md。
3//! 透视面板与文字按顶点投影;碰撞复用 arc-physics3d 的平面约束。
4
5use std::{cell::RefCell, rc::Rc, sync::Arc};
6
7use arc_motion::{SpringSolver, is_reduced_motion, motion_now};
8use arc_physics3d::{PhysicsWorld, Quat, RigidBody, Shape, Vec3};
9use arc_tokens::{ActiveArcTheme as _, SpringSpec};
10use gpui_kit::{
11    App, Bounds, ClickEvent, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
12    MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role,
13    SharedString, Styled, TestSupportExt as _, Window, base::Button as BaseButton, canvas, div,
14    point, prelude::*, px,
15};
16
17use crate::text::glyph_outline::{Outline, with_face};
18
19const PILL_H: f32 = 34.0;
20const GAP: f32 = 12.0;
21const ROW: f32 = 52.0;
22const DRAG_MIN: f32 = 4.0;
23
24type OpenHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
25type SelectHandler = Rc<dyn Fn(&FolderFloatSelection, &mut Window, &mut App)>;
26type SharedState = Rc<RefCell<State>>;
27
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29pub enum FolderFloatTrigger {
30    #[default]
31    Hover,
32    Click,
33}
34
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct FolderFloatItem {
37    pub label: SharedString,
38    pub value: SharedString,
39}
40
41impl FolderFloatItem {
42    pub fn new(label: impl Into<SharedString>) -> Self {
43        let label = label.into();
44        Self {
45            value: label.clone(),
46            label,
47        }
48    }
49
50    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
51        self.value = value.into();
52        self
53    }
54}
55
56impl From<&str> for FolderFloatItem {
57    fn from(value: &str) -> Self {
58        Self::new(value)
59    }
60}
61
62#[derive(Clone, Debug, PartialEq, Eq)]
63pub struct FolderFloatSelection {
64    pub value: SharedString,
65    pub index: usize,
66}
67
68/// 几何与时序采用参考组件默认值;颜色默认跟随 Arc 主题,也可逐项覆盖。
69/// 时间单位统一为秒,而不是上游的毫秒。
70#[derive(Clone, Debug, PartialEq)]
71pub struct FolderFloatConfig {
72    pub width: f32,
73    pub height: f32,
74    pub radius: f32,
75    pub spread: f32,
76    pub lift: f32,
77    pub tilt: f32,
78    pub flap_angle: f32,
79    pub rest_angle: f32,
80    pub open_duration: f32,
81    pub stagger: f32,
82    pub bounce: f32,
83    pub physics: bool,
84    pub drift: f32,
85    pub trigger: FolderFloatTrigger,
86    pub close_on_select: bool,
87    pub folder_color: Option<Hsla>,
88    pub front_color: Option<Hsla>,
89    pub paper_color: Option<Hsla>,
90    pub item_color: Option<Hsla>,
91    pub item_text_color: Option<Hsla>,
92    pub label_color: Option<Hsla>,
93}
94
95impl Default for FolderFloatConfig {
96    fn default() -> Self {
97        Self {
98            width: 200.0,
99            height: 148.0,
100            radius: 14.0,
101            spread: 180.0,
102            lift: 26.0,
103            tilt: 8.0,
104            flap_angle: 34.0,
105            rest_angle: 16.0,
106            open_duration: 0.52,
107            stagger: 0.045,
108            bounce: 0.3,
109            physics: true,
110            drift: 0.5,
111            trigger: FolderFloatTrigger::Hover,
112            close_on_select: true,
113            folder_color: None,
114            front_color: None,
115            paper_color: None,
116            item_color: None,
117            item_text_color: None,
118            label_color: None,
119        }
120    }
121}
122
123impl FolderFloatConfig {
124    fn sanitized(&self) -> Self {
125        fn safe(v: f32, default: f32, min: f32, max: f32) -> f32 {
126            if v.is_finite() {
127                v.clamp(min, max)
128            } else {
129                default
130            }
131        }
132        Self {
133            width: safe(self.width, 200.0, 100.0, 480.0),
134            height: safe(self.height, 148.0, 80.0, 320.0),
135            radius: safe(self.radius, 14.0, 0.0, 40.0),
136            spread: safe(self.spread, 180.0, 90.0, 600.0),
137            lift: safe(self.lift, 26.0, 0.0, 160.0),
138            tilt: safe(self.tilt, 8.0, 0.0, 25.0),
139            flap_angle: safe(self.flap_angle, 34.0, 0.0, 75.0),
140            rest_angle: safe(self.rest_angle, 16.0, 0.0, 60.0),
141            open_duration: safe(self.open_duration, 0.52, 0.1, 3.0),
142            stagger: safe(self.stagger, 0.045, 0.0, 0.4),
143            bounce: safe(self.bounce, 0.3, 0.0, 0.8),
144            drift: safe(self.drift, 0.5, 0.0, 2.0),
145            ..self.clone()
146        }
147    }
148}
149
150#[derive(Clone, Default)]
151struct TextGeometry {
152    contours: Vec<Vec<(f32, f32)>>,
153    width: f32,
154}
155
156fn text_geometry(text: &str, font_size: f32) -> TextGeometry {
157    // 优先选择同时有中西文字形的字体,避免中文标签用 ASCII 字符数估宽。
158    let family = if cfg!(target_os = "windows") {
159        "Microsoft YaHei"
160    } else {
161        "Noto Sans CJK SC"
162    };
163    with_face(family, 500, |face| {
164        let scale = font_size / face.units_per_em() as f32;
165        let mut geometry = TextGeometry::default();
166        for ch in text.chars().take(120) {
167            let glyph = face.glyph_index(ch).unwrap_or(ttf_parser::GlyphId(0));
168            let outline = Outline::glyph(face, glyph);
169            for contour in outline.contours {
170                geometry.contours.push(
171                    contour
172                        .points
173                        .iter()
174                        .map(|p| (geometry.width + p.x * scale, p.y * scale))
175                        .collect(),
176                );
177            }
178            geometry.width += face
179                .glyph_hor_advance(glyph)
180                .unwrap_or(face.units_per_em() / 2) as f32
181                * scale;
182        }
183        Ok(geometry)
184    })
185    .unwrap_or_else(|_| TextGeometry {
186        width: text.chars().count() as f32 * font_size * 0.6,
187        ..Default::default()
188    })
189}
190
191#[derive(Clone, Copy, Debug, Default)]
192struct Pose {
193    x: f32,
194    y: f32,
195    angle: f32,
196    alpha: f32,
197}
198
199#[derive(Clone, Copy, Debug)]
200struct Slot {
201    pose: Pose,
202    width: f32,
203}
204
205fn jitter(i: usize) -> f32 {
206    ((i as f32 * 127.1 + 311.7).sin() * 43_758.547).fract()
207}
208
209fn layout(widths: &[f32], config: &FolderFloatConfig) -> (Vec<Slot>, f32) {
210    let mut rows: Vec<Vec<(usize, f32)>> = vec![Vec::new()];
211    let mut used = 0.0;
212    for (i, width) in widths.iter().enumerate() {
213        let width = width.clamp(40.0, config.spread * 2.0);
214        let extra = if used > 0.0 { GAP } else { 0.0 };
215        if used + extra + width > config.spread * 2.0 && used > 0.0 {
216            rows.push(Vec::new());
217            used = 0.0;
218        }
219        if used > 0.0 {
220            used += GAP;
221        }
222        rows.last_mut().unwrap().push((i, width));
223        used += width;
224    }
225    let mut slots = vec![
226        Slot {
227            pose: Pose::default(),
228            width: 40.0
229        };
230        widths.len()
231    ];
232    for (row, entries) in rows.iter().enumerate() {
233        let total = entries.iter().map(|(_, w)| w).sum::<f32>()
234            + GAP * entries.len().saturating_sub(1) as f32;
235        let mut x = -total * 0.5;
236        for &(i, width) in entries {
237            slots[i] = Slot {
238                width,
239                pose: Pose {
240                    x: x + width * 0.5,
241                    y: -config.lift - PILL_H * 0.5 - row as f32 * ROW,
242                    angle: jitter(i) * config.tilt,
243                    alpha: 1.0,
244                },
245            };
246            x += width + GAP;
247        }
248    }
249    (slots, config.lift + rows.len() as f32 * ROW + 64.0)
250}
251
252struct Drag {
253    index: usize,
254    start: (f32, f32),
255    offset: (f32, f32),
256    last: (f32, f32),
257    at: f64,
258    velocity: (f32, f32),
259    moved: bool,
260}
261
262struct State {
263    open: bool,
264    changed: f64,
265    last: f64,
266    poses: Vec<Pose>,
267    from: Vec<Pose>,
268    flap: f32,
269    from_flap: f32,
270    world: Option<PhysicsWorld>,
271    physics_started: f64,
272    drag: Option<Drag>,
273    swallow_click: bool,
274    hovered: bool,
275    bounds: Option<Bounds<Pixels>>,
276    visible: bool,
277    focus: FocusHandle,
278    geometry_key: Vec<SharedString>,
279    geometry: Option<Arc<Vec<TextGeometry>>>,
280    generation: u64,
281    config: FolderFloatConfig,
282}
283
284impl State {
285    fn new(open: bool, now: f64, config: FolderFloatConfig, cx: &mut App) -> Self {
286        Self {
287            open,
288            changed: now,
289            last: now,
290            poses: Vec::new(),
291            from: Vec::new(),
292            flap: 0.0,
293            from_flap: 0.0,
294            world: None,
295            physics_started: now,
296            drag: None,
297            swallow_click: false,
298            hovered: false,
299            bounds: None,
300            visible: true,
301            focus: cx.focus_handle(),
302            geometry_key: Vec::new(),
303            geometry: None,
304            generation: 0,
305            config,
306        }
307    }
308
309    fn set_open(&mut self, open: bool, now: f64) -> bool {
310        if self.open == open {
311            return false;
312        }
313        self.open = open;
314        self.changed = now;
315        self.from = self.poses.clone();
316        self.from_flap = self.flap;
317        self.world = None;
318        self.drag = None;
319        true
320    }
321
322    fn tick(&mut self, now: f64, slots: &[Slot], zone_h: f32, reduced: bool) -> bool {
323        let n = slots.len();
324        if self.poses.len() != n {
325            self.poses = vec![
326                Pose {
327                    y: self.config.height * 0.45,
328                    ..Default::default()
329                };
330                n
331            ];
332            self.from = self.poses.clone();
333            self.world = None;
334        }
335        let dt = (now - self.last).clamp(0.0, 0.032) as f32;
336        self.last = now;
337        let duration = self.config.open_duration * if self.open { 1.0 } else { 0.6 };
338        let elapsed = (now - self.changed).max(0.0) as f32;
339        let span = duration + n.saturating_sub(1) as f32 * self.config.stagger;
340        let flap_progress = if reduced {
341            1.0
342        } else {
343            (elapsed / duration).clamp(0.0, 1.0)
344        };
345        let target_flap = if self.open { 1.0 } else { 0.0 };
346        self.flap =
347            self.from_flap + (target_flap - self.from_flap) * (1.0 - (1.0 - flap_progress).powi(3));
348        if reduced || !self.config.physics || !self.open {
349            self.world = None;
350        }
351        if let Some(world) = &mut self.world {
352            let t = (now - self.physics_started) as f32;
353            for (i, body) in world.bodies.iter_mut().take(n).enumerate() {
354                let phase = i as f32 * 2.4;
355                let force = self.config.drift * 65.0 * (t / 2.0).min(1.0);
356                body.accelerate(
357                    Vec3::new(
358                        (t * 0.9 + phase).sin() * force,
359                        (t * 1.3 + phase * 1.7).cos() * force,
360                        0.0,
361                    ),
362                    dt,
363                );
364            }
365            world.step(dt);
366            for (i, slot) in slots.iter().enumerate() {
367                let body = &mut world.bodies[i];
368                let (x, y) = constrain(
369                    body.position.x,
370                    body.position.y,
371                    slot.width,
372                    zone_h,
373                    &self.config,
374                );
375                body.position = Vec3::new(x, y, 0.0);
376                self.poses[i].x = x;
377                self.poses[i].y = y;
378            }
379            return self.config.drift > 0.0
380                || self.drag.is_some()
381                || world.bodies.iter().take(n).any(|b| b.speed() > 0.1);
382        }
383        for (i, slot) in slots.iter().enumerate() {
384            let rank = if self.open { i } else { n - 1 - i };
385            let progress = if reduced {
386                1.0
387            } else {
388                ((elapsed - rank as f32 * self.config.stagger) / duration).clamp(0.0, 1.0)
389            };
390            let eased = if self.open && !reduced && progress < 1.0 {
391                SpringSolver::new(
392                    SpringSpec::visual(duration, self.config.bounce),
393                    0.0,
394                    1.0,
395                    0.0,
396                )
397                .sample((progress * duration) as f64)
398                .value
399            } else {
400                1.0 - (1.0 - progress).powi(3)
401            };
402            let target = if self.open {
403                slot.pose
404            } else {
405                Pose {
406                    y: self.config.height * 0.45,
407                    ..Default::default()
408                }
409            };
410            let start = self.from[i];
411            self.poses[i] = Pose {
412                x: start.x + (target.x - start.x) * eased,
413                y: start.y + (target.y - start.y) * eased,
414                angle: start.angle + (target.angle - start.angle) * eased,
415                alpha: start.alpha + (target.alpha - start.alpha) * progress,
416            };
417        }
418        if self.open && self.config.physics && !reduced && elapsed >= span + 0.08 && n > 0 {
419            self.world = Some(make_world(&self.poses, slots, zone_h, &self.config));
420            self.physics_started = now;
421            return true;
422        }
423        !reduced && elapsed < span + 0.08
424    }
425}
426
427fn constrain(x: f32, y: f32, width: f32, zone_h: f32, config: &FolderFloatConfig) -> (f32, f32) {
428    let half = (config.spread + 24.0 - width * 0.5).max(0.0);
429    (
430        x.clamp(-half, half),
431        y.clamp(-zone_h + PILL_H * 0.5 + 8.0, -PILL_H * 0.5 - 8.0),
432    )
433}
434
435fn make_world(
436    poses: &[Pose],
437    slots: &[Slot],
438    zone_h: f32,
439    config: &FolderFloatConfig,
440) -> PhysicsWorld {
441    let mut world = PhysicsWorld::new();
442    world.gravity = Vec3::ZERO;
443    world.allow_sleep = false;
444    world.penetration_slop = 0.1;
445    for (pose, slot) in poses.iter().zip(slots) {
446        let mut body = RigidBody::dynamic(
447            Shape::cuboid(Vec3::new(slot.width * 0.5, PILL_H * 0.5, 0.5)),
448            1.0,
449        )
450        .at(Vec3::new(pose.x, pose.y, 0.0))
451        .with_material(0.0, 0.55)
452        .planar(0.0);
453        body.rotation = Quat::from_axis_angle(Vec3::Z, pose.angle.to_radians());
454        body.linear_damping = 5.0;
455        world.add_body(body);
456    }
457    let half_w = config.spread + 24.0;
458    for (x, y, w, h) in [
459        (-half_w - 10.0, -zone_h * 0.5, 10.0, zone_h),
460        (half_w + 10.0, -zone_h * 0.5, 10.0, zone_h),
461        (0.0, -zone_h - 10.0, half_w + 20.0, 10.0),
462        (0.0, 2.0, half_w + 20.0, 10.0),
463    ] {
464        world.add_body(
465            RigidBody::fixed(Shape::cuboid(Vec3::new(w, h, 1.0)))
466                .at(Vec3::new(x, y, 0.0))
467                .with_material(0.0, 0.55)
468                .planar(0.0),
469        );
470    }
471    world
472}
473
474#[derive(IntoElement)]
475pub struct FolderFloat {
476    id: ElementId,
477    items: Vec<FolderFloatItem>,
478    label: SharedString,
479    sublabel: SharedString,
480    config: FolderFloatConfig,
481    default_open: bool,
482    open: Option<bool>,
483    on_select: Option<SelectHandler>,
484    on_open_change: Option<OpenHandler>,
485}
486
487impl FolderFloat {
488    pub fn new(id: impl Into<ElementId>) -> Self {
489        Self {
490            id: id.into(),
491            items: Vec::new(),
492            label: "Design feedback".into(),
493            sublabel: "".into(),
494            config: FolderFloatConfig::default(),
495            default_open: false,
496            open: None,
497            on_select: None,
498            on_open_change: None,
499        }
500    }
501    pub fn items(mut self, items: impl IntoIterator<Item = impl Into<FolderFloatItem>>) -> Self {
502        self.items = items.into_iter().take(48).map(Into::into).collect();
503        self
504    }
505    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
506        self.label = label.into();
507        self
508    }
509    pub fn sublabel(mut self, label: impl Into<SharedString>) -> Self {
510        self.sublabel = label.into();
511        self
512    }
513    pub fn config(mut self, config: FolderFloatConfig) -> Self {
514        self.config = config;
515        self
516    }
517    pub fn default_open(mut self, open: bool) -> Self {
518        self.default_open = open;
519        self
520    }
521    pub fn open(mut self, open: bool) -> Self {
522        self.open = Some(open);
523        self
524    }
525    pub fn on_select(
526        mut self,
527        handler: impl Fn(&FolderFloatSelection, &mut Window, &mut App) + 'static,
528    ) -> Self {
529        self.on_select = Some(Rc::new(handler));
530        self
531    }
532    pub fn on_open_change(
533        mut self,
534        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
535    ) -> Self {
536        self.on_open_change = Some(Rc::new(handler));
537        self
538    }
539}
540
541fn change_open(
542    state: &SharedState,
543    open: bool,
544    controlled: bool,
545    callback: &Option<OpenHandler>,
546    window: &mut Window,
547    cx: &mut App,
548) {
549    let changed = if controlled {
550        state.borrow().open != open
551    } else {
552        state.borrow_mut().set_open(open, motion_now(cx))
553    };
554    if changed {
555        if let Some(callback) = callback {
556            callback(&open, window, cx);
557        }
558        window.refresh();
559    }
560}
561
562impl RenderOnce for FolderFloat {
563    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
564        let config = self.config.sanitized();
565        let reduced = is_reduced_motion(cx);
566        let now = motion_now(cx);
567        let colors = cx.arc_theme().colors;
568        let initial = config.clone();
569        let entity = window.use_keyed_state(
570            ElementId::NamedChild(self.id.clone().into(), "folder-state".into()),
571            cx,
572            |_, cx| {
573                Rc::new(RefCell::new(State::new(
574                    self.open.unwrap_or(self.default_open),
575                    now,
576                    initial,
577                    cx,
578                )))
579            },
580        );
581        let state = entity.read(cx).clone();
582        let mut key: Vec<SharedString> = self.items.iter().map(|i| i.label.clone()).collect();
583        key.extend([self.label.clone(), self.sublabel.clone()]);
584        if state.borrow().geometry_key != key {
585            let mut s = state.borrow_mut();
586            s.geometry_key = key.clone();
587            s.geometry = None;
588            s.generation += 1;
589            s.world = None;
590            s.drag = None;
591            let generation = s.generation;
592            drop(s);
593            let target = state.clone();
594            let n = self.items.len();
595            let task = cx.background_executor().spawn(async move {
596                Arc::new(
597                    key.iter()
598                        .enumerate()
599                        .map(|(i, text)| text_geometry(text, if i == n { 15.0 } else { 13.0 }))
600                        .collect::<Vec<_>>(),
601                )
602            });
603            window
604                .spawn(cx, async move |cx| {
605                    let geometry = task.await;
606                    let _ = cx.update(|window, _| {
607                        let mut s = target.borrow_mut();
608                        if s.generation == generation {
609                            s.geometry = Some(geometry);
610                            s.world = None;
611                            s.drag = None;
612                            s.changed = s.last;
613                            s.from = s.poses.clone();
614                            window.refresh();
615                        }
616                    });
617                })
618                .detach();
619        }
620        let geometry = state.borrow().geometry.clone();
621        let widths: Vec<f32> = self
622            .items
623            .iter()
624            .enumerate()
625            .map(|(i, item)| {
626                geometry
627                    .as_ref()
628                    .map_or(item.label.chars().count() as f32 * 7.0, |g| g[i].width)
629                    + 28.0
630            })
631            .collect();
632        let (slots, zone_h) = layout(&widths, &config);
633        let total_w = (config.spread * 2.0 + 64.0).max(config.width + 48.0);
634        let total_h = zone_h + config.height + 24.0;
635        let (poses, flap, open, focus, visible) = {
636            let mut s = state.borrow_mut();
637            if s.config != config {
638                s.from = s.poses.clone();
639                s.from_flap = s.flap;
640                s.changed = now;
641                s.world = None;
642                s.drag = None;
643                s.config = config.clone();
644            }
645            if let Some(open) = self.open {
646                s.set_open(open, now);
647            }
648            let active = s.tick(now, &slots, zone_h, reduced);
649            if active && s.visible {
650                window.request_animation_frame();
651            }
652            (s.poses.clone(), s.flap, s.open, s.focus.clone(), s.visible)
653        };
654        let controlled = self.open.is_some();
655        let trigger_state = state.clone();
656        let trigger_callback = self.on_open_change.clone();
657        let trigger = config.trigger;
658        let trigger_btn = BaseButton::new(ElementId::NamedChild(
659            self.id.clone().into(),
660            "trigger".into(),
661        ))
662        .accessibility_label(self.label.clone())
663        .on_click(move |_, window, cx| {
664            let next = !trigger_state.borrow().open;
665            change_open(
666                &trigger_state,
667                next,
668                controlled,
669                &trigger_callback,
670                window,
671                cx,
672            );
673        })
674        .absolute()
675        .left(px((total_w - config.width) * 0.5))
676        .top(px(zone_h))
677        .w(px(config.width))
678        .h(px(config.height))
679        .cursor_pointer();
680        let mut buttons = Vec::new();
681        for (i, slot) in slots.iter().enumerate() {
682            if !open {
683                continue;
684            }
685            let pose = poses[i];
686            let item = self.items[i].clone();
687            let click_state = state.clone();
688            let select = self.on_select.clone();
689            let callback = self.on_open_change.clone();
690            let close_on_select = config.close_on_select;
691            let down_state = state.clone();
692            let can_drag = config.physics && !reduced;
693            buttons.push(
694                BaseButton::new(ElementId::NamedChild(
695                    self.id.clone().into(),
696                    format!("item-{i}").into(),
697                ))
698                .accessibility_label(item.label.clone())
699                .on_click(move |event: &ClickEvent, window, cx| {
700                    // 鼠标点击由窗口级释放处理;键盘与触摸走按钮行为,避免重复回调。
701                    if matches!(event, ClickEvent::Mouse(_)) && click_state.borrow().swallow_click {
702                        return;
703                    }
704                    if !click_state.borrow().open {
705                        return;
706                    }
707                    if let Some(select) = &select {
708                        select(
709                            &FolderFloatSelection {
710                                value: item.value.clone(),
711                                index: i,
712                            },
713                            window,
714                            cx,
715                        );
716                    }
717                    if close_on_select {
718                        change_open(&click_state, false, controlled, &callback, window, cx);
719                    }
720                })
721                .absolute()
722                .left(px(total_w * 0.5 + pose.x - slot.width * 0.5))
723                .top(px(zone_h + pose.y - PILL_H * 0.5))
724                .w(px(slot.width))
725                .h(px(PILL_H))
726                .cursor_pointer()
727                .on_mouse_down(MouseButton::Left, move |event, window, cx| {
728                    let mut s = down_state.borrow_mut();
729                    s.swallow_click = false;
730                    if !can_drag || s.world.is_none() {
731                        return;
732                    }
733                    let p = (f32::from(event.position.x), f32::from(event.position.y));
734                    let Some(bounds) = s.bounds else {
735                        return;
736                    };
737                    let local = (
738                        p.0 - f32::from(bounds.origin.x) - total_w * 0.5,
739                        p.1 - f32::from(bounds.origin.y) - zone_h,
740                    );
741                    s.drag = Some(Drag {
742                        index: i,
743                        start: p,
744                        offset: (local.0 - s.poses[i].x, local.1 - s.poses[i].y),
745                        last: (s.poses[i].x, s.poses[i].y),
746                        at: motion_now(cx),
747                        velocity: (0.0, 0.0),
748                        moved: false,
749                    });
750                    window.refresh();
751                }),
752            );
753        }
754        let hover_state = state.clone();
755        let hover_callback = self.on_open_change.clone();
756        let key_state = state.clone();
757        let key_callback = self.on_open_change.clone();
758        let paint_state = state.clone();
759        let event_items = self.items.clone();
760        let event_select = self.on_select.clone();
761        let event_callback = self.on_open_change.clone();
762        let event_slots = slots.clone();
763        let event_config = config.clone();
764        let bounds_state = state.clone();
765        let palette = Palette {
766            folder: config.folder_color.unwrap_or(colors.border_strong),
767            front: config.front_color.unwrap_or(colors.text_secondary),
768            paper: config.paper_color.unwrap_or(colors.surface_raised),
769            item: config.item_color.unwrap_or(colors.foreground),
770            item_text: config.item_text_color.unwrap_or(colors.background),
771            label: config.label_color.unwrap_or(colors.background),
772        };
773        div()
774            .id(self.id)
775            .test_support()
776            .role(Role::Group)
777            .aria_label(self.label)
778            .track_focus(&focus)
779            .relative()
780            .flex_none()
781            .w(px(total_w))
782            .h(px(total_h))
783            .on_hover(move |hovered, window, cx| {
784                hover_state.borrow_mut().hovered = *hovered;
785                if trigger == FolderFloatTrigger::Hover && hover_state.borrow().drag.is_none() {
786                    change_open(
787                        &hover_state,
788                        *hovered,
789                        controlled,
790                        &hover_callback,
791                        window,
792                        cx,
793                    );
794                }
795            })
796            .on_key_down(move |event: &KeyDownEvent, window, cx| {
797                if event.keystroke.key == "escape" {
798                    change_open(&key_state, false, controlled, &key_callback, window, cx);
799                    key_state.borrow_mut().drag = None;
800                    window.focus(&focus, cx);
801                    cx.stop_propagation();
802                }
803            })
804            .child(
805                canvas(
806                    move |bounds, window, _| {
807                        let mut s = bounds_state.borrow_mut();
808                        s.bounds = Some(bounds);
809                        s.visible = !bounds.intersect(&window.content_mask().bounds).is_empty();
810                    },
811                    move |bounds, _, window, _| {
812                        paint_folder(
813                            bounds,
814                            zone_h,
815                            &config,
816                            flap,
817                            &poses,
818                            &slots,
819                            geometry.as_deref(),
820                            palette,
821                            window,
822                        );
823                        let move_state = paint_state.clone();
824                        let move_slots = event_slots.clone();
825                        let move_config = event_config.clone();
826                        window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
827                            if !phase.bubble() {
828                                return;
829                            }
830                            let mut s = move_state.borrow_mut();
831                            let Some(mut drag) = s.drag.take() else {
832                                return;
833                            };
834                            if event.pressed_button != Some(MouseButton::Left) {
835                                if let Some(world) = &mut s.world {
836                                    world.bodies[drag.index].inv_mass = 1.0;
837                                }
838                                s.swallow_click = true;
839                                window.refresh();
840                                return;
841                            }
842                            let pointer =
843                                (f32::from(event.position.x), f32::from(event.position.y));
844                            drag.moved |= (pointer.0 - drag.start.0)
845                                .hypot(pointer.1 - drag.start.1)
846                                >= DRAG_MIN;
847                            if drag.moved {
848                                let x = pointer.0
849                                    - f32::from(bounds.origin.x)
850                                    - total_w * 0.5
851                                    - drag.offset.0;
852                                let y =
853                                    pointer.1 - f32::from(bounds.origin.y) - zone_h - drag.offset.1;
854                                let (x, y) = constrain(
855                                    x,
856                                    y,
857                                    move_slots[drag.index].width,
858                                    zone_h,
859                                    &move_config,
860                                );
861                                let now = motion_now(cx);
862                                let dt = (now - drag.at).max(1.0 / 240.0) as f32;
863                                drag.velocity = (
864                                    ((x - drag.last.0) / dt).clamp(-1200.0, 1200.0),
865                                    ((y - drag.last.1) / dt).clamp(-1200.0, 1200.0),
866                                );
867                                drag.last = (x, y);
868                                drag.at = now;
869                                s.poses[drag.index].x = x;
870                                s.poses[drag.index].y = y;
871                                if let Some(world) = &mut s.world {
872                                    let body = &mut world.bodies[drag.index];
873                                    body.inv_mass = 0.0;
874                                    body.position = Vec3::new(x, y, 0.0);
875                                    body.linear_velocity = Vec3::ZERO;
876                                }
877                                s.swallow_click = true;
878                                window.refresh();
879                                cx.stop_propagation();
880                            }
881                            s.drag = Some(drag);
882                        });
883                        let up_state = paint_state.clone();
884                        let callback = event_callback.clone();
885                        let select = event_select.clone();
886                        let items = event_items.clone();
887                        let close_on_select = event_config.close_on_select;
888                        let trigger = event_config.trigger;
889                        let event_slots = event_slots.clone();
890                        window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
891                            if !phase.capture() || event.button != MouseButton::Left {
892                                return;
893                            }
894                            let mut s = up_state.borrow_mut();
895                            let Some(drag) = s.drag.take() else {
896                                return;
897                            };
898                            let stale = motion_now(cx) - drag.at > 0.12;
899                            if let Some(world) = &mut s.world {
900                                let body = &mut world.bodies[drag.index];
901                                body.inv_mass = 1.0;
902                                body.linear_velocity = if stale {
903                                    Vec3::ZERO
904                                } else {
905                                    Vec3::new(drag.velocity.0, drag.velocity.1, 0.0)
906                                };
907                            }
908                            let hovered = s.hovered;
909                            s.swallow_click = true;
910                            drop(s);
911                            let released_inside = {
912                                let pose = up_state.borrow().poses[drag.index];
913                                let x =
914                                    f32::from(event.position.x - bounds.origin.x) - total_w * 0.5;
915                                let y = f32::from(event.position.y - bounds.origin.y) - zone_h;
916                                (x - pose.x).abs() <= event_slots[drag.index].width * 0.5
917                                    && (y - pose.y).abs() <= PILL_H * 0.5
918                            };
919                            if !drag.moved && released_inside {
920                                if let Some(select) = &select {
921                                    select(
922                                        &FolderFloatSelection {
923                                            value: items[drag.index].value.clone(),
924                                            index: drag.index,
925                                        },
926                                        window,
927                                        cx,
928                                    );
929                                }
930                                if close_on_select {
931                                    change_open(
932                                        &up_state, false, controlled, &callback, window, cx,
933                                    );
934                                }
935                            } else if !hovered && trigger == FolderFloatTrigger::Hover {
936                                change_open(&up_state, false, controlled, &callback, window, cx);
937                            }
938                            window.refresh();
939                        });
940                        let _ = visible;
941                    },
942                )
943                .absolute()
944                .inset_0(),
945            )
946            .child(trigger_btn)
947            .children(buttons)
948    }
949}
950
951#[derive(Clone, Copy)]
952struct Palette {
953    folder: Hsla,
954    front: Hsla,
955    paper: Hsla,
956    item: Hsla,
957    item_text: Hsla,
958    label: Hsla,
959}
960
961fn alpha(mut color: Hsla, opacity: f32) -> Hsla {
962    color.a *= opacity.clamp(0.0, 1.0);
963    color
964}
965
966fn rounded_points(w: f32, h: f32, radius: f32) -> Vec<(f32, f32)> {
967    let r = radius.min(w * 0.5).min(h * 0.5);
968    let mut points = Vec::with_capacity(36);
969    for (cx, cy, start) in [
970        (w - r, r, -90.0_f32),
971        (w - r, h - r, 0.0),
972        (r, h - r, 90.0),
973        (r, r, 180.0),
974    ] {
975        for step in 0..=8 {
976            let a = (start + step as f32 * 90.0 / 8.0).to_radians();
977            points.push((cx + a.cos() * r, cy + a.sin() * r));
978        }
979    }
980    points
981}
982
983fn paint_contours(
984    contours: impl IntoIterator<Item = impl AsRef<[(f32, f32)]>>,
985    project: impl Fn(f32, f32) -> (f32, f32),
986    color: Hsla,
987    window: &mut Window,
988) {
989    let mut path = PathBuilder::fill();
990    for contour in contours {
991        let points = contour.as_ref();
992        if points.len() < 3 {
993            continue;
994        }
995        for (i, &(x, y)) in points.iter().enumerate() {
996            let (x, y) = project(x, y);
997            if i == 0 {
998                path.move_to(point(px(x), px(y)));
999            } else {
1000                path.line_to(point(px(x), px(y)));
1001            }
1002        }
1003        path.close();
1004    }
1005    if let Ok(path) = path.build() {
1006        window.paint_path(path, color);
1007    }
1008}
1009
1010#[allow(clippy::too_many_arguments)]
1011fn paint_folder(
1012    bounds: Bounds<Pixels>,
1013    zone_h: f32,
1014    config: &FolderFloatConfig,
1015    flap: f32,
1016    poses: &[Pose],
1017    slots: &[Slot],
1018    geometry: Option<&Vec<TextGeometry>>,
1019    palette: Palette,
1020    window: &mut Window,
1021) {
1022    let cx = f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
1023    let top = f32::from(bounds.origin.y) + zone_h;
1024    let w = config.width;
1025    let h = config.height;
1026    let left = cx - w * 0.5;
1027    let back = |x: f32, y: f32| {
1028        let dy = y - h;
1029        let angle = 8.0_f32.to_radians();
1030        let k = 600.0 / (600.0 + dy * angle.sin());
1031        (cx + (x - w * 0.5) * k, top + h + dy * angle.cos() * k)
1032    };
1033    paint_contours(
1034        [rounded_points(w * 0.4, 24.0, config.radius * 0.6)],
1035        |x, y| (left + x + 10.0, top + y - 14.0),
1036        palette.folder,
1037        window,
1038    );
1039    paint_contours(
1040        [rounded_points(w, h, config.radius)],
1041        back,
1042        palette.folder,
1043        window,
1044    );
1045    for i in 0..3 {
1046        let inset = 10.0 + i as f32 * 5.0;
1047        paint_contours(
1048            [rounded_points(w - inset * 2.0, h * 0.8, 6.0)],
1049            |x, y| {
1050                (
1051                    left + inset + x,
1052                    top + h * 0.12 + y - flap * (10.0 + i as f32 * 5.0),
1053                )
1054            },
1055            alpha(palette.paper, 0.65 + i as f32 * 0.12),
1056            window,
1057        );
1058    }
1059    for (i, (pose, slot)) in poses.iter().zip(slots).enumerate() {
1060        if pose.alpha <= 0.005 {
1061            continue;
1062        }
1063        let theta = pose.angle.to_radians();
1064        let (sin, cos) = theta.sin_cos();
1065        let project = |x: f32, y: f32| {
1066            (
1067                cx + pose.x + x * cos - y * sin,
1068                top + pose.y + x * sin + y * cos,
1069            )
1070        };
1071        paint_contours(
1072            [rounded_points(slot.width, PILL_H, PILL_H * 0.5)],
1073            |x, y| project(x - slot.width * 0.5, y - PILL_H * 0.5),
1074            alpha(palette.item, pose.alpha),
1075            window,
1076        );
1077        if let Some(text) = geometry.and_then(|g| g.get(i)) {
1078            let scale = ((slot.width - 28.0) / text.width.max(1.0)).min(1.0);
1079            paint_contours(
1080                &text.contours,
1081                |x, y| project((x - text.width * 0.5) * scale, y * scale + 4.5),
1082                alpha(palette.item_text, pose.alpha),
1083                window,
1084            );
1085        }
1086    }
1087    let front_h = h * 0.76;
1088    let angle = -(config.rest_angle + (config.flap_angle - config.rest_angle) * flap).to_radians();
1089    let project = |x: f32, y: f32| {
1090        let dy = y - front_h;
1091        let depth = dy * angle.sin();
1092        let k = 600.0 / (600.0 + depth);
1093        (cx + (x - w * 0.5) * k, top + h + dy * angle.cos() * k)
1094    };
1095    paint_contours(
1096        [rounded_points(w, front_h, config.radius)],
1097        project,
1098        palette.front,
1099        window,
1100    );
1101    if let Some(geometry) = geometry {
1102        let n = slots.len();
1103        for (i, y, opacity) in [
1104            (n, front_h * 0.52, 1.0),
1105            (n + 1, front_h * 0.52 + 23.0, 0.65),
1106        ] {
1107            if let Some(text) = geometry.get(i) {
1108                let scale = ((w - 32.0) / text.width.max(1.0)).min(1.0);
1109                paint_contours(
1110                    &text.contours,
1111                    |x, dy| project(w * 0.5 + (x - text.width * 0.5) * scale, y + dy * scale),
1112                    alpha(palette.label, opacity),
1113                    window,
1114                );
1115            }
1116        }
1117    }
1118}
1119
1120#[cfg(test)]
1121mod tests {
1122    use super::*;
1123
1124    #[test]
1125    fn layout_wraps_measured_labels_without_overlap() {
1126        let config = FolderFloatConfig::default();
1127        let (slots, height) = layout(&[180.0, 180.0, 120.0, 140.0], &config);
1128        assert!(height > 150.0);
1129        assert_eq!(slots.len(), 4);
1130        assert!(slots[1].pose.y < slots[0].pose.y);
1131        for slot in slots {
1132            assert!(slot.pose.x.abs() + slot.width * 0.5 <= config.spread + 0.01);
1133        }
1134    }
1135
1136    #[test]
1137    fn floating_world_stays_planar_and_bounded() {
1138        let config = FolderFloatConfig::default();
1139        let (slots, height) = layout(&[130.0, 180.0, 110.0], &config);
1140        let poses: Vec<Pose> = slots.iter().map(|s| s.pose).collect();
1141        let mut world = make_world(&poses, &slots, height, &config);
1142        world.bodies[0].linear_velocity = Vec3::new(600.0, -300.0, 0.0);
1143        for _ in 0..600 {
1144            world.step(1.0 / 120.0);
1145        }
1146        for body in world.bodies.iter().take(poses.len()) {
1147            assert!(body.position.x.abs() < config.spread + 30.0);
1148            assert!(body.position.y >= -height - 2.0 && body.position.y < 0.0);
1149            assert_eq!(body.position.z, 0.0);
1150        }
1151    }
1152
1153    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
1154    use gpui_kit::{
1155        Context, Render, TestAppContext,
1156        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
1157    };
1158    use std::cell::Cell;
1159
1160    struct Host {
1161        selected: Rc<Cell<usize>>,
1162        changes: Rc<Cell<usize>>,
1163    }
1164    impl Render for Host {
1165        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1166            let selected = self.selected.clone();
1167            let changes = self.changes.clone();
1168            div().child(
1169                FolderFloat::new("folder-test")
1170                    .label("Feedback")
1171                    .items(["Warmer palette", "Spacing"])
1172                    .config(FolderFloatConfig {
1173                        trigger: FolderFloatTrigger::Click,
1174                        physics: false,
1175                        ..Default::default()
1176                    })
1177                    .on_select(move |selection, _, _| {
1178                        assert_eq!(selection.index, 0);
1179                        selected.set(selected.get() + 1);
1180                    })
1181                    .on_open_change(move |_, _, _| changes.set(changes.get() + 1)),
1182            )
1183        }
1184    }
1185
1186    #[gpui_kit::test]
1187    fn folder_float_selection_fires_once_and_closes(cx: &mut TestAppContext) {
1188        cx.update(|cx| {
1189            gpui_kit::init(cx);
1190            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
1191            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
1192        });
1193        let selected = Rc::new(Cell::new(0));
1194        let changes = Rc::new(Cell::new(0));
1195        let (_, cx) = cx.add_window_view(|_, _| Host {
1196            selected: selected.clone(),
1197            changes: changes.clone(),
1198        });
1199        cx.update(|window, cx| {
1200            window.render_frame(cx);
1201            let bounds = window.find("folder-test").bounds();
1202            let p = point(bounds.center().x, bounds.bottom() - px(70.0));
1203            window.pointer_down(p, MouseButton::Left, cx);
1204            window.pointer_up(p, MouseButton::Left, cx);
1205            window.render_frame(cx);
1206            let item = window.find_by_label("Warmer palette");
1207            assert_eq!(item.role(), Some(Role::Button));
1208            let p = item.bounds().center();
1209            window.pointer_down(p, MouseButton::Left, cx);
1210            window.pointer_up(p, MouseButton::Left, cx);
1211            window.render_frame(cx);
1212            assert_eq!(selected.get(), 1);
1213            assert_eq!(changes.get(), 2);
1214        });
1215    }
1216
1217    #[gpui_kit::test]
1218    fn folder_float_reversal_and_reduced_motion_preserve_lifecycle(cx: &mut TestAppContext) {
1219        cx.update(|cx| {
1220            let config = FolderFloatConfig::default();
1221            let (slots, height) = layout(&[120.0, 130.0], &config);
1222            let mut state = State::new(false, 0.0, config, cx);
1223            state.tick(0.0, &slots, height, false);
1224            state.set_open(true, 0.0);
1225            state.tick(1.0, &slots, height, false);
1226            assert!(state.world.is_some());
1227            state.tick(1.1, &slots, height, false);
1228            let x = state.poses[0].x;
1229            let y = state.poses[0].y;
1230            state.set_open(false, 1.1);
1231            state.tick(1.1, &slots, height, false);
1232            assert_eq!(state.poses[0].x, x);
1233            assert_eq!(state.poses[0].y, y);
1234            assert!(state.world.is_none());
1235            state.set_open(true, 1.2);
1236            assert!(!state.tick(1.2, &slots, height, true));
1237            assert!(state.world.is_none());
1238            assert_eq!(state.poses[0].alpha, 1.0);
1239            assert_eq!(state.poses[0].x, slots[0].pose.x);
1240        });
1241    }
1242
1243    #[test]
1244    fn invalid_configuration_is_sanitized() {
1245        let config = FolderFloatConfig {
1246            spread: f32::NAN,
1247            open_duration: -2.0,
1248            ..Default::default()
1249        }
1250        .sanitized();
1251        assert_eq!(config.spread, 180.0);
1252        assert_eq!(config.open_duration, 0.1);
1253    }
1254}