use std::sync::Arc;
use super::{
Button, ButtonSize, ButtonVariant, Tooltip, icons, media_time_text, names,
part_style::{FontFamily, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{fading, glyph, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
ctx::Ctx,
events::MouseEvent,
theme::{BorderSize, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::{Column, Row, Stack, TextOverflow},
core::{ElementRef, Signal},
layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
node::{CursorIcon, Element, FocusGroup, dimension::Dimension, outline::Outline},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AudioQueuePart {
Root,
Item,
Lead,
Number,
LeadIcon,
Media,
MediaIcon,
Text,
Title,
Description,
Duration,
More,
}
names!(AudioQueuePart {
Root => "root",
Item => "item",
Lead => "lead",
Number => "number",
LeadIcon => "lead_icon",
Media => "media",
MediaIcon => "media_icon",
Text => "text",
Title => "title",
Description => "description",
Duration => "duration",
More => "more",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AudioQueueState {
Current,
Playing,
Unavailable,
Media,
Disabled,
}
names!(AudioQueueState {
Current => "current",
Playing => "playing",
Unavailable => "unavailable",
Media => "media",
Disabled => "disabled",
});
pub type AudioQueueRenderer = Arc<dyn Fn(AudioQueueView) -> Element + Send + Sync>;
type Command = Arc<dyn Fn() + Send + Sync>;
#[derive(Clone)]
pub struct AudioQueueItem {
title: Arc<str>,
description: Option<Arc<str>>,
media: Option<Element>,
duration: Option<f64>,
disabled: bool,
on_select: Vec<Command>,
on_more: Vec<Command>,
more_anchor: Option<ElementRef>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl AudioQueueItem {
pub fn new(title: &str) -> Self {
Self {
title: Arc::from(title),
description: None,
media: None,
duration: None,
disabled: false,
on_select: Vec::new(),
on_more: Vec::new(),
more_anchor: None,
id: None,
key: None,
}
}
pub fn description(mut self, description: &str) -> Self {
self.description = Some(Arc::from(description));
self
}
pub fn media(mut self, media: impl Into<Element>) -> Self {
self.media = Some(media.into());
self
}
pub fn duration(mut self, seconds: impl Into<f64>) -> Self {
self.duration = Some(seconds.into());
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn on_select(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_select.push(Arc::new(handler));
self
}
pub fn on_more(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_more.push(Arc::new(handler));
self
}
pub fn more_anchor(mut self, anchor: ElementRef) -> Self {
self.more_anchor = Some(anchor);
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
}
}
#[derive(Clone)]
pub struct AudioQueue {
current: Option<usize>,
on_change: Vec<Arc<dyn Fn(usize) + Send + Sync>>,
items: Vec<AudioQueueItem>,
playing: bool,
label: Arc<str>,
more_label: Arc<str>,
playing_label: Arc<str>,
disabled: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl AudioQueue {
pub fn new(current: Signal<Option<usize>>, items: impl IntoIterator<Item = AudioQueueItem>) -> Self {
let set = current.clone();
let mut queue = Self::controlled(current.get(), items, move |index| set.set(Some(index)));
queue.current = current.get();
queue
}
pub fn controlled(
current: Option<usize>,
items: impl IntoIterator<Item = AudioQueueItem>,
on_change: impl Fn(usize) + Send + Sync + 'static,
) -> Self {
Self {
current,
on_change: vec![Arc::new(on_change)],
items: items.into_iter().collect(),
playing: false,
label: super::current_locale().media.queue.clone(),
more_label: super::current_locale().media.more.clone(),
playing_label: super::current_locale().media.now_playing.clone(),
disabled: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn item(mut self, item: AudioQueueItem) -> Self {
self.items.push(item);
self
}
pub fn items(mut self, items: impl IntoIterator<Item = AudioQueueItem>) -> Self {
self.items.extend(items);
self
}
pub fn playing(mut self, playing: bool) -> Self {
self.playing = playing;
self
}
pub fn on_change(mut self, handler: impl Fn(usize) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Arc::from(label);
self
}
pub fn more_label(mut self, label: &str) -> Self {
self.more_label = Arc::from(label);
self
}
pub fn playing_label(mut self, label: &str) -> Self {
self.playing_label = Arc::from(label);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
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 mount(self, ctx: &mut Ctx) -> Element {
let theme = current_theme();
Self::render_view(self.view(&theme, Some(ctx)))
}
pub fn build(self, theme: &Theme) -> Element {
Self::render_view(self.view(theme, None))
}
fn render_view(view: AudioQueueView) -> Element {
match view.theme().renderer::<AudioQueue>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
fn case(&self) -> Case {
Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(AudioQueueState::Disabled, self.disabled)
}
fn view(self, theme: &Theme, mut ctx: Option<&mut Ctx>) -> AudioQueueView {
let recipe = theme
.resolve::<AudioQueue>(&self.case(), Some(&self.rules))
.owned_by(self.id.as_ref());
let entry = self
.current
.filter(|current| self.items.get(*current).is_some_and(|item| !item.disabled))
.or_else(|| self.items.iter().position(|item| !item.disabled));
let base = self.case();
let handlers = Arc::new(self.on_change);
let rows = self
.items
.into_iter()
.enumerate()
.map(|(index, item)| {
let current = self.current == Some(index);
let case = base
.clone()
.state(AudioQueueState::Current, current)
.state(AudioQueueState::Playing, current && self.playing)
.state(AudioQueueState::Unavailable, item.disabled)
.state(AudioQueueState::Media, item.media.is_some());
let in_case = theme
.resolve::<AudioQueue>(&case, Some(&self.rules))
.owned_like(&recipe);
let row_recipe = match (&item.id, &item.key) {
(None, Some(key)) => in_case.keyed_item(key, AudioQueuePart::Item),
(id, _) => in_case.item(id.as_ref(), AudioQueuePart::Item),
};
let forced = self.forced.filter(|_| entry == Some(index));
let more = (!item.on_more.is_empty()).then(|| {
let commands = item.on_more.clone();
let mut button = Button::new(&self.more_label)
.rules(&row_recipe.lend(AudioQueuePart::More))
.icon(icons::MORE_HORIZONTAL)
.icon_only(true)
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Xs)
.disabled(item.disabled || self.disabled)
.on_click(move |event: MouseEvent| {
event.stop_propagation();
for command in &commands {
command();
}
});
if let Some(id) = &item.id {
button = button.id(format!("{id}-more"));
}
if let Some(anchor) = &item.more_anchor {
button = button.ref_element(anchor.clone());
}
let element = button.build(theme);
match ctx.as_deref_mut() {
Some(ctx) => Tooltip::new(&self.more_label).mount(ctx, element),
None => element,
}
});
AudioQueueRow {
index,
current,
playing: current && self.playing,
press: (!current && !item.disabled && !self.disabled).then(|| {
let (handlers, own) = (handlers.clone(), item.on_select.clone());
Arc::new(move || {
for handler in handlers.iter() {
handler(index);
}
for command in &own {
command();
}
}) as Command
}),
entry: entry == Some(index),
recipe: row_recipe,
forced,
more,
item,
}
})
.collect();
AudioQueueView {
rows,
label: self.label,
playing_label: self.playing_label,
disabled: self.disabled,
recipe,
id: self.id,
key: self.key,
}
}
}
impl crate::app::component::IntoComponent for AudioQueue {
type Component = AudioQueueHost;
fn into_props(self) -> AudioQueueProps {
AudioQueueProps(self)
}
fn component_key(&self) -> Option<Arc<str>> {
self.key.clone()
}
}
#[doc(hidden)]
#[derive(Clone)]
pub struct AudioQueueProps(AudioQueue);
impl PartialEq for AudioQueueProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for AudioQueueProps {}
#[doc(hidden)]
pub struct AudioQueueHost;
impl crate::app::component::Component for AudioQueueHost {
type Props = AudioQueueProps;
fn create(_ctx: &mut Ctx) -> Self {
Self
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let queue = ctx.props::<AudioQueueProps>().0.clone();
queue.mount(ctx)
}
}
pub struct AudioQueueRow {
pub index: usize,
pub current: bool,
pub playing: bool,
pub entry: bool,
pub recipe: ResolvedRecipe,
pub more: Option<Element>,
press: Option<Command>,
forced: Option<Interaction>,
item: AudioQueueItem,
}
impl AudioQueueRow {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
}
pub struct AudioQueueView {
pub rows: Vec<AudioQueueRow>,
pub label: Arc<str>,
pub playing_label: Arc<str>,
pub disabled: bool,
pub recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl AudioQueueView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn lead(&self, row: &AudioQueueRow) -> Row {
let part = row.part(AudioQueuePart::Lead);
let lead = Row::new()
.part(&part)
.flex_shrink(0.0)
.align_items(Alignment::Center)
.justify(Justify::Center);
if row.playing {
let mut icon = glyph(&row.part(AudioQueuePart::LeadIcon), Name::from(icons::EQUALIZER), false);
crate::node::NodeUpdate::describe(&mut *icon.node, Arc::from("a11y_name"), self.playing_label.clone());
return lead.child(icon);
}
let number = row.part(AudioQueuePart::Number);
let mut stack = Stack::new().child(
Row::new()
.part(&number)
.child(number.text(&(row.index + 1).to_string()).nowrap()),
);
if row.press.is_some() {
stack = stack.child(glyph(
&row.part(AudioQueuePart::LeadIcon),
Name::from(icons::PLAY),
false,
));
}
lead.child(stack)
}
pub fn media(&self, row: &mut AudioQueueRow) -> Row {
let held = Row::new()
.part(&row.part(AudioQueuePart::Media))
.flex_shrink(0.0)
.clip()
.align_items(Alignment::Center)
.justify(Justify::Center);
match row.item.media.take() {
Some(media) => held.child(media),
None => held.child(glyph(
&row.part(AudioQueuePart::MediaIcon),
Name::from(icons::MUSIC),
false,
)),
}
}
pub fn text(&self, row: &AudioQueueRow) -> Column {
let line = |part: ResolvedPart, text: &str| {
Column::new()
.width(Dimension::Pct(100.0))
.min_width(Dimension::Px(0.0))
.part(&part)
.child(
part
.text(text)
.nowrap()
.text_overflow(TextOverflow::Elipsis)
.width(Dimension::Pct(100.0)),
)
};
let mut column = Column::new()
.flex(1.0)
.min_width(Dimension::Px(0.0))
.part(&row.part(AudioQueuePart::Text))
.child(line(row.part(AudioQueuePart::Title), &row.item.title));
if let Some(description) = &row.item.description {
column = column.child(line(row.part(AudioQueuePart::Description), description));
}
column
}
pub fn row(&self, mut row: AudioQueueRow) -> Element {
let part = row.part(AudioQueuePart::Item);
let mut name = row.item.title.to_string();
if let Some(description) = &row.item.description {
name = format!("{name}, {description}");
}
let mut root = pressable(&part, row.item.disabled || self.disabled)
.justify(Justify::Start)
.align_items(Alignment::Center)
.width(Dimension::Pct(100.0))
.interaction_group(true)
.stops_inside(true)
.focus_entry(row.entry)
.describe("a11y_role", "option")
.describe("a11y_name", name)
.describe("a11y_selected", if row.current { "true" } else { "false" })
.child(self.lead(&row));
root = root.child(self.media(&mut row)).child(self.text(&row));
if let Some(seconds) = row.item.duration {
let duration = row.part(AudioQueuePart::Duration);
root = root.child(
Row::new()
.part(&duration)
.flex_shrink(0.0)
.child(duration.text(&media_time_text(seconds, seconds >= 3600.0)).nowrap()),
);
}
if let Some(more) = row.more.take() {
root = root.child(
Row::new()
.part(&row.part(AudioQueuePart::More).unnamed())
.flex_shrink(0.0)
.focus_group(FocusGroup::none())
.on_click(|event: MouseEvent| event.stop_propagation())
.child(more),
);
}
if let Some(press) = &row.press {
let press = press.clone();
root = root.on_click(move |_| press());
}
if let Some(id) = &row.item.id {
root = root.id(id.clone());
}
if let Some(key) = &row.item.key {
root = root.key(key.clone());
}
root.into()
}
pub fn render(mut self) -> Element {
let rows = std::mem::take(&mut self.rows);
let mut root = Column::new()
.part(&self.part(AudioQueuePart::Root))
.focus_group(FocusGroup::vertical().wrap(false).one_stop(true))
.describe("a11y_role", "listbox")
.describe("a11y_name", self.label.clone());
for row in rows {
root = root.child(self.row(row));
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root.into()
}
}
impl crate::ui::Styled for AudioQueue {
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 AudioQueue {
const NAME: &'static str = "audio_queue";
type Renderer = AudioQueueRenderer;
fn parts() -> crate::ui::Declared {
AudioQueuePart::declared()
}
fn states() -> crate::ui::Declared {
AudioQueueState::declared()
}
fn recipe() -> Recipe {
use AudioQueuePart::*;
use AudioQueueState::{Current, Disabled, Unavailable};
use PaletteColor::{Foreground, Highlight, Muted, MutedForeground, Ring, StateHover, StatePressed};
Recipe::new()
.base(Root, |s| s.foreground(Foreground))
.state(Disabled, Root, |s| s.opacity(OpacityLevel::Disabled))
.base(Item, |s| {
fading(
s.height(48.0)
.padding_x(8.0)
.gap(12.0)
.radius(RadiusSize::Md)
.foreground(Foreground)
.cursor(CursorIcon::Pointer),
)
})
.row_density(Selector::new(), Item, 48.0)
.hovered(Item, |s| s.veil(StateHover))
.pressed(Item, |s| s.veil(StatePressed))
.focus_visible(Item, |s| s.outline(Outline::new(BorderSize::Md, Ring).offset(-2.0)))
.state(Current, Item, |s| s.background(Highlight).cursor(CursorIcon::Default))
.state(Unavailable, Item, |s| s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default))
.base(Lead, |s| s.width(20.0))
.base(Number, |s| {
s.font_family(FontFamily::Mono)
.font_size(12.0)
.foreground(MutedForeground)
})
.within_hovered(Number, |s| s.opacity(0.0))
.base(LeadIcon, |s| s.square(14.0).foreground(Foreground).opacity(0.0))
.within_hovered(LeadIcon, |s| s.opacity(1.0))
.state(AudioQueueState::Playing, LeadIcon, |s| s.square(16.0).opacity(1.0))
.base(Media, |s| s.square(32.0).radius(RadiusSize::Sm).background(Muted))
.base(MediaIcon, |s| s.square(16.0).foreground(MutedForeground))
.base(Text, |s| s.gap(2.0))
.base(Title, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.weight(FontWeight::Medium)
})
.state(Current, Title, |s| s.weight(FontWeight::SemiBold))
.base(Description, |s| {
s.typography(TypographyStyle::Body)
.font_size(12.0)
.foreground(MutedForeground)
})
.base(Duration, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(More, |s| s.opacity(0.0))
.within(More, |s| s.opacity(1.0))
}
}