Skip to main content

hyprforge_ui/widgets/
drag.rs

1//! What a drag looks like: the card that travels under the pointer, and
2//! the place it is about to land.
3//!
4//! Files' was the first written here. Nothing about either is about
5//! files: Media dragging a picture into an album, or Settings dragging
6//! a rule up its list, would want a card under the pointer and a target
7//! that says "here" in the same way.
8//!
9//! Two rules from the catalogue shape them:
10//!
11//! - **Purple means selected.** A drop target is not a selection, so it
12//!   is drawn in the foreground colour — an outline crisp enough to tell
13//!   from a hover, which has none, and a fill. What is being *carried*
14//!   is the selection, so the card's count badge is the one place the
15//!   accent appears.
16//! - **Progress is not selection.** A target that will open if the drag
17//!   rests on it (a spring-loaded folder) fills from the left as the
18//!   wait runs out, in the foreground colour, so the opening is
19//!   announced rather than sprung.
20
21use crate::theme::{self, spacing, surface, FontScale};
22use crate::widgets::scaled_text;
23use iced::widget::{container, row, stack, Space};
24use iced::{gradient, Background, Border, Color, Element, Length, Padding, Radians, Shadow, Vector};
25
26/// How a drop target is drawn.
27#[derive(Debug, Clone, Copy, PartialEq, Default)]
28pub enum DropLook {
29    /// Nothing is held over it.
30    #[default]
31    Idle,
32    /// A drag is over it. `opening` is how much of the wait before it
33    /// opens has passed, `0.0` to `1.0` — `0.0` for one that does not
34    /// open, or has not started to.
35    Over { opening: f32 },
36}
37
38/// How opaque the target's fill is at its strongest — the part of the
39/// wait that has passed.
40const OPENING_ALPHA: f32 = 0.16;
41
42/// The style of a container that something can be dropped on.
43pub fn drop_target_style(look: DropLook) -> container::Style {
44    let radius = crate::density::inner_radius();
45    let DropLook::Over { opening } = look else {
46        return container::Style {
47            border: Border { radius: radius.into(), ..Border::default() },
48            ..container::Style::default()
49        };
50    };
51    let opening = opening.clamp(0.0, 1.0);
52    let filled = Color { a: OPENING_ALPHA, ..theme::text() };
53    let background = if opening <= 0.0 {
54        Background::Color(surface::row())
55    } else {
56        // Two stops at the same offset make a hard edge: the part of the
57        // wait that has passed, and the part still to come.
58        Background::Gradient(
59            gradient::Linear::new(Radians(std::f32::consts::FRAC_PI_2))
60                .add_stop(0.0, filled)
61                .add_stop(opening, filled)
62                .add_stop(opening, surface::row())
63                .add_stop(1.0, surface::row())
64                .into(),
65        )
66    };
67    container::Style {
68        background: Some(background),
69        border: Border { color: Color { a: 0.85, ..theme::text() }, width: 1.5, radius: radius.into() },
70        ..container::Style::default()
71    }
72}
73
74/// What the card under the pointer says.
75#[derive(Debug, Clone, PartialEq)]
76pub struct DragCard {
77    /// The first thing carried, by name.
78    pub label: String,
79    /// How many things are carried. More than one stacks the card and
80    /// shows the count.
81    pub count: usize,
82    /// Letting go copies rather than moves — Ctrl is held. A `+` says so,
83    /// the mark every desktop uses for it.
84    pub copying: bool,
85}
86
87/// The card under the pointer, `lift` of the way picked up: `0.0` lying
88/// flat and invisible, `1.0` held. Picking up and letting go both pass
89/// through the values between, which is the whole of the animation —
90/// the caller eases `lift` over time and redraws.
91pub fn drag_card<'a, Message: 'a>(card: &DragCard, lift: f32, scale: FontScale) -> Element<'a, Message> {
92    let lift = lift.clamp(0.0, 1.0);
93    let fade = move |c: Color| Color { a: c.a * lift, ..c };
94    let radius = crate::density::inner_radius();
95    let face = move |shadow: bool| {
96        move |_: &iced::Theme| container::Style {
97            background: Some(Background::Color(fade(surface::sidebar()))),
98            text_color: Some(fade(theme::text())),
99            border: Border { color: fade(surface::card_border()), width: 1.0, radius: radius.into() },
100            // The shadow grows as the card rises: what makes it read as
101            // picked up rather than slid along. The root step, darkened
102            // by its own alpha — never an invented black.
103            shadow: if shadow {
104                Shadow {
105                    color: fade(Color { a: 0.55, ..surface::root() }),
106                    offset: Vector::new(0.0, 2.0 + 6.0 * lift),
107                    blur_radius: 4.0 + 14.0 * lift,
108                }
109            } else {
110                Shadow::default()
111            },
112            ..container::Style::default()
113        }
114    };
115    let label = scaled_text(card.label.clone(), 13.0, scale).wrapping(iced::widget::text::Wrapping::None);
116    let mut front = row![label].spacing(spacing::SM).align_y(iced::Alignment::Center);
117    if card.copying {
118        front = front.push(badge("+".to_string(), fade(theme::success()), scale));
119    }
120    if card.count > 1 {
121        front = front.push(badge(card.count.to_string(), fade(crate::color::to_iced(theme::active().accent)), scale));
122    }
123    let top = container(front).padding([spacing::XS + 2.0, spacing::SM + 4.0]).style(face(true));
124    if card.count <= 1 {
125        return container(top).padding(Padding { right: 8.0, bottom: 8.0, ..Padding::ZERO }).into();
126    }
127    // More than one: two blank cards behind, each offset a little further,
128    // as a pile of papers is.
129    let behind = |offset: f32| {
130        container(container(Space::new().width(Length::Fill).height(Length::Fill)).style(face(false)))
131            .padding(Padding { left: offset, top: offset, right: 8.0 - offset, bottom: 8.0 - offset })
132            .width(Length::Fill)
133            .height(Length::Fill)
134    };
135    stack![
136        behind(8.0),
137        behind(4.0),
138        container(top).padding(Padding { right: 8.0, bottom: 8.0, ..Padding::ZERO }),
139    ]
140    .into()
141}
142
143/// A small round mark with a number or a sign in it.
144fn badge<'a, Message: 'a>(text: String, fill: Color, scale: FontScale) -> Element<'a, Message> {
145    container(scaled_text(text, 11.0, scale))
146        .padding([1.0, 6.0])
147        .style(move |_: &iced::Theme| container::Style {
148            background: Some(Background::Color(fill)),
149            text_color: Some(Color { a: fill.a, ..surface::root() }),
150            border: Border { radius: 999.0.into(), ..Border::default() },
151            ..container::Style::default()
152        })
153        .into()
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn a_target_nothing_is_over_draws_nothing() {
162        let style = drop_target_style(DropLook::Idle);
163        assert!(style.background.is_none());
164        assert_eq!(style.border.width, 0.0);
165    }
166
167    #[test]
168    fn a_target_under_a_drag_has_an_outline_a_hover_does_not() {
169        let style = drop_target_style(DropLook::Over { opening: 0.0 });
170        assert!(style.border.width > 0.0);
171    }
172
173    /// Purple means selected — see the catalogue. A drop target is not a
174    /// selection, so the accent appears nowhere in its look, whatever
175    /// part of the wait has passed.
176    #[test]
177    fn a_drop_target_never_uses_the_accent() {
178        let accent = crate::color::to_iced(theme::active().accent);
179        for opening in [0.0, 0.5, 1.0] {
180            let style = drop_target_style(DropLook::Over { opening });
181            assert_ne!(style.border.color, accent);
182            if let Some(Background::Color(c)) = style.background {
183                assert_ne!(c, accent);
184            }
185        }
186    }
187
188    #[test]
189    fn an_opening_target_fills_as_far_as_the_wait_has_gone() {
190        let Some(Background::Gradient(iced::Gradient::Linear(linear))) =
191            drop_target_style(DropLook::Over { opening: 0.4 }).background
192        else {
193            panic!("an opening target is filled part of the way")
194        };
195        let edges: Vec<f32> = linear.stops.iter().flatten().map(|s| s.offset).collect();
196        assert!(edges.contains(&0.4), "{edges:?}");
197    }
198}