use std::sync::Arc;
use super::{
Menu, MenuItem, Skeleton, SkeletonAnimation, SkeletonPart, Tooltip, icons, names,
part_style::{Length, PartAnimation, PartTransition},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{fading, glyph, pressable},
theme::{Themed, current_theme},
};
use crate::{
animation::Transition,
app::{
component::Component,
ctx::{Ctx, Placement},
events::MouseEvent,
theme::{MotionDuration, MotionEasing, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::{Column, Row, Stack},
core::{ElementRef, PictureError, Signal},
layout::{
Alignment, StackAlignment,
layout_kind::{Justify, SizeBounds},
text_style::{FontStyle, FontWeight, TextAlign},
},
node::{
CursorIcon, Element, EventHandler, HitTestBehavior, IntoMouseEventHandler, NodeUpdate, border::Border,
color::Color, dimension::Dimension, outline::Outline,
},
};
pub const PICTURE_LARGE_FROM: f32 = 240.0;
pub const PICTURE_SMALL_UP_TO: f32 = 96.0;
pub const PICTURE_SMALLEST_UP_TO: f32 = 40.0;
const WIDE: f32 = 16.0 / 9.0;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PictureSize {
Xs,
Sm,
Md,
#[default]
Lg,
}
names!(PictureSize {
Xs => "xs",
Sm => "sm",
Md => "md",
Lg => "lg",
});
impl PictureSize {
const ALL: [Self; 4] = [Self::Xs, Self::Sm, Self::Md, Self::Lg];
pub fn for_width(width: f32) -> Self {
if width <= PICTURE_SMALLEST_UP_TO {
Self::Xs
} else if width <= PICTURE_SMALL_UP_TO {
Self::Sm
} else if width < PICTURE_LARGE_FROM {
Self::Md
} else {
Self::Lg
}
}
pub fn bounds(self) -> SizeBounds {
match self {
Self::Xs => SizeBounds::new().max_width(PICTURE_SMALLEST_UP_TO),
Self::Sm => SizeBounds::new()
.above_width(PICTURE_SMALLEST_UP_TO)
.max_width(PICTURE_SMALL_UP_TO),
Self::Md => SizeBounds::new()
.above_width(PICTURE_SMALL_UP_TO)
.below_width(PICTURE_LARGE_FROM),
Self::Lg => SizeBounds::new().min_width(PICTURE_LARGE_FROM),
}
}
fn of(name: Name) -> Self {
Self::ALL
.into_iter()
.find(|size| Name::from(*size) == name)
.unwrap_or_default()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PictureFit {
#[default]
Cover,
Contain,
Fill,
None,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PictureShape {
#[default]
Rounded,
Circle,
}
#[derive(Clone, Debug, Default)]
pub enum PicturePlaceholder {
#[default]
Skeleton,
Blur(PictureSmall),
None,
}
impl PicturePlaceholder {
pub fn blur(source: impl Into<crate::resources::Source>) -> Self {
Self::Blur(PictureSmall(Source::Encoded {
source: source.into(),
cap: None,
}))
}
#[cfg(feature = "raster")]
pub fn blur_pixels(data: crate::images::ImageData) -> Self {
Self::Blur(PictureSmall(Source::Data(data)))
}
}
#[derive(Clone)]
pub struct PictureSmall(#[cfg_attr(not(feature = "raster"), allow(dead_code))] Source);
impl std::fmt::Debug for PictureSmall {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("PictureSmall")
}
}
#[cfg(feature = "raster")]
const BLUR: f32 = 24.0;
#[cfg(feature = "raster")]
const BLUR_OVERDRAW: f32 = 1.25;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PicturePart {
Figure,
Root,
Image,
Edge,
StandIn,
Sheen,
Veil,
Overlay,
Center,
Mark,
Label,
ErrorIcon,
ErrorLabel,
ErrorDescription,
Retry,
Progress,
Track,
Fill,
ProgressLabel,
ProgressLine,
Count,
Top,
Select,
SelectIcon,
Controls,
Text,
Title,
Description,
Actions,
Control,
ControlIcon,
MoreMenu,
Caption,
}
names!(PicturePart {
Figure => "figure",
Root => "root",
Image => "image",
Edge => "edge",
StandIn => "stand_in",
Sheen => "sheen",
Veil => "veil",
Overlay => "overlay",
Center => "center",
Mark => "mark",
Label => "label",
ErrorIcon => "error_icon",
ErrorLabel => "error_label",
ErrorDescription => "error_description",
Retry => "retry",
Progress => "progress",
Track => "track",
Fill => "fill",
ProgressLabel => "progress_label",
ProgressLine => "progress_line",
Count => "count",
Top => "top",
Select => "select",
SelectIcon => "select_icon",
Controls => "controls",
Text => "text",
Title => "title",
Description => "description",
Actions => "actions",
Control => "control",
ControlIcon => "control_icon",
MoreMenu => "more_menu",
Caption => "caption",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum PictureVariant {
#[default]
Desktop,
Phone,
}
names!(PictureVariant {
Desktop => "desktop",
Phone => "phone",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PictureState {
Bare,
Circle,
Pressable,
Selectable,
Selected,
Disabled,
Shown,
On,
}
names!(PictureState {
Bare => "bare",
Circle => "circle",
Pressable => "pressable",
Selectable => "selectable",
Selected => "selected",
Disabled => "disabled",
Shown => "shown",
On => "on",
});
pub type PictureRenderer = Arc<dyn Fn(PictureView) -> Element + Send + Sync>;
type Action = Arc<dyn Fn() + Send + Sync>;
type Told<T> = Arc<dyn Fn(T) + Send + Sync>;
#[derive(Clone)]
enum Source {
None,
#[cfg(feature = "raster")]
Data(crate::images::ImageData),
Encoded {
source: crate::resources::Source,
cap: Option<(u32, u32)>,
},
}
#[derive(Clone)]
enum Phase {
Empty,
#[cfg(feature = "raster")]
Ready(crate::images::ImageData),
#[cfg_attr(not(feature = "image"), allow(dead_code))]
Loading(Option<(u64, u64)>),
Failed(PictureError),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PictureLoad {
pub fraction: f64,
pub bytes: Option<(u64, u64)>,
}
impl PictureLoad {
fn text(self) -> String {
let percent = format!("{}%", (self.fraction * 100.0).round());
match self.bytes {
Some((loaded, total)) => {
let locale = super::current_locale();
let megabytes = |bytes: u64| format!("{:.1}", bytes as f64 / (1024.0 * 1024.0));
let total = crate::core::fill(&locale.fields.megabytes, &[("size", &megabytes(total))]);
let said = crate::core::fill(
&locale.common.place_of,
&[("at", &megabytes(loaded)), ("total", &total)],
);
format!("{percent} · {said}")
}
None => percent,
}
}
}
#[cfg(not(feature = "image"))]
const NO_CODECS: &str = "this build has no `image` feature: it decodes no picture";
#[derive(Clone, PartialEq)]
struct Words {
error_description: Arc<str>,
retry: Arc<str>,
download: Arc<str>,
more: Arc<str>,
open: Arc<str>,
}
impl Default for Words {
fn default() -> Self {
let locale = super::current_locale();
let words = &locale.common;
Self {
error_description: words.picture_failed.clone(),
retry: words.try_again.clone(),
download: words.download.clone(),
more: words.more.clone(),
open: words.open.clone(),
}
}
}
#[derive(Clone)]
pub struct Picture {
source: Source,
label: Option<Arc<str>>,
decorative: bool,
width: Option<Length>,
height: Option<Length>,
aspect_ratio: Option<f32>,
fit: PictureFit,
anchor: StackAlignment,
shape: PictureShape,
bare: bool,
size: Option<Name>,
variant: Option<Name>,
placeholder: PicturePlaceholder,
loading: bool,
progress: Option<f64>,
progress_text: Option<Arc<dyn Fn(PictureLoad) -> String + Send + Sync>>,
words: Words,
on_retry: Vec<Action>,
on_load: Vec<Action>,
on_error: Vec<Told<PictureError>>,
fallback: Option<Arc<dyn Fn() -> Element + Send + Sync>>,
caption: Option<Arc<str>>,
title: Option<Arc<str>>,
description: Option<Arc<str>>,
badge: Option<Element>,
on_download: Vec<Action>,
menu_items: Vec<MenuItem>,
actions: Vec<Element>,
bar: bool,
force_bar_shown: Option<bool>,
children: Vec<Element>,
count: Option<Arc<str>>,
on_click: Vec<EventHandler<MouseEvent>>,
selectable: bool,
selected: bool,
on_change: Vec<Told<bool>>,
lightbox: bool,
open: Option<Signal<bool>>,
on_open_change: Vec<Told<bool>>,
disabled: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Picture {
fn of(source: Source) -> Self {
Self {
source,
label: None,
decorative: false,
width: None,
height: None,
aspect_ratio: None,
fit: PictureFit::default(),
anchor: StackAlignment::Center,
shape: PictureShape::default(),
bare: false,
size: None,
variant: None,
placeholder: PicturePlaceholder::default(),
loading: false,
progress: None,
progress_text: None,
words: Words::default(),
on_retry: Vec::new(),
on_load: Vec::new(),
on_error: Vec::new(),
fallback: None,
caption: None,
title: None,
description: None,
badge: None,
on_download: Vec::new(),
menu_items: Vec::new(),
actions: Vec::new(),
bar: true,
force_bar_shown: None,
children: Vec::new(),
count: None,
on_click: Vec::new(),
selectable: false,
selected: false,
on_change: Vec::new(),
lightbox: false,
open: None,
on_open_change: Vec::new(),
disabled: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
#[cfg(feature = "raster")]
pub fn new(data: crate::images::ImageData) -> Self {
Self::of(Source::Data(data))
}
pub fn empty() -> Self {
Self::of(Source::None)
}
pub fn from_source(source: impl Into<crate::resources::Source>) -> Self {
Self::of(Source::Encoded {
source: source.into(),
cap: None,
})
}
pub fn from_file(path: impl Into<std::path::PathBuf>) -> Self {
Self::from_source(crate::resources::Source::file(path))
}
pub fn from_bytes(bytes: impl Into<Arc<[u8]>>) -> Self {
Self::from_source(crate::resources::Source::bytes(bytes))
}
pub fn from_resource(path: &str) -> Self {
Self::from_source(crate::resources::Source::resource(path))
}
pub fn from_url(url: &str) -> Self {
Self::from_source(crate::resources::Source::url(url))
}
pub fn cache_key(mut self, key: u64) -> Self {
if let Source::Encoded { source, .. } = &mut self.source {
*source = source.clone().key(key);
}
self
}
pub fn downscale_to(mut self, width: u32, height: u32) -> Self {
if let Source::Encoded { cap, .. } = &mut self.source {
*cap = Some((width, height));
}
self
}
pub(crate) fn source_key(&self) -> Option<u64> {
match &self.source {
Source::Encoded { source, .. } => Some(source.cache_key()),
_ => None,
}
}
#[cfg(feature = "raster")]
pub fn pixels(&self) -> Option<crate::images::ImageData> {
match &self.source {
Source::None => None,
Source::Data(data) => Some(data.clone()),
#[cfg(feature = "image")]
Source::Encoded { source, cap } => {
use crate::images::{ImageKey, ImageSizeCap, decoded_images};
let cap = cap.map(|(width, height)| ImageSizeCap::new(width, height));
decoded_images()
.state(ImageKey::new(source.cache_key()), cap)?
.ready()
.cloned()
}
#[cfg(not(feature = "image"))]
Source::Encoded { .. } => None,
}
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn decorative(mut self, decorative: bool) -> Self {
self.decorative = decorative;
self
}
pub fn width(mut self, width: impl Into<Length>) -> Self {
self.width = Some(width.into());
self
}
pub fn height(mut self, height: impl Into<Length>) -> Self {
self.height = Some(height.into());
self
}
pub fn size_px(self, width: f32, height: f32) -> Self {
self.width(width).height(height)
}
pub fn aspect_ratio(mut self, ratio: f32) -> Self {
self.aspect_ratio = Some(ratio);
self
}
pub fn fit(mut self, fit: PictureFit) -> Self {
self.fit = fit;
self
}
pub fn anchor(mut self, anchor: StackAlignment) -> Self {
self.anchor = anchor;
self
}
pub fn shape(mut self, shape: PictureShape) -> Self {
self.shape = shape;
self
}
pub fn bare(mut self, bare: bool) -> Self {
self.bare = bare;
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = Some(size.into());
self
}
pub fn placeholder(mut self, placeholder: PicturePlaceholder) -> Self {
self.placeholder = placeholder;
self
}
pub fn loading(mut self, loading: bool) -> Self {
self.loading = loading;
self
}
pub fn progress(mut self, progress: impl Into<Option<f64>>) -> Self {
self.progress = progress.into().map(|progress| progress.clamp(0.0, 1.0));
self
}
pub fn progress_text(mut self, text: impl Fn(PictureLoad) -> String + Send + Sync + 'static) -> Self {
self.progress_text = Some(Arc::new(text));
self
}
pub fn error_description(mut self, description: &str) -> Self {
self.words.error_description = Arc::from(description);
self
}
pub fn retry_label(mut self, label: &str) -> Self {
self.words.retry = Arc::from(label);
self
}
pub fn download_label(mut self, label: &str) -> Self {
self.words.download = Arc::from(label);
self
}
pub fn open_label(mut self, label: &str) -> Self {
self.words.open = Arc::from(label);
self
}
pub fn more_label(mut self, label: &str) -> Self {
self.words.more = Arc::from(label);
self
}
pub fn on_retry(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_retry.push(Arc::new(handler));
self
}
pub(crate) fn fallback(mut self, fallback: impl Fn() -> Element + Send + Sync + 'static) -> Self {
self.fallback = Some(Arc::new(fallback));
self
}
pub fn on_load(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_load.push(Arc::new(handler));
self
}
pub fn on_error(mut self, handler: impl Fn(&PictureError) + Send + Sync + 'static) -> Self {
self.on_error.push(Arc::new(move |error: PictureError| handler(&error)));
self
}
pub fn caption(mut self, caption: &str) -> Self {
self.caption = Some(Arc::from(caption));
self
}
pub fn title(mut self, title: &str) -> Self {
self.title = Some(Arc::from(title));
self
}
pub fn description(mut self, description: &str) -> Self {
self.description = Some(Arc::from(description));
self
}
pub fn badge(mut self, badge: impl Into<Element>) -> Self {
self.badge = Some(badge.into());
self
}
pub fn on_download(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_download.push(Arc::new(handler));
self
}
pub fn menu_item(mut self, item: MenuItem) -> Self {
self.menu_items.push(item);
self
}
pub fn menu_items(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
self.menu_items.extend(items);
self
}
pub fn action(mut self, action: impl Into<Element>) -> Self {
self.actions.push(action.into());
self
}
pub fn actions(mut self, actions: impl IntoIterator<Item = impl Into<Element>>) -> Self {
self.actions.extend(actions.into_iter().map(Into::into));
self
}
pub fn bar(mut self, bar: bool) -> Self {
self.bar = bar;
self
}
pub fn force_bar_shown(mut self, shown: Option<bool>) -> Self {
self.force_bar_shown = shown;
self
}
pub fn child(mut self, child: impl Into<Element>) -> Self {
self.children.push(child.into());
self
}
pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Element>>) -> Self {
self.children.extend(children.into_iter().map(Into::into));
self
}
pub(crate) fn count(mut self, count: &str) -> Self {
self.count = Some(Arc::from(count));
self
}
pub fn on_click(mut self, handler: impl IntoMouseEventHandler) -> Self {
self.on_click.push(handler.into_event_handler());
self
}
pub fn selectable(mut self, selectable: bool) -> Self {
self.selectable = selectable;
self
}
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
pub fn on_change(mut self, handler: impl Fn(bool) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = Some(variant.into());
self
}
pub fn lightbox(mut self, lightbox: bool) -> Self {
self.lightbox = lightbox;
self
}
pub fn open(mut self, open: Signal<bool>) -> Self {
self.open = Some(open);
self
}
pub fn on_open_change(mut self, handler: impl Fn(bool) + Send + Sync + 'static) -> Self {
self.on_open_change.push(Arc::new(handler));
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(super::PartStyle) -> super::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 key = self.key.clone();
let props = PictureProps(self);
match key {
Some(key) => ctx.mount_keyed::<PictureHost>(&key, props),
None => ctx.mount::<PictureHost>(props),
}
}
#[cfg(feature = "image")]
pub(crate) fn fetch(&self, loader: Option<&crate::resources::Loader>) -> Option<crate::resources::Load> {
use crate::{
images::{ImageKey, ImageSizeCap, ImageSource, decoded_images},
resources::{LoadState, SourceKind},
};
let Source::Encoded { source, cap } = &self.source else {
return None;
};
let key = ImageKey::new(source.cache_key());
let cap = cap.map(|(width, height)| ImageSizeCap::new(width, height));
let decode = |from: ImageSource| {
decoded_images().load(key, cap, || from, None);
};
match &source.kind {
SourceKind::Bytes(bytes) => decode(ImageSource::Bytes(bytes.clone())),
SourceKind::File(path) => decode(ImageSource::File(path.clone())),
SourceKind::Resource(_) | SourceKind::Url(_) => {
if decoded_images().state(key, cap).is_some() {
return None;
}
let load = loader?.load(source);
match load.state() {
LoadState::Loading { .. } => return Some(load),
LoadState::Ready(bytes) => decode(ImageSource::Bytes(bytes)),
LoadState::Failed(_) => {}
}
}
}
None
}
pub(crate) fn in_viewer(mut self) -> Self {
self = self.stripped();
self.width = Some(Length::Fill);
self.height = Some(Length::Fill);
self.aspect_ratio = None;
self.fit = PictureFit::Contain;
self.shape = PictureShape::Rounded;
self.bare = true;
self.size = Some(PictureSize::Lg.into());
self
}
pub(crate) fn as_thumb(mut self, width: f32, height: f32) -> Self {
self = self.stripped();
self.width = Some(Length::Px(width));
self.height = Some(Length::Px(height));
self.aspect_ratio = None;
self.fit = PictureFit::Cover;
self.bare = true;
self.size = None;
self.decorative = true;
if let Source::Encoded { cap, .. } = &mut self.source
&& cap.is_none()
{
let side = (width.max(height) * 4.0).ceil() as u32;
*cap = Some((side, side));
}
self
}
pub(crate) fn in_grid(mut self) -> Self {
self = self.stripped();
self.width = Some(Length::Fill);
self.height = Some(Length::Fill);
self.aspect_ratio = None;
self.fit = PictureFit::Cover;
self
}
fn stripped(mut self) -> Self {
self.caption = None;
self.badge = None;
self.bar = false;
self.force_bar_shown = None;
self.children.clear();
self.count = None;
self.on_click.clear();
self.selectable = false;
self.selected = false;
self.on_change.clear();
self.lightbox = false;
self.open = None;
self.on_open_change.clear();
self.id = None;
self.key = None;
self
}
pub(crate) fn caption_of(&self) -> (Option<Arc<str>>, Option<Arc<str>>) {
(self.title.clone(), self.description.clone())
}
pub(crate) fn label_of(&self) -> Option<Arc<str>> {
self.label.clone().or_else(|| self.title.clone())
}
fn pressable(&self) -> bool {
!self.disabled && (self.selectable || self.lightbox || !self.on_click.is_empty())
}
fn forms(&self, theme: &Theme, narrowed: Option<PictureSize>) -> Vec<(PictureSize, Option<SizeBounds>)> {
if let Some(size) = self.size {
return vec![(PictureSize::of(size), None)];
}
match self.width.and_then(|width| width.resolve(theme)) {
Some(Dimension::Px(width)) => vec![(narrowed.unwrap_or(PictureSize::for_width(width)), None)],
None if self.aspect_ratio.is_none() => vec![(PictureSize::Lg, None)],
_ => PictureSize::ALL
.into_iter()
.map(|size| (size, Some(size.bounds())))
.collect(),
}
}
}
#[cfg(feature = "raster")]
impl From<crate::images::ImageData> for Picture {
fn from(data: crate::images::ImageData) -> Self {
Self::new(data)
}
}
impl From<Picture> for Element {
fn from(picture: Picture) -> Self {
let key = picture.key.clone();
let props = PictureProps(picture);
match key {
Some(key) => Element::component_keyed::<PictureHost>(key, props),
None => Element::component::<PictureHost>(props),
}
}
}
#[derive(Clone)]
struct PictureProps(Picture);
impl PartialEq for PictureProps {
fn eq(&self, other: &Self) -> bool {
match (self.0.plain(), other.0.plain()) {
(Some(this), Some(that)) => this == that,
_ => false,
}
}
}
#[derive(PartialEq)]
enum SourceId {
None,
#[cfg(feature = "raster")]
Data(u64),
Encoded(u64, Option<(u32, u32)>),
}
impl Source {
fn id(&self) -> SourceId {
match self {
Source::None => SourceId::None,
#[cfg(feature = "raster")]
Source::Data(data) => SourceId::Data(data.id()),
Source::Encoded { source, cap } => SourceId::Encoded(source.cache_key(), *cap),
}
}
}
#[derive(PartialEq)]
struct Plain<'a> {
source: SourceId,
placeholder: (u8, SourceId),
texts: [&'a Option<Arc<str>>; 7],
words: &'a Words,
lengths: (&'a Option<Length>, &'a Option<Length>, Option<f32>),
shown: (
PictureFit,
StackAlignment,
PictureShape,
&'a Option<Name>,
&'a Option<Name>,
&'a [Name],
),
flags: [bool; 8],
open: Option<usize>,
load: (Option<f64>, Option<bool>, Option<Interaction>),
}
impl Picture {
fn plain(&self) -> Option<Plain<'_>> {
let Picture {
source,
label,
decorative,
width,
height,
aspect_ratio,
fit,
anchor,
shape,
bare,
size,
variant,
placeholder,
loading,
progress,
progress_text,
words,
on_retry,
on_load,
on_error,
fallback,
caption,
title,
description,
badge,
on_download,
menu_items,
actions,
bar,
force_bar_shown,
children,
count,
on_click,
selectable,
selected,
on_change,
lightbox,
open,
on_open_change,
disabled,
states,
rules,
forced,
id,
key,
} = self;
let made_anew = progress_text.is_some()
|| fallback.is_some()
|| badge.is_some()
|| !(on_retry.is_empty()
&& on_load.is_empty()
&& on_error.is_empty()
&& on_download.is_empty()
&& menu_items.is_empty()
&& actions.is_empty()
&& children.is_empty()
&& on_click.is_empty()
&& on_change.is_empty()
&& on_open_change.is_empty()
&& rules.is_empty());
if made_anew {
return None;
}
Some(Plain {
source: source.id(),
placeholder: match placeholder {
PicturePlaceholder::Skeleton => (0, SourceId::None),
PicturePlaceholder::None => (1, SourceId::None),
PicturePlaceholder::Blur(PictureSmall(small)) => (2, small.id()),
},
texts: [label, caption, title, description, count, id, key],
words,
lengths: (width, height, *aspect_ratio),
shown: (*fit, *anchor, *shape, size, variant, states),
flags: [
*decorative,
*bare,
*loading,
*bar,
*selectable,
*selected,
*disabled,
*lightbox,
],
open: open.as_ref().map(Signal::id),
load: (*progress, *force_bar_shown, *forced),
})
}
}
impl crate::app::component::DevtoolsInspectable for PictureProps {}
#[derive(Clone)]
struct Live {
menu: Signal<bool>,
more: ElementRef,
viewer: Signal<bool>,
sheet: Signal<bool>,
tick: Signal<u64>,
wake: Action,
held: Arc<parking_lot::Mutex<Option<(u64, crate::resources::Load)>>>,
#[cfg_attr(not(feature = "image"), allow(dead_code))]
shows: Arc<std::sync::atomic::AtomicBool>,
_watching: Arc<crate::core::VisibilityObserver>,
held_small: Arc<parking_lot::Mutex<Option<(u64, crate::resources::Load)>>>,
told: Arc<parking_lot::Mutex<Option<(u64, bool)>>>,
news: Arc<parking_lot::Mutex<Vec<Action>>>,
frame: ElementRef,
said: Arc<parking_lot::Mutex<Option<f32>>>,
narrowed: Signal<Option<PictureSize>>,
}
struct PictureHost {
live: Live,
}
impl Component for PictureHost {
type Props = PictureProps;
fn create(ctx: &mut Ctx) -> Self {
let tick = ctx.signal(0u64);
let wake: Action = {
let tick = tick.clone();
Arc::new(move || tick.set(tick.get_untracked().wrapping_add(1)))
};
let (frame, said, narrowed) = (
ElementRef::new(),
Arc::new(parking_lot::Mutex::new(None::<f32>)),
ctx.signal(None::<PictureSize>),
);
{
let (said, narrowed) = (said.clone(), narrowed.clone());
frame.observe_rect_before_paint(move |rect| {
let want = match *said.lock() {
Some(width) if rect.width + 0.5 < width => {
let form = PictureSize::for_width(rect.width);
(form != PictureSize::for_width(width)).then_some(form)
}
_ => None,
};
if narrowed.get_untracked() != want {
narrowed.set(want);
}
});
}
type Held = Arc<parking_lot::Mutex<Option<(u64, crate::resources::Load)>>>;
let (held, held_small): (Held, Held) = (Arc::default(), Arc::default());
let shows = Arc::new(std::sync::atomic::AtomicBool::new(false));
let watching = frame.observe_visibility(crate::core::VisibilityOptions::new(), {
let (shows, loads) = (shows.clone(), [held.clone(), held_small.clone()]);
move |seen| {
shows.store(seen.visible, std::sync::atomic::Ordering::Relaxed);
let priority = if seen.visible {
crate::resources::LoadPriority::High
} else {
crate::resources::LoadPriority::Normal
};
for held in &loads {
if let Some((_, load)) = &*held.lock() {
load.set_priority(priority);
}
}
}
});
Self {
live: Live {
menu: ctx.signal(false),
more: ElementRef::new(),
viewer: ctx.signal(false),
sheet: ctx.signal(false),
tick,
wake,
held,
held_small,
shows,
_watching: Arc::new(watching),
told: Arc::default(),
news: Arc::default(),
frame,
said,
narrowed,
},
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let picture = ctx.props::<PictureProps>().0.clone();
let theme = current_theme();
*self.live.said.lock() = match (picture.size, picture.width.and_then(|width| width.resolve(&theme))) {
(None, Some(Dimension::Px(width))) => Some(width),
_ => None,
};
self.live.tick.get();
let phase = self.phase(&picture, ctx);
self.tell(&picture, &phase);
let loader = ctx.app_handle().map(|app| app.loader().clone());
#[cfg(feature = "raster")]
let small = self.small(&picture, &phase, ctx);
#[cfg_attr(not(feature = "raster"), allow(unused_mut))]
let mut view = view(picture, &theme, &self.live, phase, loader, Some(ctx));
#[cfg(feature = "raster")]
{
view.small = small;
}
view.render_themed()
}
fn after_layout(&self) {
let news = std::mem::take(&mut *self.live.news.lock());
news.iter().for_each(|tell| tell());
}
fn on_unmounted(&self) {
*self.live.held.lock() = None;
*self.live.held_small.lock() = None;
}
}
impl PictureHost {
fn phase(&self, picture: &Picture, ctx: &Ctx) -> Phase {
match &picture.source {
Source::None => Phase::Empty,
#[cfg(feature = "raster")]
Source::Data(data) => Phase::Ready(data.clone()),
#[cfg(not(feature = "image"))]
Source::Encoded { .. } => {
let _ = ctx;
Phase::Failed(PictureError::Unavailable(Arc::from(NO_CODECS)))
}
#[cfg(feature = "image")]
Source::Encoded { source, cap } => self.decoded(source, *cap, ctx, &self.live.held),
}
}
#[cfg(feature = "raster")]
fn small(&self, picture: &Picture, phase: &Phase, ctx: &Ctx) -> Option<crate::images::ImageData> {
let waits = picture.loading || matches!(phase, Phase::Loading(_));
let PicturePlaceholder::Blur(PictureSmall(small)) = &picture.placeholder else {
return None;
};
if !waits {
*self.live.held_small.lock() = None;
return None;
}
match small {
Source::Data(data) => Some(data.clone()),
#[cfg(feature = "image")]
Source::Encoded { source, cap } => match self.decoded(source, *cap, ctx, &self.live.held_small) {
Phase::Ready(data) => Some(data),
_ => None,
},
_ => {
let _ = ctx;
None
}
}
}
#[cfg(feature = "image")]
fn decoded(
&self,
source: &crate::resources::Source,
cap: Option<(u32, u32)>,
ctx: &Ctx,
held: &parking_lot::Mutex<Option<(u64, crate::resources::Load)>>,
) -> Phase {
use crate::{
images::{ImageKey, ImageLoadState, ImageSizeCap, ImageSource, decoded_images},
resources::{LoadState, SourceKind},
};
let key = ImageKey::new(source.cache_key());
let cap = cap.map(|(width, height)| ImageSizeCap::new(width, height));
let wake = &self.live.wake;
let decode = |from: ImageSource| match decoded_images().load(key, cap, || from, Some(wake.clone())) {
ImageLoadState::Loading => Phase::Loading(None),
ImageLoadState::Ready(data) => Phase::Ready(data),
ImageLoadState::Failed(error) => Phase::Failed(error.kind().clone()),
};
match &source.kind {
SourceKind::Bytes(bytes) => decode(ImageSource::Bytes(bytes.clone())),
SourceKind::File(path) => decode(ImageSource::File(path.clone())),
SourceKind::Resource(_) | SourceKind::Url(_) => {
let mut held = held.lock();
match decoded_images().state(key, cap) {
Some(ImageLoadState::Ready(data)) => {
*held = None;
return Phase::Ready(data);
}
Some(ImageLoadState::Failed(error)) => {
*held = None;
return Phase::Failed(error.kind().clone());
}
_ => {}
}
let load = match &*held {
Some((of, load)) if *of == source.cache_key() => load.clone(),
_ => {
let Some(app) = ctx.app_handle() else {
return Phase::Failed(PictureError::Unavailable(Arc::from(
"the picture is in no app: nothing loads it",
)));
};
let load = app.loader().load(source);
if self.live.shows.load(std::sync::atomic::Ordering::Relaxed) {
load.set_priority(crate::resources::LoadPriority::High);
}
*held = Some((source.cache_key(), load.clone()));
load
}
};
load.wake_with(wake.clone());
match load.state() {
LoadState::Loading { loaded, total } => Phase::Loading(total.map(|total| (loaded, total))),
LoadState::Failed(error) => Phase::Failed(load_failed(error, source.is_remote())),
LoadState::Ready(bytes) => decode(ImageSource::Bytes(bytes)),
}
}
}
}
fn tell(&self, picture: &Picture, phase: &Phase) {
let came = match phase {
#[cfg(feature = "raster")]
Phase::Ready(_) => true,
Phase::Failed(_) => false,
Phase::Empty | Phase::Loading(_) => return,
};
let key = match &picture.source {
Source::Encoded { source, .. } => source.cache_key(),
_ => 0,
};
let mut told = self.live.told.lock();
if *told == Some((key, came)) {
return;
}
*told = Some((key, came));
let mut news = self.live.news.lock();
match phase {
Phase::Failed(error) => news.extend(picture.on_error.iter().map(|handler| {
let (handler, error) = (handler.clone(), error.clone());
Arc::new(move || handler(error.clone())) as Action
})),
_ => news.extend(picture.on_load.iter().cloned()),
}
}
}
#[cfg(feature = "image")]
fn load_failed(error: crate::resources::LoadError, remote: bool) -> PictureError {
use crate::resources::LoadError;
match error {
LoadError::NotFound => PictureError::NotFound,
LoadError::Denied => PictureError::Denied,
LoadError::Status(status) => PictureError::Server(status),
LoadError::TooLarge { .. } => PictureError::TooLarge,
LoadError::TimedOut => PictureError::TimedOut,
LoadError::Unsupported(why) => PictureError::Unavailable(Arc::from(why)),
LoadError::Io(said) if remote => PictureError::Network(Arc::from(said)),
LoadError::Io(said) => PictureError::Other(Arc::from(said)),
LoadError::Cancelled => PictureError::Other(Arc::from("the load was stopped")),
}
}
fn layer() -> Stack {
Stack::new().size(Dimension::Pct(100.0), Dimension::Pct(100.0))
}
#[derive(Clone, Copy)]
struct Known {
width: bool,
height: bool,
}
impl Known {
fn stand_in(self) -> Stack {
let full = Dimension::Pct(100.0);
let stack = Stack::new().stack_align(StackAlignment::Center);
match (self.width, self.height) {
(true, true) => stack.size(full, full),
(true, false) => stack.width(full).aspect_ratio(WIDE),
(false, true) => stack.height(full).aspect_ratio(WIDE),
(false, false) => stack,
}
}
}
#[derive(Clone)]
pub struct PictureForm {
pub size: PictureSize,
pub bounds: Option<SizeBounds>,
pub recipe: ResolvedRecipe,
on_recipe: ResolvedRecipe,
}
impl PictureForm {
fn part(&self, part: PicturePart) -> ResolvedPart {
self.recipe.part(part)
}
fn placed(&self, layer: Stack) -> Stack {
layer.drop_outside(self.bounds.unwrap_or_default())
}
}
fn empty_center(form: &PictureForm, label: Option<&Arc<str>>) -> Element {
let mark = glyph(&form.part(PicturePart::Mark), Name::new(icons::IMAGE), false);
let mut center = middle(form).child(mark);
if let (Some(label), PictureSize::Md | PictureSize::Lg) = (label, form.size) {
center = center.child(wrapped(&form.part(PicturePart::Label), label));
}
center.into()
}
fn middle(form: &PictureForm) -> Column {
Column::new()
.part(&form.part(PicturePart::Center))
.size(Dimension::Pct(100.0), Dimension::Pct(100.0))
.align_items(Alignment::Center)
.justify(Justify::Center)
}
fn wrapped(part: &ResolvedPart, text: &str) -> Element {
Column::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.child(
part
.text(text)
.text_align(TextAlign::Center)
.width(Dimension::Pct(100.0))
.part(part),
)
.into()
}
fn rail(track: &ResolvedPart, fill: &ResolvedPart, progress: f64) -> Row {
Row::new().part(track).clip().child(
Row::new()
.part(fill)
.size(Dimension::Pct(progress as f32 * 100.0), Dimension::Pct(100.0)),
)
}
fn view(
picture: Picture,
theme: &Theme,
live: &Live,
phase: Phase,
loader: Option<crate::resources::Loader>,
mut ctx: Option<&mut Ctx>,
) -> PictureView {
let pressable = picture.pressable();
let phone = match picture.variant {
Some(variant) => variant == Name::from(PictureVariant::Phone),
None => super::touch_form(),
};
let bar_has = picture.title.is_some()
|| picture.description.is_some()
|| (!phone
&& (!picture.actions.is_empty()
|| !picture.on_download.is_empty()
|| !picture.menu_items.is_empty()
|| picture.lightbox));
let menu_open = live.menu.get();
let case = |size: PictureSize, on: bool| {
Case {
variant: Some(if phone { PictureVariant::Phone } else { PictureVariant::Desktop }.into()),
size: Some(size.into()),
density: None,
breakpoint: super::current_breakpoint(),
states: picture.states.clone(),
}
.state(PictureState::Bare, picture.bare)
.state(PictureState::Circle, picture.shape == PictureShape::Circle)
.state(PictureState::Pressable, pressable)
.state(PictureState::Selectable, picture.selectable)
.state(PictureState::Selected, picture.selected)
.state(PictureState::Disabled, picture.disabled)
.state(
PictureState::Shown,
picture.force_bar_shown.unwrap_or(menu_open || phone) && picture.force_bar_shown != Some(false),
)
.state(PictureState::On, on)
};
let sizes = picture.forms(theme, live.narrowed.get());
let owner = sizes.first().map(|(size, _)| {
theme
.resolve::<Picture>(&case(*size, false), Some(&picture.rules))
.owned_by(picture.id.as_ref())
});
let forms: Vec<PictureForm> = sizes
.into_iter()
.map(|(size, bounds)| {
let resolve = |on: bool| {
let recipe = theme.resolve::<Picture>(&case(size, on), Some(&picture.rules));
match &owner {
Some(owner) => recipe.owned_like(owner),
None => recipe,
}
};
PictureForm {
size,
bounds,
recipe: resolve(false),
on_recipe: resolve(true),
}
})
.collect();
let id = |suffix: &str| picture.id.as_ref().map(|id| format!("{id}-{suffix}"));
let mut bars = Vec::with_capacity(forms.len());
for form in &forms {
let shown = picture.bar && bar_has && picture.force_bar_shown != Some(false);
if !shown || matches!(form.size, PictureSize::Xs | PictureSize::Sm) {
bars.push(None);
continue;
}
let large = form.size == PictureSize::Lg;
let mut buttons: Vec<Element> = Vec::new();
if large && !phone {
buttons.extend(picture.actions.iter().cloned());
if !picture.on_download.is_empty() {
let handlers = picture.on_download.clone();
let press: Action = Arc::new(move || handlers.iter().for_each(|handler| handler()));
let button = control(
form,
false,
icons::DOWNLOAD,
&picture.words.download,
id("download"),
press,
);
buttons.push(tip(ctx.as_deref_mut(), button, &picture.words.download));
}
}
let mut menu = None;
if !picture.menu_items.is_empty() && !phone {
let open = live.menu.clone();
let press: Action = Arc::new(move || open.set(!open.get_untracked()));
let button = control(
form,
menu_open,
icons::MORE_HORIZONTAL,
&picture.words.more,
id("more"),
press,
);
let button = Row::new().ref_element(live.more.clone()).child(button);
buttons.push(tip(ctx.as_deref_mut(), button.into(), &picture.words.more));
menu = Some(
Menu::new(live.menu.clone(), live.more.clone())
.label(&picture.words.more)
.placement(Placement::TopEnd)
.offset(4.0)
.rules(&form.recipe.rules_for(PicturePart::MoreMenu, super::MenuPart::Panel))
.items(picture.menu_items.iter().cloned())
.build(theme),
);
}
if large && picture.lightbox && !phone {
let open = picture.open.clone().unwrap_or_else(|| live.viewer.clone());
let told = picture.on_open_change.clone();
let press: Action = Arc::new(move || {
if !open.get_untracked() {
open.set(true);
told.iter().for_each(|tell| tell(true));
}
});
let button = control(form, false, icons::FULLSCREEN, &picture.words.open, id("open"), press);
buttons.push(tip(ctx.as_deref_mut(), button, &picture.words.open));
}
bars.push(Some(PictureBar {
title: picture.title.clone(),
description: picture.description.clone().filter(|_| large),
buttons,
menu,
}));
}
let retry: Action = {
let handlers = picture.on_retry.clone();
let (source, live) = (picture.source.clone(), live.clone());
Arc::new(move || {
handlers.iter().for_each(|handler| handler());
#[cfg(feature = "image")]
if let Source::Encoded { source, cap } = &source {
let cap = cap.map(|(width, height)| crate::images::ImageSizeCap::new(width, height));
crate::images::decoded_images().forget(crate::images::ImageKey::new(source.cache_key()), cap);
if let Some(loader) = &loader {
loader.forget(source);
}
}
#[cfg(not(feature = "image"))]
let _ = (&source, &loader);
*live.held.lock() = None;
*live.told.lock() = None;
(live.wake)();
})
};
PictureView {
phase,
retry,
viewer: picture.open.clone().unwrap_or_else(|| live.viewer.clone()),
phone,
sheet: live.sheet.clone(),
#[cfg(feature = "raster")]
small: None,
known: Known {
width: picture.width.is_some() || picture.aspect_ratio.is_some(),
height: picture.height.is_some() || picture.aspect_ratio.is_some(),
},
pressable,
forms,
bars,
picture,
frame: live.frame.clone(),
}
}
fn control(
form: &PictureForm,
on: bool,
icon: &'static str,
label: &str,
id: Option<String>,
press: Action,
) -> Element {
let recipe = if on { &form.on_recipe } else { &form.recipe };
let mut button = pressable(&recipe.part(PicturePart::Control), false)
.describe("a11y_role", "button")
.describe("a11y_name", Arc::<str>::from(label))
.child(glyph(&recipe.part(PicturePart::ControlIcon), Name::new(icon), false))
.on_click(move |event: MouseEvent| {
event.stop_propagation();
press();
});
if let Some(id) = id {
button = button.id(id);
}
button.into()
}
fn tip(ctx: Option<&mut Ctx>, element: Element, text: &str) -> Element {
match ctx {
Some(ctx) => Tooltip::new(text)
.placement(Placement::Top)
.arrow(true)
.offset(4.0)
.mount(ctx, element),
None => element,
}
}
#[derive(Clone)]
pub struct PictureBar {
pub title: Option<Arc<str>>,
pub description: Option<Arc<str>>,
pub buttons: Vec<Element>,
pub menu: Option<Element>,
}
pub struct PictureView {
pub forms: Vec<PictureForm>,
pub bars: Vec<Option<PictureBar>>,
pub pressable: bool,
known: Known,
picture: Picture,
phase: Phase,
viewer: Signal<bool>,
#[cfg(feature = "raster")]
small: Option<crate::images::ImageData>,
retry: Action,
pub phone: bool,
sheet: Signal<bool>,
frame: ElementRef,
}
impl PictureView {
fn base(&self) -> &PictureForm {
self.forms.last().expect("a picture has a form")
}
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.base().recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.base().recipe.theme()
}
pub fn label(&self) -> Option<Arc<str>> {
(!self.picture.decorative)
.then(|| self.picture.label.clone().or_else(|| self.picture.title.clone()))
.flatten()
}
fn id(&self, suffix: &str) -> Option<String> {
self.picture.id.as_ref().map(|id| format!("{id}-{suffix}"))
}
fn render_themed(self) -> Element {
match self.theme().renderer::<Picture>() {
Some(renderer) => renderer(self),
None => self.render(),
}
}
fn loading_maker(&self) -> impl Fn(Option<(u64, u64)>) -> Element + Send + Sync + 'static {
let (forms, known) = (self.forms.clone(), self.known);
let said = self.picture.progress;
let sheen = matches!(self.picture.placeholder, PicturePlaceholder::Skeleton);
let words = self.picture.progress_text.clone();
#[cfg(feature = "raster")]
let blurred = self.small.clone().map(|data| {
let (fit, (x, y)) = (fit_of(self.picture.fit), anchor_shares(self.picture.anchor));
let part = self.part(PicturePart::Image);
move || -> Element {
#[allow(deprecated)]
let image = crate::components::Image::new(data.clone())
.fit(fit)
.image_anchor(x, y)
.part(&part)
.size(Dimension::Pct(100.0), Dimension::Pct(100.0))
.blur(BLUR)
.transform(crate::node::transform::Transform2D::scale_uniform(BLUR_OVERDRAW));
layer().child(image).into()
}
});
move |bytes: Option<(u64, u64)>| {
let load = match (said, bytes) {
(Some(fraction), _) => Some(PictureLoad { fraction, bytes }),
(None, Some((loaded, total))) if total > 0 => Some(PictureLoad {
fraction: (loaded as f64 / total as f64).clamp(0.0, 1.0),
bytes,
}),
_ => None,
};
let progress = load.map(|load| load.fraction);
let text = match (load, &words) {
(Some(load), Some(words)) => words(load),
(Some(load), None) => load.text(),
(None, _) => String::new(),
};
let mut stand_in = known.stand_in();
#[cfg(feature = "raster")]
if let Some(blurred) = &blurred {
return stand_in.child(blurred()).into();
}
for form in &forms {
let content: Option<Element> = match (progress, form.size) {
(Some(progress), PictureSize::Lg | PictureSize::Md) => {
let mut block = Column::new()
.part(&form.part(PicturePart::Progress))
.align_items(Alignment::Center)
.child(rail(
&form.part(PicturePart::Track),
&form.part(PicturePart::Fill),
progress,
));
if form.size == PictureSize::Lg {
block = block.child(form.part(PicturePart::ProgressLabel).text(&text).nowrap());
}
Some(middle(form).child(block).into())
}
(Some(progress), PictureSize::Sm) => Some(
Column::new()
.size(Dimension::Pct(100.0), Dimension::Pct(100.0))
.justify(Justify::End)
.child(rail(
&form.part(PicturePart::ProgressLine),
&form.part(PicturePart::Fill),
progress,
))
.into(),
),
(_, PictureSize::Xs) => None,
(None, _) if sheen => Some(
Skeleton::block(Length::Fill, Length::Fill)
.animation(SkeletonAnimation::Shimmer)
.rules(&form.recipe.rules_for(PicturePart::Sheen, SkeletonPart::Bone))
.build(form.recipe.theme()),
),
(None, _) => None,
};
if let Some(content) = content {
stand_in = stand_in.child(form.placed(layer().child(content)));
}
}
stand_in.into()
}
}
fn error_maker(&self) -> impl Fn() -> Element + Send + Sync + 'static {
let (forms, known) = (self.forms.clone(), self.known);
let (label, words) = (self.picture.label.clone(), self.picture.words.clone());
#[cfg(not(feature = "image"))]
let words = {
static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| tracing::warn!("{NO_CODECS}"));
Words {
error_description: Arc::from(NO_CODECS),
..words
}
};
let retry_id = self.id("retry");
let retry = self.retry.clone();
move || {
let mut stand_in = known.stand_in();
for form in &forms {
let icon = glyph(
&form.part(PicturePart::ErrorIcon),
Name::new(icons::ALERT_CIRCLE),
false,
);
let content: Element = match form.size {
PictureSize::Lg | PictureSize::Md => {
let mut text = Column::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center);
if let Some(label) = &label {
text = text.child(wrapped(&form.part(PicturePart::ErrorLabel), label));
}
if form.size == PictureSize::Lg {
text = text.child(wrapped(
&form.part(PicturePart::ErrorDescription),
&words.error_description,
));
}
let part = form.part(PicturePart::Retry);
let press = retry.clone();
let mut button = pressable(&part, false)
.describe("a11y_role", "button")
.describe("a11y_name", words.retry.clone())
.child(part.text(&words.retry).nowrap())
.on_click(move |event: MouseEvent| {
event.stop_propagation();
press();
});
if let Some(id) = &retry_id {
button = button.id(id.clone());
}
middle(form).child(icon).child(text).child(button).into()
}
PictureSize::Sm | PictureSize::Xs => {
let press = retry.clone();
let name = match &label {
Some(label) => format!("{label}. {} {}", words.error_description, words.retry),
None => format!("{} {}", words.error_description, words.retry),
};
middle(form)
.describe("a11y_role", "button")
.describe("a11y_name", name)
.cursor(CursorIcon::Pointer)
.on_click(move |event: MouseEvent| {
event.stop_propagation();
press();
})
.child(icon)
.into()
}
};
stand_in = stand_in.child(form.placed(layer().child(content)));
}
stand_in.into()
}
}
#[allow(deprecated)]
pub fn image(&self) -> Option<Element> {
#[cfg(not(feature = "raster"))]
return None;
#[cfg(feature = "raster")]
{
use crate::components::Image;
let Phase::Ready(data) = &self.phase else {
return None;
};
let (x, y) = anchor_shares(self.picture.anchor);
let image = Image::new(data.clone())
.fit(fit_of(self.picture.fit))
.image_anchor(x, y)
.part(&self.part(PicturePart::Image));
let full = Dimension::Pct(100.0);
Some(match (self.known.width, self.known.height) {
(true, true) => image.size(full, full).into(),
(true, false) => image.width(full).into(),
(false, true) => image.height(full).into(),
(false, false) => image.into(),
})
}
}
pub fn empty(&self) -> Element {
let mut stand_in = self.known.stand_in();
for form in &self.forms {
let content = empty_center(form, self.picture.label.as_ref());
stand_in = stand_in.child(form.placed(layer().child(content)));
}
stand_in.into()
}
pub fn count(&self) -> Vec<Element> {
let Some(count) = &self.picture.count else {
return Vec::new();
};
let mut layers = vec![
layer()
.part(&self.part(PicturePart::Veil))
.drop_outside(SizeBounds::new())
.pointer_events_none()
.into(),
];
for form in self.forms.iter().filter(|form| form.size != PictureSize::Xs) {
let text = form.part(PicturePart::Count).text(count).nowrap();
layers.push(
form
.placed(layer().pointer_events_none().child(middle(form).child(text)))
.into(),
);
}
layers
}
pub fn overlay(&self) -> Option<Element> {
if self.picture.children.is_empty() {
return None;
}
let mut overlay = layer()
.part(&self.part(PicturePart::Overlay))
.drop_outside(SizeBounds::new())
.hit_test(HitTestBehavior::ContentOnly)
.with_children(self.picture.children.iter().cloned());
if let Some(id) = self.id("overlay") {
overlay = overlay.id(id);
}
Some(overlay.into())
}
pub fn top(&self) -> Vec<Element> {
let picture = &self.picture;
let marked = picture.selectable || picture.selected;
let mut rows = Vec::new();
for form in &self.forms {
let badge = picture
.badge
.clone()
.filter(|_| matches!(form.size, PictureSize::Lg | PictureSize::Md));
let mark = (marked && form.size != PictureSize::Xs).then(|| {
let mut mark = Row::new()
.part(&form.part(PicturePart::Select))
.align_items(Alignment::Center)
.justify(Justify::Center);
if picture.selected {
mark = mark.child(glyph(
&form.part(PicturePart::SelectIcon),
Name::new(icons::CHECK),
false,
));
}
mark
});
if badge.is_none() && mark.is_none() {
continue;
}
let mut row = Row::new()
.part(&form.part(PicturePart::Top))
.width(Dimension::Pct(100.0))
.align_items(Alignment::Start);
if let Some(badge) = badge {
row = row.child(badge);
}
row = row.child(Row::new().flex(1.0));
if let Some(mark) = mark {
row = row.child(mark);
}
rows.push(
form
.placed(
layer()
.stack_align(StackAlignment::TopStart)
.pointer_events_none()
.child(row),
)
.into(),
);
}
rows
}
pub fn controls(&self) -> Vec<Element> {
let mut bars = Vec::new();
for (form, bar) in self.forms.iter().zip(&self.bars) {
let Some(bar) = bar else {
continue;
};
let part = form.part(PicturePart::Controls);
let end = part
.rest()
.background
.clone()
.unwrap_or(crate::node::BackgroundColor::Color(Color::new(0, 0, 0, 0xB3)));
let clear = crate::node::BackgroundColor::Color(Color::new(0, 0, 0, 0));
let mut text = Column::new()
.part(&form.part(PicturePart::Text))
.flex(1.0)
.min_width(0.0);
if let Some(title) = &bar.title {
let part = form.part(PicturePart::Title);
text = text.child(part.text(title).width(Dimension::Pct(100.0)).part(&part));
}
if let Some(description) = &bar.description {
let part = form.part(PicturePart::Description);
text = text.child(part.text(description).width(Dimension::Pct(100.0)).part(&part));
}
let buttons = Row::new()
.part(&form.part(PicturePart::Actions))
.align_items(Alignment::Center)
.overflow_visible()
.with_children(bar.buttons.iter().cloned());
let mut controls = Row::new()
.part(&part)
.width(Dimension::Pct(100.0))
.align_items(Alignment::End)
.overflow_visible()
.background_gradient(crate::node::Gradient::linear(
180.0,
[(clear, 0.0), (end, 1.0)].map(|(color, at)| crate::node::gradient::GradientStop::at(color, at)),
))
.child(text)
.child(buttons);
if let Some(menu) = &bar.menu {
controls = controls.child(menu.clone());
}
if let Some(id) = self.id("controls") {
controls = controls.id(id);
}
bars.push(
form
.placed(
layer()
.stack_align(StackAlignment::BottomStart)
.hit_test(HitTestBehavior::ContentOnly)
.child(controls),
)
.into(),
);
}
bars
}
pub fn actions(&self) -> Vec<MenuItem> {
let picture = &self.picture;
if !self.phone || picture.disabled {
return Vec::new();
}
let mut items = Vec::new();
if !picture.on_download.is_empty() {
let handlers = picture.on_download.clone();
items.push(
MenuItem::new(&picture.words.download)
.icon(icons::DOWNLOAD)
.on_select(move || handlers.iter().for_each(|handler| handler())),
);
}
items.extend(picture.menu_items.iter().cloned());
items
}
pub fn edge(&self) -> Option<Element> {
let edge_to_edge = self.phone && self.base().size == PictureSize::Lg;
(!self.picture.bare && !edge_to_edge).then(|| {
layer()
.part(&self.part(PicturePart::Edge))
.drop_outside(SizeBounds::new())
.pointer_events_none()
.into()
})
}
fn press(&self) -> impl Fn(MouseEvent) + Send + Sync + 'static {
let (clicks, changes) = (self.picture.on_click.clone(), self.picture.on_change.clone());
let (selectable, next) = (self.picture.selectable, !self.picture.selected);
let opens =
(self.picture.lightbox && !selectable).then(|| (self.viewer.clone(), self.picture.on_open_change.clone()));
move |event: MouseEvent| {
for handler in &clicks {
handler.call(&event);
}
if selectable {
changes.iter().for_each(|handler| handler(next));
}
if let Some((open, told)) = &opens
&& !open.get_untracked()
{
open.set(true);
told.iter().for_each(|tell| tell(true));
}
}
}
pub fn frame(&self) -> Element {
let picture = &self.picture;
let theme = self.theme();
let full = Dimension::Pct(100.0);
let mut inner = Stack::new().stack_align(StackAlignment::Center);
if self.known.width {
inner = inner.width(full);
}
if self.known.height {
inner = inner.height(full);
}
let fades = self.known.width && self.known.height;
let waiting = |stand_in: Element| -> Element {
if !fades {
return stand_in;
}
Stack::new()
.size(full, full)
.key("stand-in")
.part(&self.part(PicturePart::StandIn))
.child(stand_in)
.into()
};
let (pixels, over) = match (&self.phase, self.image()) {
(_, Some(image)) if !picture.loading => (Some(image), None),
_ if picture.fallback.is_some() => (
None,
picture.fallback.as_ref().map(|fallback| {
let centered = Stack::new()
.stack_align(StackAlignment::Center)
.size(full, full)
.child(fallback());
waiting(centered.into())
}),
),
_ if picture.loading => (None, Some(waiting(self.loading_maker()(None)))),
(_, Some(image)) => (Some(image), None),
(Phase::Loading(bytes), _) => (None, Some(waiting(self.loading_maker()(*bytes)))),
(Phase::Failed(_), _) => (None, Some(self.error_maker()())),
_ => (None, Some(self.empty())),
};
inner = if fades {
inner.presence().child(pixels.unwrap_or_default()).with_children(over)
} else {
inner.with_children(pixels.or(over))
};
if let Some(overlay) = self.overlay() {
inner = inner.child(overlay);
}
inner = inner
.with_children(self.count())
.with_children(self.top())
.with_children(self.controls());
if let Some(edge) = self.edge() {
inner = inner.child(edge);
}
let actions = self.actions();
let actions_empty = actions.is_empty();
if !actions.is_empty() {
let mut sheet = super::ActionSheet::new(self.sheet.clone(), actions).key("actions");
if let Some(title) = picture.title.clone().or_else(|| self.label()) {
sheet = sheet.title(&title);
}
if let Some(id) = self.id("actions") {
sheet = sheet.id(id);
}
inner = inner.child(sheet);
}
if picture.lightbox {
let told = picture.on_open_change.clone();
let mut viewer = super::Lightbox::new(self.viewer.clone(), [picture.clone()])
.on_dismiss(move || told.iter().for_each(|tell| tell(false)))
.key("viewer");
if let Some(label) = self.label() {
viewer = viewer.label(&label);
}
if let Some(id) = self.id("viewer") {
viewer = viewer.id(id);
}
inner = inner.child(viewer);
}
let part = self.part(PicturePart::Root).forced(picture.forced);
let role = match (picture.selectable, self.pressable) {
(true, _) => "checkbox",
(false, true) => "button",
(false, false) => "img",
};
let mut root: Element = if self.pressable {
pressable(&part, false)
.clip()
.interaction_group(true)
.on_click(self.press())
.child(inner)
.into()
} else {
Row::new()
.part(&part)
.clip()
.interaction_group(true)
.disabled(picture.disabled)
.child(inner)
.into()
};
NodeUpdate::ref_element(&mut *root.node, self.frame.clone());
if !actions_empty {
let sheet = self.sheet.clone();
NodeUpdate::on_long_press(&mut *root.node, move |_: crate::app::events::LongPressEvent| {
sheet.set(true)
});
}
let node = &mut *root.node;
let width = picture.width.and_then(|width| width.resolve(theme));
let height = picture.height.and_then(|height| height.resolve(theme));
if let Some(width) = width {
NodeUpdate::width(node, width);
NodeUpdate::max_width(node, Dimension::Pct(100.0));
}
match (width, height, picture.aspect_ratio) {
(Some(Dimension::Px(wide)), Some(Dimension::Px(high)), None) if wide > 0.0 && high > 0.0 => {
NodeUpdate::aspect_ratio(node, wide / high * (1.0 - 4.0 * f32::EPSILON));
NodeUpdate::max_height(node, high);
}
(width, height, ratio) => {
if let Some(height) = height {
NodeUpdate::height(node, height);
}
if let Some(ratio) = ratio {
NodeUpdate::aspect_ratio(node, ratio);
if width.is_none() && height.is_none() {
NodeUpdate::width(node, Dimension::Pct(100.0));
}
}
}
}
match self.label() {
Some(label) => {
NodeUpdate::describe(node, Arc::from("a11y_role"), Arc::from(role));
NodeUpdate::describe(node, Arc::from("a11y_name"), label);
}
None if role != "img" => NodeUpdate::describe(node, Arc::from("a11y_role"), Arc::from(role)),
None => {}
}
if picture.selectable {
let checked = if picture.selected { "true" } else { "false" };
NodeUpdate::describe(node, Arc::from("a11y_checked"), Arc::from(checked));
}
if let Some(id) = &picture.id {
NodeUpdate::id(node, id.clone());
}
if let (Some(key), None) = (&picture.key, &picture.caption) {
node.set_component_key(Some(key));
}
root
}
pub fn render(self) -> Element {
let frame = self.frame();
let Some(caption) = &self.picture.caption else {
return frame;
};
let part = self.part(PicturePart::Caption);
let mut figure = Column::new()
.part(&self.part(PicturePart::Figure))
.align_items(Alignment::Center)
.describe("a11y_role", "figure")
.child(frame)
.child(wrapped(&part, caption));
if let Some(width) = self.picture.width.and_then(|width| width.resolve(self.theme())) {
figure = figure.width(width).max_width(Dimension::Pct(100.0));
}
if let Some(key) = &self.picture.key {
figure = figure.key(key.clone());
}
figure.into()
}
}
#[cfg(feature = "raster")]
fn fit_of(fit: PictureFit) -> crate::node::BackgroundSize {
use crate::node::BackgroundSize;
match fit {
PictureFit::Cover => BackgroundSize::Cover,
PictureFit::Contain => BackgroundSize::Contain,
PictureFit::Fill => BackgroundSize::Stretch,
PictureFit::None => BackgroundSize::Natural,
}
}
#[cfg(feature = "raster")]
fn anchor_shares(anchor: StackAlignment) -> (f32, f32) {
use StackAlignment::*;
match anchor {
TopStart => (0.0, 0.0),
TopCenter => (0.5, 0.0),
TopEnd => (1.0, 0.0),
CenterStart => (0.0, 0.5),
Center => (0.5, 0.5),
CenterEnd => (1.0, 0.5),
BottomStart => (0.0, 1.0),
BottomCenter => (0.5, 1.0),
BottomEnd => (1.0, 1.0),
}
}
impl crate::ui::Styled for Picture {
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 Picture {
const NAME: &'static str = "picture";
type Renderer = PictureRenderer;
fn parts() -> crate::ui::Declared {
PicturePart::declared()
}
fn states() -> crate::ui::Declared {
PictureState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{Background, Foreground, Input, Muted, MutedForeground, Primary, PrimaryForeground, StateHover};
use PicturePart::*;
use PictureSize::{Md, Sm, Xs};
use PictureState::{Bare, Circle, Disabled, On, Pressable, Selectable, Selected, Shown};
let white = Color::new(255, 255, 255, 255);
let white_60 = Color::new(255, 255, 255, 0x99);
let white_20 = Color::new(255, 255, 255, 0x33);
let white_12 = Color::new(255, 255, 255, 0x1F);
let black_40 = Color::new(0, 0, 0, 0x66);
let black_60 = Color::new(0, 0, 0, 0x99);
let black_70 = Color::new(0, 0, 0, 0xB3);
let appear = |s: super::PartStyle| {
s.transition(PartTransition::new(Transition::opacity(), MotionDuration::Base).easing(MotionEasing::Enter))
};
Recipe::new()
.base(Figure, |s| s.gap(8.0))
.base(Root, |s| s.radius(RadiusSize::Lg).background(Muted))
.size(Sm, Root, |s| s.radius(RadiusSize::Md))
.size(Xs, Root, |s| s.radius(RadiusSize::Md))
.state(Circle, Root, |s| s.radius(RadiusSize::Full))
.state(Bare, Root, |s| s.radius(0.0).background(Color::new(0, 0, 0, 0)))
.state(Pressable, Root, |s| s.cursor(CursorIcon::Pointer))
.state(Selected, Root, |s| s.outline(Outline::new(2.0, Primary)))
.state(Disabled, Root, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
.when(Selector::new().state(Pressable).focus_visible(), Root, |s| {
s.focus_ring()
})
.base(Edge, |s| {
s.radius(RadiusSize::Lg)
.border(Border::inside(1.0, PaletteColor::Border))
})
.size(Sm, Edge, |s| s.radius(RadiusSize::Md))
.size(Xs, Edge, |s| s.radius(RadiusSize::Md))
.state(Circle, Edge, |s| s.radius(RadiusSize::Full))
.base(StandIn, |s| {
s.exit(PartAnimation::new(
super::FADE_OUT,
MotionDuration::Base,
MotionEasing::Exit,
))
})
.base(Sheen, |s| s.radius(0.0))
.base(Veil, |s| s.background(black_60))
.base(Center, |s| s.padding_x(24.0).padding_y(8.0).gap(12.0))
.size(Md, Center, |s| s.padding_x(12.0).padding_y(12.0).gap(8.0))
.size(Sm, Center, |s| s.padding_x(8.0).padding_y(8.0))
.size(Xs, Center, |s| s.padding_x(0.0).padding_y(0.0))
.base(Mark, |s| s.square(28.0).foreground(MutedForeground))
.size(Md, Mark, |s| s.square(24.0))
.size(Sm, Mark, |s| s.square(20.0))
.size(Xs, Mark, |s| s.square(16.0))
.base(Label, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.line_height(1.4)
.foreground(MutedForeground)
})
.base(ErrorIcon, |s| s.square(24.0).foreground(MutedForeground))
.size(Sm, ErrorIcon, |s| s.square(20.0))
.size(Xs, ErrorIcon, |s| s.square(16.0))
.base(ErrorLabel, |s| {
s.typography(TypographyStyle::Body)
.font_size(14.0)
.weight(FontWeight::Medium)
.line_height(1.4)
.foreground(Foreground)
.padding_bottom(4.0)
})
.size(Md, ErrorLabel, |s| s.font_size(13.0).padding_bottom(0.0))
.base(ErrorDescription, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(MutedForeground)
})
.base(Retry, |s| {
fading(
s.height(32.0)
.padding_x(16.0)
.radius(RadiusSize::Md)
.background(Background)
.border(Border::inside(1.0, Input))
.foreground(Foreground)
.typography(TypographyStyle::Body)
.font_size(13.0)
.weight(FontWeight::Medium)
.cursor(CursorIcon::Pointer),
)
})
.size(Md, Retry, |s| s.height(28.0).padding_x(12.0).font_size(12.0))
.hovered(Retry, |s| s.veil(StateHover))
.focus_visible(Retry, |s| s.focus_ring())
.base(Progress, |s| s.gap(8.0))
.base(Track, |s| {
s.width(160.0).height(4.0).radius(RadiusSize::Full).background(Input)
})
.size(Md, Track, |s| s.width(96.0))
.base(Fill, |s| s.background(Primary))
.base(ProgressLabel, |s| {
s.typography(TypographyStyle::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(ProgressLine, |s| s.width(Length::Fill).height(2.0).background(Input))
.base(Count, |s| {
s.typography(TypographyStyle::Body)
.font_size(20.0)
.weight(FontWeight::SemiBold)
.foreground(white)
})
.size(Sm, Count, |s| s.font_size(13.0))
.base(Top, |s| s.padding_x(12.0).padding_y(12.0))
.size(Sm, Top, |s| s.padding_x(6.0).padding_y(6.0))
.base(Select, |s| {
appear(
s.square(20.0)
.radius(RadiusSize::Full)
.background(black_40)
.border(Border::inside(1.5, white))
.opacity(0.0),
)
})
.size(Sm, Select, |s| s.square(16.0))
.when(Selector::new().state(Selectable).within(), Select, |s| s.opacity(1.0))
.when(Selector::new().state(Selectable).state(Shown), Select, |s| {
s.opacity(1.0)
})
.state(Selected, Select, |s| {
s.background(Primary)
.border(Border::inside(1.5, PrimaryForeground))
.opacity(1.0)
})
.base(SelectIcon, |s| s.square(12.0).foreground(PrimaryForeground))
.size(Sm, SelectIcon, |s| s.square(10.0))
.base(Controls, |s| {
appear(
s.padding_top(24.0)
.padding_x(12.0)
.padding_bottom(8.0)
.gap(12.0)
.background(black_70)
.opacity(0.0),
)
})
.size(Md, Controls, |s| {
s.padding_top(20.0).padding_x(8.0).padding_bottom(6.0).gap(8.0)
})
.within(Controls, |s| s.opacity(1.0))
.state(Shown, Controls, |s| s.opacity(1.0))
.base(Text, |s| s.gap(2.0).padding_start(4.0).padding_bottom(4.0))
.size(Md, Text, |s| s.padding_bottom(6.0))
.base(Title, |s| {
s.typography(TypographyStyle::Body)
.font_size(14.0)
.weight(FontWeight::Medium)
.foreground(white)
})
.size(Md, Title, |s| s.font_size(13.0))
.base(Description, |s| {
s.typography(TypographyStyle::Body).font_size(13.0).foreground(white_60)
})
.base(Actions, |s| s.gap(4.0))
.base(Control, |s| {
fading(
s.square(36.0)
.radius(RadiusSize::Md)
.foreground(white)
.cursor(CursorIcon::Pointer),
)
})
.size(Md, Control, |s| s.square(28.0))
.hovered(Control, |s| s.background(white_12))
.focus_visible(Control, |s| s.outline(Outline::new(2.0, white)))
.state(On, Control, |s| s.background(white_20))
.base(ControlIcon, |s| s.square(20.0))
.when(Selector::new().variant(PictureVariant::Phone).size(PictureSize::Lg), Root, |s| s.radius(0.0))
.when(Selector::new().variant(PictureVariant::Phone).size(PictureSize::Lg), Top, |s| {
s.padding_x(16.0).padding_y(16.0)
})
.when(Selector::new().variant(PictureVariant::Phone).size(PictureSize::Lg), Controls, |s| {
s.padding_top(32.0).padding_x(16.0).padding_bottom(12.0)
})
.when(Selector::new().variant(PictureVariant::Phone).size(PictureSize::Lg), Text, |s| {
s.padding_start(0.0).padding_bottom(0.0)
})
.when(Selector::new().variant(PictureVariant::Phone).size(PictureSize::Lg), Title, |s| s.font_size(15.0))
.size(Md, ControlIcon, |s| s.square(16.0))
.base(MoreMenu, |s| s.width(216.0))
.base(Caption, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.font_style(FontStyle::Italic)
.line_height(1.4)
.foreground(MutedForeground)
})
}
}