use std::sync::Arc;
use super::{
Badge, BadgePart, BadgeVariant, FontFamily, names,
part_style::PartStyle,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::pressable,
theme::{Themed, current_theme},
};
use crate::{
app::{
events::MouseEvent,
theme::{PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::Row,
layout::Alignment,
node::{CursorIcon, Element, EventHandler, IntoMouseEventHandler, color::Color},
};
pub const MEDIA_RATES: [f32; 6] = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0];
pub fn media_rate_text(rate: f32) -> String {
if (rate - 1.0).abs() < f32::EPSILON {
super::current_locale().media.normal_speed.to_string()
} else {
format!("{rate}×")
}
}
pub fn media_time_text(seconds: f64, hours: bool) -> String {
let whole = if seconds.is_finite() && seconds > 0.0 {
seconds.floor() as u64
} else {
0
};
let (h, m, s) = (whole / 3600, whole / 60 % 60, whole % 60);
if hours || h > 0 {
format!("{h}:{m:02}:{s:02}")
} else {
format!("{m}:{s:02}")
}
}
pub(super) fn said_to_tooling(
state: &'static str,
position: f64,
duration: Option<f64>,
source: Option<&Arc<str>>,
) -> Vec<(&'static str, Arc<str>)> {
let mut said: Vec<(&'static str, Arc<str>)> = vec![
("media_state", Arc::from(state)),
("media_position", Arc::from(format!("{position:.1}"))),
];
if let Some(duration) = duration.filter(|duration| duration.is_finite() && *duration > 0.0) {
said.push(("media_duration", Arc::from(format!("{duration:.1}"))));
}
if let Some(source) = source {
said.push(("media_source", source.clone()));
}
said
}
const UNKNOWN: &str = "-:--";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MediaTimePart {
Root,
Elapsed,
Divider,
Total,
Live,
}
names!(MediaTimePart {
Root => "root",
Elapsed => "elapsed",
Divider => "divider",
Total => "total",
Live => "live",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MediaTimeState {
OnMedia,
Remaining,
Unknown,
Live,
Pressable,
}
names!(MediaTimeState {
OnMedia => "on_media",
Remaining => "remaining",
Unknown => "unknown",
Live => "live",
Pressable => "pressable",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MediaTimeSize {
Sm,
#[default]
Md,
Lg,
}
names!(MediaTimeSize {
Sm => "sm",
Md => "md",
Lg => "lg",
});
pub type MediaTimeRenderer = Arc<dyn Fn(MediaTimeView) -> Element + Send + Sync>;
#[derive(Clone)]
pub struct MediaTime {
position: f64,
duration: Option<f64>,
remaining: bool,
on_media: bool,
live: bool,
live_text: Arc<str>,
size: Name,
label: Option<Arc<str>>,
on_click: Vec<EventHandler<MouseEvent>>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl MediaTime {
pub fn new(position: impl Into<f64>, duration: Option<f64>) -> Self {
Self {
position: position.into(),
duration,
remaining: false,
on_media: false,
live: false,
live_text: super::current_locale().media.live.clone(),
size: MediaTimeSize::default().into(),
label: None,
on_click: Vec::new(),
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn remaining(mut self, remaining: bool) -> Self {
self.remaining = remaining;
self
}
pub fn on_media(mut self, on_media: bool) -> Self {
self.on_media = on_media;
self
}
pub fn live(mut self, live: bool) -> Self {
self.live = live;
self
}
pub fn live_text(mut self, text: &str) -> Self {
self.live_text = Arc::from(text);
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn on_click(mut self, handler: impl IntoMouseEventHandler) -> Self {
self.on_click.push(handler.into_event_handler());
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
let known = |seconds: Option<f64>| seconds.filter(|seconds| seconds.is_finite() && *seconds >= 0.0);
let duration = known(self.duration);
let unknown = !self.live && duration.is_none();
let case = Case {
variant: None,
size: Some(self.size.clone()),
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(MediaTimeState::OnMedia, self.on_media)
.state(MediaTimeState::Remaining, self.remaining && !unknown && !self.live)
.state(MediaTimeState::Unknown, unknown)
.state(MediaTimeState::Live, self.live)
.state(MediaTimeState::Pressable, !self.on_click.is_empty());
let view = MediaTimeView {
position: known(Some(self.position)).unwrap_or(0.0),
duration,
remaining: self.remaining,
on_media: self.on_media,
live: self.live,
live_text: self.live_text,
size: self.size,
label: self.label,
recipe: theme
.resolve::<MediaTime>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
on_click: self.on_click,
forced: self.forced,
id: self.id,
key: self.key,
};
match theme.renderer::<MediaTime>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<MediaTime> for Element {
fn from(time: MediaTime) -> Self {
time.build(¤t_theme())
}
}
pub struct MediaTimeView {
pub position: f64,
pub duration: Option<f64>,
pub remaining: bool,
pub on_media: bool,
pub live: bool,
pub live_text: Arc<str>,
pub size: Name,
pub label: Option<Arc<str>>,
pub recipe: ResolvedRecipe,
on_click: Vec<EventHandler<MouseEvent>>,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl MediaTimeView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self
.recipe
.part(part)
.forced(self.forced.filter(|_| !self.on_click.is_empty()))
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn readings(&self) -> (String, Option<String>) {
let Some(duration) = self.duration else {
return (UNKNOWN.to_owned(), Some(UNKNOWN.to_owned()));
};
let hours = duration >= 3600.0;
if self.remaining {
(
format!("-{}", media_time_text((duration - self.position).max(0.0), hours)),
None,
)
} else {
(
media_time_text(self.position.min(duration), hours),
Some(media_time_text(duration, hours)),
)
}
}
pub fn name(&self) -> Arc<str> {
if let Some(label) = &self.label {
return label.clone();
}
if self.live {
return self.live_text.clone();
}
match self.readings() {
(elapsed, Some(total)) => Arc::from(format!("{elapsed} of {total}")),
(left, None) => Arc::from(format!("{} left", left.trim_start_matches('-'))),
}
}
fn reading(&self, part: MediaTimePart, text: &str) -> Element {
let part = self.part(part);
part.text(text).nowrap().part(&part).into()
}
pub fn content(&self) -> Vec<Element> {
if self.live {
return vec![
Badge::new(&self.live_text)
.variant(BadgeVariant::Destructive)
.rules(&self.recipe.rules_for(MediaTimePart::Live, BadgePart::Root))
.build(self.theme()),
];
}
let (elapsed, total) = self.readings();
let mut content = vec![self.reading(MediaTimePart::Elapsed, &elapsed)];
if let Some(total) = total {
content.push(self.reading(MediaTimePart::Divider, "/"));
content.push(self.reading(MediaTimePart::Total, &total));
}
content
}
pub fn render(self) -> Element {
let root = self.part(MediaTimePart::Root);
let name = self.name();
if self.on_click.is_empty() {
let mut row = Row::new()
.align_items(Alignment::Center)
.flex_shrink(0.0)
.part(&root)
.with_children(self.content())
.describe("a11y_name", name);
if let Some(id) = &self.id {
row = row.id(id.clone());
}
if let Some(key) = &self.key {
row = row.key(key.clone());
}
return row.into();
}
let mut button = pressable(&root, false)
.align_items(Alignment::Center)
.flex_shrink(0.0)
.with_children(self.content())
.describe("a11y_role", "button")
.describe("a11y_name", name);
for handler in self.on_click.iter().cloned() {
button = button.on_click(handler);
}
if let Some(id) = &self.id {
button = button.id(id.clone());
}
if let Some(key) = &self.key {
button = button.key(key.clone());
}
button.into()
}
}
impl crate::ui::Styled for MediaTime {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for MediaTime {
const NAME: &'static str = "media_time";
type Renderer = MediaTimeRenderer;
fn parts() -> crate::ui::Declared {
MediaTimePart::declared()
}
fn states() -> crate::ui::Declared {
MediaTimeState::declared()
}
fn recipe() -> Recipe {
use MediaTimePart::{Divider, Elapsed, Live, Root, Total};
use PaletteColor::*;
let mono = |s: PartStyle| s.typography(TypographyStyle::Caption).font_family(FontFamily::Mono);
let sized = |recipe: Recipe, size: MediaTimeSize, font: f32| {
[Elapsed, Divider, Total]
.into_iter()
.fold(recipe, |recipe, part| recipe.size(size, part, |s| s.font_size(font)))
};
let recipe = Recipe::new()
.base(Root, |s| s.gap(4.0))
.base(Elapsed, |s| mono(s).foreground(Foreground))
.base(Divider, |s| mono(s).foreground(MutedForeground))
.base(Total, |s| mono(s).foreground(MutedForeground))
.base(Live, |s| s.background(Destructive).foreground(DestructiveForeground))
.state(MediaTimeState::Unknown, Elapsed, |s| s.foreground(MutedForeground))
.state(MediaTimeState::OnMedia, Elapsed, |s| s.foreground(Color::from_hex("#FFFFFF")))
.state(MediaTimeState::OnMedia, Divider, |s| s.foreground(Color::from_hex("#FFFFFF99")))
.state(MediaTimeState::OnMedia, Total, |s| s.foreground(Color::from_hex("#FFFFFF99")))
.when(
Selector::new().state(MediaTimeState::OnMedia).state(MediaTimeState::Unknown),
Elapsed,
|s| s.foreground(Color::from_hex("#FFFFFF99")),
)
.state(MediaTimeState::Pressable, Root, |s| {
s.radius(RadiusSize::Sm).cursor(CursorIcon::Pointer)
})
.focus_visible(Root, |s| s.focus_ring());
let recipe = sized(recipe, MediaTimeSize::Sm, 11.0);
sized(recipe, MediaTimeSize::Lg, 13.0)
}
}