use std::{sync::Arc, time::Duration};
use parking_lot::Mutex;
use crate::{
animation::{Easing, Transition},
app::{
component::Component,
ctx::Ctx,
events::{GesturePhase, PanEvent},
window::Haptic,
},
components::{Row, Stack, Text},
core::{ElementRef, Signal},
layout::{
Alignment,
layout_kind::Justify,
text_style::{FontWeight, TextStyle},
},
node::{Element, color::Color, dimension::Dimension, transform::Transform2D},
ui::{Recipe, Themed, engine_look::EngineLook, names},
};
const FILL: Dimension = Dimension::Pct(100.0);
const NO_DRAG: f32 = f32::MIN;
#[derive(Clone)]
pub struct SwipeAction {
pub title: String,
pub icon: Option<Element>,
pub background: Color,
pub color: Color,
pub on_press: Arc<dyn Fn() + Send + Sync>,
}
impl SwipeAction {
pub fn new(title: impl Into<String>, on_press: impl Fn() + Send + Sync + 'static) -> Self {
Self::of(SwipeRowPart::Action, title.into(), Arc::new(on_press))
}
pub fn destructive(title: impl Into<String>, on_press: impl Fn() + Send + Sync + 'static) -> Self {
Self::of(SwipeRowPart::DestructiveAction, title.into(), Arc::new(on_press))
}
fn of(part: SwipeRowPart, title: String, on_press: Arc<dyn Fn() + Send + Sync>) -> Self {
let look = EngineLook::of::<SwipeRowStyle>(&[]);
let (background, color) = legacy_colors(part);
Self {
title,
icon: None,
background: look.background(part, background),
color: look.foreground(part, color),
on_press,
}
}
pub fn background(mut self, color: Color) -> Self {
self.background = color;
self
}
pub fn color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn icon(mut self, icon: impl Into<Element>) -> Self {
self.icon = Some(icon.into());
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SwipeRowPart {
Action,
DestructiveAction,
}
names!(SwipeRowPart {
Action => "action",
DestructiveAction => "destructive_action",
});
fn legacy_colors(part: SwipeRowPart) -> (Color, Color) {
let white = Color::new(255, 255, 255, 255);
match part {
SwipeRowPart::Action => (Color::new(0x8E, 0x8E, 0x93, 255), white),
SwipeRowPart::DestructiveAction => (Color::new(0xFF, 0x3B, 0x30, 255), white),
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SwipeRowStyle {
pub action_width: f32,
pub title_size: f32,
pub full_swipe: f32,
pub throw: f32,
pub duration: Duration,
pub haptic: bool,
}
impl Themed for SwipeRowStyle {
const NAME: &'static str = "phone_swipe_row";
type Renderer = ();
fn recipe() -> Recipe {
use crate::app::theme::PaletteColor::{Background, Destructive, DestructiveForeground, MutedForeground};
Recipe::new()
.base(SwipeRowPart::Action, |s| {
s.background(MutedForeground).foreground(Background)
})
.base(SwipeRowPart::DestructiveAction, |s| {
s.background(Destructive).foreground(DestructiveForeground)
})
}
}
impl SwipeRowStyle {
pub(crate) fn legacy_recipe() -> Recipe {
let mut recipe = Recipe::new();
for part in SwipeRowPart::all() {
let (background, color) = legacy_colors(*part);
recipe = recipe.base(*part, |s| s.background(background).foreground(color));
}
recipe
}
}
impl Default for SwipeRowStyle {
fn default() -> Self {
Self {
action_width: 74.0,
title_size: 15.0,
full_swipe: 0.6,
throw: 0.15,
duration: Duration::from_millis(350),
haptic: true,
}
}
}
#[derive(Clone, Default)]
pub struct SwipeRowProps {
leading: Vec<SwipeAction>,
trailing: Vec<SwipeAction>,
style: SwipeRowStyle,
open: Option<Signal<i8>>,
}
impl PartialEq for SwipeRowProps {
fn eq(&self, _other: &Self) -> bool {
false
}
}
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for SwipeRowProps {
fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}
impl SwipeRowProps {
pub fn new() -> Self {
Self::default()
}
pub fn trailing(mut self, actions: impl IntoIterator<Item = SwipeAction>) -> Self {
self.trailing = actions.into_iter().collect();
self
}
pub fn leading(mut self, actions: impl IntoIterator<Item = SwipeAction>) -> Self {
self.leading = actions.into_iter().collect();
self
}
pub fn style(mut self, style: SwipeRowStyle) -> Self {
self.style = style;
self
}
pub fn open(mut self, open: Signal<i8>) -> Self {
self.open = Some(open);
self
}
}
struct Held {
from: f32,
base: f32,
}
pub struct SwipeRow {
open: Signal<i8>,
drag: Signal<f32>,
held: Arc<Mutex<Option<Held>>>,
velocity: Arc<Mutex<f64>>,
row: ElementRef,
height: Signal<f32>,
moved: Arc<Mutex<bool>>,
settle: crate::app::ctx::Timeout,
settled: Signal<u32>,
}
const SETTLE: Duration = Duration::from_millis(1000);
impl SwipeRow {
pub fn mount(ctx: &mut Ctx, props: SwipeRowProps, content: impl Into<Element>) -> Element {
ctx.mount_with::<Self>(props, vec![content.into()])
}
pub fn mount_keyed(ctx: &mut Ctx, key: &str, props: SwipeRowProps, content: impl Into<Element>) -> Element {
ctx.mount_keyed_with::<Self>(key, props, vec![content.into()])
}
}
impl Component for SwipeRow {
type Props = SwipeRowProps;
fn create(ctx: &mut Ctx) -> Self {
let settled = Signal::new(0u32);
let settle = ctx.create_timeout(SETTLE, {
let settled = settled.clone();
move || settled.update(|times| *times = times.wrapping_add(1))
});
Self {
moved: Arc::default(),
settle,
settled,
open: Signal::new(0),
drag: Signal::new(NO_DRAG),
held: Arc::default(),
velocity: Arc::default(),
row: ElementRef::default(),
height: Signal::new(0.0),
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let props = ctx.props::<SwipeRowProps>().clone();
let style = props.style;
let open = props.open.clone().unwrap_or_else(|| self.open.clone());
let side = open.get();
let drag = self.drag.get();
let height = self.height.get();
let (leading, trailing) = (
props.leading.len() as f32 * style.action_width,
props.trailing.len() as f32 * style.action_width,
);
let rest = match side {
1 => leading,
-1 => -trailing,
_ => 0.0,
};
let dragged = drag != NO_DRAG;
let at = if dragged { drag } else { rest };
let pace = if dragged { Duration::ZERO } else { style.duration };
self.settled.get();
let out = dragged || at != 0.0;
{
let mut moved = self.moved.lock();
if *moved && !out {
self.settle.restart();
}
*moved = out;
}
let bare = !out && !self.settle.is_active();
let curve = Easing::Spring {
velocity: *self.velocity.lock(),
};
let close = {
let open = open.clone();
move || {
if open.get_untracked() != 0 {
open.set(0);
}
}
};
let actions = |list: &[SwipeAction], at_end: bool, shown: f32| {
let mut row = Row::new().height(FILL);
let ordered: Vec<&SwipeAction> = if at_end {
list.iter().rev().collect()
} else {
list.iter().collect()
};
let each = if list.is_empty() {
0.0
} else {
(shown / list.len() as f32).max(style.action_width)
};
for action in ordered {
let (press, close) = (action.on_press.clone(), close.clone());
let mut inside = crate::components::Column::new()
.align_items(Alignment::Center)
.spacing(4.0);
if let Some(icon) = &action.icon {
inside = inside.child(icon.clone());
}
if !action.title.is_empty() {
inside = inside.child(
Text::styled(
&action.title,
TextStyle {
font_size: style.title_size,
weight: FontWeight::Medium,
color: action.color,
..TextStyle::default()
},
)
.nowrap(),
);
}
row = row.child(
Row::new()
.width(each)
.height(FILL)
.align_items(Alignment::Center)
.justify(Justify::Center)
.background(action.background)
.child(inside)
.on_click(move |_| {
close();
press();
}),
);
}
row
};
let mut content = Stack::new()
.width(FILL)
.transform(Transform2D::translate(at, 0.0))
.transition(Transition::transform().duration(pace).easing(curve));
for child in ctx.children() {
content = content.child(child.clone());
}
let content = content
.on_click({
let close = close.clone();
let open = open.clone();
move |event: crate::app::events::MouseEvent| {
if open.get_untracked() != 0 {
event.stop_propagation();
close();
}
}
})
.on_pan({
let (held, drag, velocity) = (self.held.clone(), self.drag.clone(), self.velocity.clone());
let (open, row) = (open.clone(), self.row.clone());
let (first_leading, first_trailing) = (
props.leading.first().map(|action| action.on_press.clone()),
props.trailing.first().map(|action| action.on_press.clone()),
);
let window = ctx.window();
move |event: PanEvent| match event.phase {
GesturePhase::Start => {
if event.fingers != 1 || event.translation_x.abs() <= event.translation_y.abs() {
return;
}
let towards = if event.translation_x < 0.0 { trailing } else { leading };
if towards <= 0.0 && rest == 0.0 {
return;
}
event.prevent_default();
event.stop_propagation();
*held.lock() = Some(Held {
from: event.translation_x,
base: rest,
});
drag.set(rest);
}
GesturePhase::Change => {
let held = held.lock();
if let Some(held) = &*held {
event.stop_propagation();
let x = held.base + event.translation_x - held.from;
let limit = if x < 0.0 { trailing } else { leading };
let over = (x.abs() - limit).max(0.0);
let give = if limit > 0.0 { 1.0 } else { 0.15 };
drag.set(x.signum() * (x.abs().min(limit) + over * give));
}
}
GesturePhase::End => {
let Some(held) = held.lock().take() else {
return;
};
event.stop_propagation();
let x = held.base + event.translation_x - held.from;
let width = row.width().max(1.0);
let thrown = x + event.velocity_x * style.throw;
let all_the_way = x.abs() > width * style.full_swipe;
let goes: i8 = if thrown < -trailing / 2.0 && trailing > 0.0 {
-1
} else if thrown > leading / 2.0 && leading > 0.0 {
1
} else {
0
};
let target = match goes {
1 => leading,
-1 => -trailing,
_ => 0.0,
};
let left = target - x;
*velocity.lock() = if left.abs() > 1.0 {
f64::from((event.velocity_x * style.duration.as_secs_f32() / left).max(0.0))
} else {
0.0
};
drag.set(NO_DRAG);
if all_the_way && goes != 0 {
let first = if goes < 0 { &first_trailing } else { &first_leading };
if open.get_untracked() != 0 {
open.set(0);
}
if style.haptic {
window.haptic(Haptic::Medium);
}
if let Some(first) = first {
first();
}
} else if open.get_untracked() != goes {
open.set(goes);
}
}
}
});
Stack::new()
.ref_element(self.row.clone())
.width(FILL)
.clip()
.child(
if bare {
Row::new().width(FILL).height(height)
} else {
Row::new()
.width(FILL)
.height(height)
.child(actions(&props.leading, false, at.max(0.0)))
.child(Row::new().flex(1.0))
.child(actions(&props.trailing, true, (-at).max(0.0)))
},
)
.child(content)
}
fn after_layout(&self) {
if self.row.is_attached() {
let height = self.row.rect().3;
if (self.height.get_untracked() - height).abs() > 0.25 {
self.height.set(height);
}
}
}
}