dfui 0.1.1

Declarative UI framework that draws shapes, text and icons analytically in one wgpu shader
Documentation
use std::any::Any;
use std::time::Duration;

use taffy::{AlignItems, JustifyContent, LengthPercentage, Style};

use super::Styled;
use super::label::Emphasis;
use crate::anim::{Animated, Lerp, ease};
use crate::render::{Color, Shadow};
use crate::theme::{Ink, Role};
use crate::widget::{Element, Event, EventCx, Focus, Key, PaintCx, Widget};

pub(crate) type Handler = Box<dyn Fn(&mut EventCx)>;

const FADE: Duration = Duration::from_millis(120);

/// Press and hover tracking shared by tappable widgets.
#[derive(Default)]
pub(crate) struct Tap {
    pub pressed: bool,
    pub hovered: bool,
}

impl Tap {
    /// Returns whether `ev` completes a tap: pressed and released inside.
    pub fn event(&mut self, ev: &Event, cx: &EventCx) -> bool {
        let hit = match *ev {
            Event::PointerDown { x, y }
            | Event::PointerMove { x, y }
            | Event::PointerUp { x, y } => cx.hit(x, y),
            _ => false,
        };
        match ev {
            Event::PointerDown { .. } if hit => self.pressed = true,
            Event::PointerMove { .. } => self.hovered = hit,
            Event::PointerUp { .. } => return std::mem::take(&mut self.pressed) && hit,
            Event::Cancel => *self = Tap::default(),
            Event::Leave => self.hovered = false,
            _ => {}
        }
        false
    }
    /// Feeds `ev` to the [`Tap`] that `field` finds in the widget's state `S`.
    /// Returns whether a tap completed and whether its look changed.
    pub fn feed<S: Default + 'static>(
        ev: &Event,
        cx: &mut EventCx,
        field: fn(&mut S) -> &mut Tap,
    ) -> (bool, bool) {
        // Enter or Space on the focused widget is a tap.
        if cx.focused && matches!(ev, Event::Key(Key::Enter | Key::Char(' '))) {
            cx.stop();
            return (true, false);
        }
        let mut tap = std::mem::take(field(cx.state.get::<S>()));
        let before = (tap.pressed, tap.hovered);
        let fire = tap.event(ev, cx);
        let changed = (tap.pressed, tap.hovered) != before;
        *field(cx.state.get::<S>()) = tap;
        (fire, changed)
    }
}

#[derive(Default)]
struct ButtonState {
    tap: Tap,
    /// 0..=1 toward the hovered and pressed looks.
    hover: Animated<f32>,
    press: Animated<f32>,
}

/// A tappable box built by [`button`]; see there.
pub struct Button {
    child: [Element; 1],
    on_click: Option<Handler>,
    style: Style,
    color: Ink,
    radius: f32,
    flat: bool,
    enabled: bool,
    /// Labels inside turn bold with the press.
    emphasis: Emphasis,
}

/// Tappable box around `child`; `on_click` runs on a release inside it.
/// Text in it morphs to bold while pressed.
#[doc = example!("button")]
pub fn button(child: impl Into<Element>) -> Button {
    Button {
        child: [child.into()],
        on_click: None,
        style: Style {
            padding: taffy::Rect {
                left: LengthPercentage::length(16.0),
                right: LengthPercentage::length(16.0),
                top: LengthPercentage::length(10.0),
                bottom: LengthPercentage::length(10.0),
            },
            align_items: AlignItems::CENTER,
            justify_content: JustifyContent::CENTER,
            ..Style::default()
        },
        color: Role::Accent.into(),
        radius: 8.0,
        flat: false,
        enabled: true,
        emphasis: Emphasis(
            Default::default(),
            Default::default(),
            Role::OnAccent.into(),
        ),
    }
}

impl Button {
    /// Runs on release inside the button, e.g. to `update` local state.
    pub fn on_click(mut self, f: impl Fn(&mut EventCx) + 'static) -> Self {
        self.on_click = Some(Box::new(f));
        self
    }
    /// Background color; [`Role::Accent`] by default.
    pub fn color(mut self, c: impl Into<Ink>) -> Self {
        self.color = c.into();
        self
    }
    /// Corner radius, logical px; 8 by default.
    pub fn radius(mut self, r: f32) -> Self {
        self.radius = r;
        self
    }
    /// No drop shadow, e.g. for items in a list.
    pub fn flat(mut self) -> Self {
        self.flat = true;
        self
    }
    /// When false the button is dimmed and ignores input; it keeps its size.
    pub fn enabled(mut self, on: bool) -> Self {
        self.enabled = on;
        self
    }
}

impl From<Button> for Element {
    fn from(w: Button) -> Self {
        Element::new(w)
    }
}

impl Styled for Button {
    fn style_mut(&mut self) -> &mut Style {
        &mut self.style
    }
}

impl Widget for Button {
    fn focus(&self) -> Option<Focus> {
        let radius = self.radius;
        (self.enabled && self.on_click.is_some()).then_some(Focus {
            radius,
            keyboard: None,
        })
    }
    fn style(&self) -> Style {
        self.style.clone()
    }
    fn children(&self) -> &[Element] {
        &self.child
    }
    fn provide(&self) -> Option<&dyn Any> {
        Some(&self.emphasis)
    }
    fn paint(&self, cx: &mut PaintCx) {
        let now = cx.now;
        let s = cx.state.get::<ButtonState>();
        let flag = |b: bool| if b { 1.0 } else { 0.0 };
        let (hovered, pressed) = (s.tap.hovered && self.enabled, s.tap.pressed && self.enabled);
        s.hover.to(flag(hovered), now, FADE, ease::out_cubic);
        s.press.to(flag(pressed), now, FADE, ease::out_cubic);
        let (hover, press) = (s.hover.get(now), s.press.get(now));
        self.emphasis.0.set(press);
        self.emphasis.1.set(!self.enabled);
        if s.hover.running(now) || s.press.running(now) {
            cx.request_frame();
        }
        let k = 1.0.lerp(0.9, hover).lerp(0.75, press);
        let c = cx.color(self.color);
        let fill = Color {
            r: c.r * k,
            g: c.g * k,
            b: c.b * k,
            a: if self.enabled { c.a } else { c.a * 0.4 },
        };
        if press < 1.0 && !self.flat && self.enabled {
            let sh = Shadow {
                color: Color::BLACK.alpha(0.25 * (1.0 - press)),
                offset: (0.0, 2.0),
                blur: 4.0,
            };
            cx.shadow(cx.rect, self.radius, sh);
        }
        cx.fill(cx.rect, self.radius, fill);
    }
    fn event(&self, ev: &Event, cx: &mut EventCx) {
        if !self.enabled {
            cx.state.get::<ButtonState>().tap = Tap::default();
            return;
        }
        let (fire, changed) = Tap::feed(ev, cx, |s: &mut ButtonState| &mut s.tap);
        if changed {
            cx.request_redraw();
        }
        if fire && let Some(f) = &self.on_click {
            f(cx);
        }
    }
}