use std::sync::Arc;
use super::{
Carousel, FontFamily, Menu, MenuItem, Picture, icons, names,
part_style::{Length, PartTransition},
recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{fading, glyph, pressable},
theme::{Themed, current_theme},
};
use crate::{
animation::Transition,
app::{
component::Component,
ctx::{Ctx, Placement},
events::{GesturePhase, KeyboardEvent, MouseEvent, PanEvent, TapEvent},
theme::{MotionDuration, RadiusSize, Theme, TypographyStyle},
},
components::{Column, Modal, Root, Row, Stack, ZoomScroll, ZoomScrollProps},
core::{ElementRef, Signal},
layout::{
Alignment, StackAlignment,
layout_kind::{Justify, ScrollState},
text_style::{FontWeight, TextAlign},
},
node::{
CursorIcon, Element, HitTestBehavior, NodeUpdate, border::Border, color::Color, dimension::Dimension,
outline::Outline,
},
};
const ZOOM_STEP: f32 = 1.5;
const PAN_STEP: f32 = 48.0;
const TOP_SIDES: f32 = 24.0;
const CONTROL_ROOM: f32 = 40.0;
const LEVEL_ROOM: f32 = 60.0;
const CONTROL_GAP: f32 = 4.0;
const COUNTER_LETTER: f32 = 8.0;
const STRIP_GAP: f32 = 6.0;
const STRIP_INSET: f32 = 8.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LightboxPart {
Veil,
Root,
Top,
Counter,
Total,
Control,
ControlIcon,
Level,
Stage,
Step,
StepIcon,
Side,
Caption,
Title,
Description,
Filmstrip,
Thumb,
Bottom,
Pages,
Page,
}
names!(LightboxPart {
Veil => "veil",
Root => "root",
Top => "top",
Counter => "counter",
Total => "total",
Control => "control",
ControlIcon => "control_icon",
Level => "level",
Stage => "stage",
Step => "step",
StepIcon => "step_icon",
Side => "side",
Caption => "caption",
Title => "title",
Description => "description",
Filmstrip => "filmstrip",
Thumb => "thumb",
Bottom => "bottom",
Pages => "pages",
Page => "page",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LightboxState {
Inline,
Current,
}
names!(LightboxState {
Inline => "inline",
Current => "current",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum LightboxVariant {
#[default]
Desktop,
Phone,
}
names!(LightboxVariant {
Desktop => "desktop",
Phone => "phone",
});
const PAGES_SHOWN: usize = 9;
const DROP_CLOSES: f32 = 120.0;
const THROW_CLOSES: f32 = 900.0;
const DROP_FADES: f32 = 400.0;
pub type LightboxRenderer = Arc<dyn Fn(LightboxView) -> Element + Send + Sync>;
type Action = Arc<dyn Fn() + Send + Sync>;
type Told<T> = Arc<dyn Fn(T) + Send + Sync>;
#[derive(Clone)]
struct Words {
label: Arc<str>,
close: Arc<str>,
previous: Arc<str>,
next: Arc<str>,
zoom_in: Arc<str>,
zoom_out: Arc<str>,
fit: Arc<str>,
download: Arc<str>,
share: Arc<str>,
more: Arc<str>,
}
impl Default for Words {
fn default() -> Self {
let locale = super::current_locale();
let words = &locale.navigation;
Self {
label: words.pictures.clone(),
close: locale.common.close.clone(),
previous: words.previous_picture.clone(),
next: words.next_picture.clone(),
zoom_in: words.zoom_in.clone(),
zoom_out: words.zoom_out.clone(),
fit: words.fit_to_window.clone(),
download: locale.common.download.clone(),
share: locale.common.share.clone(),
more: locale.common.more.clone(),
}
}
}
#[derive(Clone)]
pub struct Lightbox {
open: Signal<bool>,
pictures: Vec<Picture>,
index: Option<Signal<usize>>,
controlled: Option<usize>,
on_index_change: Vec<Told<usize>>,
zoom: Option<Signal<f32>>,
on_zoom_change: Vec<Told<f64>>,
zoom_max: f32,
preload: usize,
filmstrip: Option<bool>,
counter: Option<bool>,
counter_text: Option<Arc<dyn Fn(usize, usize) -> String + Send + Sync>>,
wrap: bool,
on_download: Vec<Told<usize>>,
on_share: Vec<Told<usize>>,
menu_items: Vec<MenuItem>,
variant: Option<Name>,
actions: Vec<Element>,
inline: bool,
width: Option<Length>,
height: Option<Length>,
on_dismiss: Vec<Action>,
dismiss_on_escape: bool,
dismiss_on_veil: bool,
close_button: bool,
words: Words,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Lightbox {
pub fn new(open: Signal<bool>, pictures: impl IntoIterator<Item = Picture>) -> Self {
Self {
open,
pictures: pictures.into_iter().collect(),
index: None,
controlled: None,
on_index_change: Vec::new(),
zoom: None,
on_zoom_change: Vec::new(),
zoom_max: 4.0,
preload: 1,
filmstrip: None,
counter: None,
counter_text: None,
wrap: false,
on_download: Vec::new(),
on_share: Vec::new(),
menu_items: Vec::new(),
variant: None,
actions: Vec::new(),
inline: false,
width: None,
height: None,
on_dismiss: Vec::new(),
dismiss_on_escape: true,
dismiss_on_veil: true,
close_button: true,
words: Words::default(),
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
pub fn picture(mut self, picture: Picture) -> Self {
self.pictures.push(picture);
self
}
pub fn pictures(mut self, pictures: impl IntoIterator<Item = Picture>) -> Self {
self.pictures.extend(pictures);
self
}
pub fn index(mut self, index: Signal<usize>) -> Self {
self.index = Some(index);
self
}
pub fn index_controlled(mut self, index: usize, on_change: impl Fn(usize) + Send + Sync + 'static) -> Self {
self.controlled = Some(index);
self.on_index_change.push(Arc::new(on_change));
self
}
pub fn on_index_change(mut self, handler: impl Fn(usize) + Send + Sync + 'static) -> Self {
self.on_index_change.push(Arc::new(handler));
self
}
pub fn zoom(mut self, zoom: Signal<f32>) -> Self {
self.zoom = Some(zoom);
self
}
pub fn on_zoom_change(mut self, handler: impl Fn(f64) + Send + Sync + 'static) -> Self {
self.on_zoom_change.push(Arc::new(handler));
self
}
pub fn preload(mut self, preload: usize) -> Self {
self.preload = preload;
self
}
pub fn zoom_max(mut self, max: f32) -> Self {
self.zoom_max = max.max(1.0);
self
}
pub fn filmstrip(mut self, filmstrip: bool) -> Self {
self.filmstrip = Some(filmstrip);
self
}
pub fn counter(mut self, counter: bool) -> Self {
self.counter = Some(counter);
self
}
pub fn counter_text(mut self, text: impl Fn(usize, usize) -> String + Send + Sync + 'static) -> Self {
self.counter_text = Some(Arc::new(text));
self
}
pub fn wrap(mut self, wrap: bool) -> Self {
self.wrap = wrap;
self
}
pub fn on_download(mut self, handler: impl Fn(usize) + Send + Sync + 'static) -> Self {
self.on_download.push(Arc::new(handler));
self
}
pub fn on_share(mut self, handler: impl Fn(usize) + Send + Sync + 'static) -> Self {
self.on_share.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 variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = Some(variant.into());
self
}
pub fn share_label(mut self, label: &str) -> Self {
self.words.share = Arc::from(label);
self
}
pub fn more_label(mut self, label: &str) -> Self {
self.words.more = Arc::from(label);
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 inline(mut self, inline: bool) -> Self {
self.inline = inline;
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 on_dismiss(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_dismiss.push(Arc::new(handler));
self
}
pub fn dismiss_on_escape(mut self, dismiss: bool) -> Self {
self.dismiss_on_escape = dismiss;
self
}
pub fn dismiss_on_veil(mut self, dismiss: bool) -> Self {
self.dismiss_on_veil = dismiss;
self
}
pub fn close_button(mut self, close_button: bool) -> Self {
self.close_button = close_button;
self
}
pub fn label(mut self, label: &str) -> Self {
self.words.label = Arc::from(label);
self
}
pub fn close_label(mut self, label: &str) -> Self {
self.words.close = Arc::from(label);
self
}
pub fn previous_label(mut self, label: &str) -> Self {
self.words.previous = Arc::from(label);
self
}
pub fn next_label(mut self, label: &str) -> Self {
self.words.next = Arc::from(label);
self
}
pub fn zoom_in_label(mut self, label: &str) -> Self {
self.words.zoom_in = Arc::from(label);
self
}
pub fn zoom_out_label(mut self, label: &str) -> Self {
self.words.zoom_out = Arc::from(label);
self
}
pub fn fit_label(mut self, label: &str) -> Self {
self.words.fit = Arc::from(label);
self
}
pub fn download_label(mut self, label: &str) -> Self {
self.words.download = Arc::from(label);
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 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 = LightboxProps(self);
match key {
Some(key) => ctx.mount_keyed::<LightboxHost>(&key, props),
None => ctx.mount::<LightboxHost>(props),
}
}
}
impl From<Lightbox> for Element {
fn from(lightbox: Lightbox) -> Self {
let key = lightbox.key.clone();
let props = LightboxProps(lightbox);
match key {
Some(key) => Element::component_keyed::<LightboxHost>(key, props),
None => Element::component::<LightboxHost>(props),
}
}
}
#[derive(Clone)]
struct LightboxProps(Lightbox);
impl PartialEq for LightboxProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for LightboxProps {}
struct LightboxHost {
index: Signal<usize>,
zoom: Signal<f32>,
scroll: ScrollState,
told: Arc<parking_lot::Mutex<f32>>,
news: Arc<parking_lot::Mutex<Vec<Action>>>,
stage: ElementRef,
room: Signal<(f32, f32)>,
came: Signal<Option<usize>>,
more_open: Signal<bool>,
more: ElementRef,
drop: Signal<f32>,
taken: Arc<std::sync::atomic::AtomicBool>,
was_open: std::sync::atomic::AtomicBool,
held: parking_lot::Mutex<Option<(bool, u64)>>,
ahead: parking_lot::Mutex<Vec<(usize, Option<crate::resources::Load>)>>,
ahead_tick: Signal<u64>,
full: Signal<bool>,
ahead_wake: Arc<dyn Fn() + Send + Sync>,
}
impl Component for LightboxHost {
type Props = LightboxProps;
fn create(ctx: &mut Ctx) -> Self {
let ahead_tick = ctx.signal(0u64);
let ahead_wake: Arc<dyn Fn() + Send + Sync> = {
let tick = ahead_tick.clone();
Arc::new(move || tick.set(tick.get_untracked().wrapping_add(1)))
};
Self {
index: ctx.signal(0),
zoom: ctx.signal(1.0),
scroll: ScrollState::new(),
told: Arc::new(parking_lot::Mutex::new(1.0)),
news: Arc::default(),
stage: ElementRef::new(),
room: ctx.signal((0.0, 0.0)),
came: ctx.signal(None),
more_open: ctx.signal(false),
more: ElementRef::new(),
drop: ctx.signal(0.0),
taken: Arc::default(),
was_open: std::sync::atomic::AtomicBool::new(false),
held: parking_lot::Mutex::new(None),
ahead: parking_lot::Mutex::new(Vec::new()),
ahead_tick,
ahead_wake,
full: ctx.signal(false),
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let lightbox = ctx.props::<LightboxProps>().0.clone();
let theme = current_theme();
let count = lightbox.pictures.len();
let index_signal = lightbox.index.clone().unwrap_or_else(|| self.index.clone());
let index = lightbox
.controlled
.unwrap_or_else(|| index_signal.get())
.min(count.saturating_sub(1));
let zoom_signal = lightbox.zoom.clone().unwrap_or_else(|| self.zoom.clone());
let open = lightbox.inline || lightbox.open.get();
let opened = open && !self.was_open.swap(open, std::sync::atomic::Ordering::Relaxed);
if !open {
self.was_open.store(false, std::sync::atomic::Ordering::Relaxed);
}
if opened && lightbox.zoom.is_none() && self.zoom.get_untracked() != 1.0 {
self.zoom.set(1.0);
self.scroll.set_scroll(0.0, 0.0);
}
let max = lightbox.zoom_max;
let phone = match lightbox.variant {
Some(variant) => variant == Name::from(LightboxVariant::Phone),
None => {
let (finger, told) = (super::touch_form(), super::theme::pointer_told());
let mut held = self.held.lock();
match *held {
Some((phone, at)) if open && at == told => phone,
_ => {
*held = open.then_some((finger, told));
finger
}
}
}
};
let safe = match lightbox.inline {
false => ctx.safe_area(),
true => crate::app::window::SafeAreaInsets::default(),
};
let drop = self.drop.get();
let zoom = zoom_signal.get().clamp(1.0, max);
let room = self.room.get();
{
let mut told = self.told.lock();
if (*told - zoom).abs() > f32::EPSILON {
*told = zoom;
let handlers = lightbox.on_zoom_change.clone();
self.news.lock().push(Arc::new(move || {
handlers.iter().for_each(|tell| tell(f64::from(zoom)));
}));
}
}
let go: Arc<dyn Fn(f32) + Send + Sync> = {
let zoom_signal = zoom_signal.clone();
Arc::new(move |next: f32| {
let next = next.clamp(1.0, max);
if (next - zoom_signal.get_untracked()).abs() > f32::EPSILON {
zoom_signal.set(next);
}
})
};
let shift: Arc<dyn Fn(f32, f32) + Send + Sync> = {
let scroll = self.scroll.clone();
Arc::new(move |x: f32, y: f32| scroll.scroll_by(x, y))
};
let turn: Told<usize> = {
let (signal, controlled, told) = (
index_signal.clone(),
lightbox.controlled.is_some(),
lightbox.on_index_change.clone(),
);
let (zoom_signal, scroll) = (zoom_signal.clone(), self.scroll.clone());
Arc::new(move |to: usize| {
if to >= count || to == index {
return;
}
zoom_signal.set(1.0);
scroll.set_scroll(0.0, 0.0);
if !controlled {
signal.set(to);
}
told.iter().for_each(|tell| tell(to));
})
};
self.bring_on(ctx, &lightbox, index);
let shown = lightbox.pictures.get(index).cloned().map(|picture| {
let came = self.came.clone();
let picture: Element = picture
.in_viewer()
.on_load(move || {
if came.get_untracked() != Some(index) {
came.set(Some(index));
}
})
.key(format!("picture-{index}"))
.into();
if room.0 <= 0.0 || room.1 <= 0.0 {
return picture;
}
let props = ZoomScrollProps::new(room.0, room.1)
.range(1.0, max)
.wheel_zoom(ZOOM_STEP)
.drag_pan(!phone || zoom > 1.0)
.scrollbars(false)
.zoom(zoom_signal.clone())
.scroll(self.scroll.clone());
ZoomScroll::mount(ctx, props, picture)
});
let case = |current: bool| {
Case {
variant: Some(
if phone {
LightboxVariant::Phone
} else {
LightboxVariant::Desktop
}
.into(),
),
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: lightbox.states.clone(),
}
.state(LightboxState::Inline, lightbox.inline)
.state(LightboxState::Current, current)
};
let in_page_on_a_phone = lightbox.inline && phone;
let expand: Option<Action> = in_page_on_a_phone.then(|| {
let full = self.full.clone();
Arc::new(move || full.set(true)) as Action
});
let expanded: Option<Element> = (in_page_on_a_phone && self.full.get()).then(|| {
let mut whole = lightbox.clone();
whole.inline = false;
whole.open = self.full.clone();
whole.index = Some(index_signal.clone());
whole.key = None;
whole.id = whole.id.map(|id| Arc::from(format!("{id}-full")));
whole.into()
});
let recipe = theme
.resolve::<Lightbox>(&case(false), Some(&lightbox.rules))
.owned_by(lightbox.id.as_ref());
let current = theme
.resolve::<Lightbox>(&case(true), Some(&lightbox.rules))
.owned_like(&recipe);
let view = LightboxView {
expand,
expanded,
recipe,
current,
index,
zoom,
shown,
go,
turn,
stage: self.stage.clone(),
shift,
phone,
safe,
room,
drop,
dropped: self.drop.clone(),
taken: self.taken.clone(),
more_open: self.more_open.clone(),
more: self.more.clone(),
lightbox,
};
match theme.renderer::<Lightbox>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
fn after_layout(&self) {
if !self.stage.is_attached() {
return;
}
let room = (self.stage.width(), self.stage.height());
let last = self.room.get_untracked();
if (last.0 - room.0).abs() > 0.25 || (last.1 - room.1).abs() > 0.25 {
self.room.set(room);
}
let news = std::mem::take(&mut *self.news.lock());
news.iter().for_each(|tell| tell());
}
}
impl LightboxHost {
fn bring_on(&self, ctx: &Ctx, lightbox: &Lightbox, index: usize) {
let _ = self.ahead_tick.get();
let count = lightbox.pictures.len();
let open = lightbox.inline || lightbox.open.get();
if !open || lightbox.preload == 0 || self.came.get() != Some(index) {
return;
}
let mut places = Vec::new();
for step in 1..=lightbox.preload.min(count) {
let after = index + step;
let before = index.checked_sub(step);
let after = if after < count {
Some(after)
} else {
lightbox.wrap.then(|| after % count)
};
let before = before.or_else(|| lightbox.wrap.then(|| (index + count - step % count) % count));
for at in [after, before].into_iter().flatten() {
if at != index && !places.contains(&at) {
places.push(at);
}
}
}
#[cfg(feature = "image")]
{
let loader = ctx.app_handle().map(|app| app.loader().clone());
let mut ahead = self.ahead.lock();
let held = std::mem::take(&mut *ahead);
for at in places {
let load = match held.iter().find(|(place, _)| *place == at) {
Some((_, None)) => None,
Some((_, Some(load))) if load.state().is_loading() => Some(load.clone()),
_ => lightbox.pictures[at].fetch(loader.as_ref()),
};
if let Some(load) = &load {
load.wake_with(self.ahead_wake.clone());
}
ahead.push((at, load));
}
}
#[cfg(not(feature = "image"))]
let _ = (ctx, places);
}
}
pub struct LightboxView {
pub recipe: ResolvedRecipe,
current: ResolvedRecipe,
pub index: usize,
pub zoom: f32,
shown: Option<Element>,
go: Arc<dyn Fn(f32) + Send + Sync>,
turn: Told<usize>,
stage: ElementRef,
shift: Arc<dyn Fn(f32, f32) + Send + Sync>,
pub phone: bool,
safe: crate::app::window::SafeAreaInsets,
room: (f32, f32),
drop: f32,
dropped: Signal<f32>,
taken: Arc<std::sync::atomic::AtomicBool>,
more_open: Signal<bool>,
more: ElementRef,
expand: Option<Action>,
expanded: Option<Element>,
lightbox: Lightbox,
}
impl LightboxView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn count(&self) -> usize {
self.lightbox.pictures.len()
}
pub fn zoomed(&self) -> bool {
self.zoom > 1.0 + f32::EPSILON
}
fn id(&self, suffix: &str) -> Option<String> {
self.lightbox.id.as_ref().map(|id| format!("{id}-{suffix}"))
}
pub fn dismisser(&self) -> impl Fn() + Send + Sync + Clone + 'static {
let (open, told) = (self.lightbox.open.clone(), self.lightbox.on_dismiss.clone());
move || {
open.set(false);
told.iter().for_each(|tell| tell());
}
}
fn neighbours(&self) -> (Option<usize>, Option<usize>) {
let count = self.count();
if count < 2 {
return (None, None);
}
let wrap = self.lightbox.wrap;
let before = match self.index {
0 => wrap.then_some(count - 1),
index => Some(index - 1),
};
let after = match self.index + 1 {
next if next >= count => wrap.then_some(0),
next => Some(next),
};
(before, after)
}
fn control(&self, icon: &'static str, label: &Arc<str>, id: &str, press: Action) -> Element {
let mut button = pressable(&self.part(LightboxPart::Control), false)
.describe("a11y_role", "button")
.describe("a11y_name", label.clone())
.child(glyph(&self.part(LightboxPart::ControlIcon), Name::new(icon), false))
.on_click(move |event: MouseEvent| {
event.stop_propagation();
press();
});
if let Some(id) = self.id(id) {
button = button.id(id);
}
button.into()
}
pub fn counter(&self) -> Option<Element> {
let lightbox = &self.lightbox;
let count = self.count();
if !lightbox.counter.unwrap_or(count > 1) {
return None;
}
let part = self.part(LightboxPart::Counter);
Some(
match &lightbox.counter_text {
Some(text) => Row::new().child(part.text(&text(self.index + 1, count)).nowrap().part(&part)),
None => Row::new()
.spacing(4.0)
.child(part.text(&(self.index + 1).to_string()).nowrap().part(&part))
.child({
let total = self.part(LightboxPart::Total);
total.text(&format!("/ {count}")).nowrap().part(&total)
}),
}
.into(),
)
}
pub fn top(&self) -> Element {
let lightbox = &self.lightbox;
let count = self.count();
let mut top = Row::new()
.part(&self.part(LightboxPart::Top))
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center);
let mut said = 0.0;
if let Some(counter) = self.counter() {
let letters = match &lightbox.counter_text {
Some(text) => text(self.index + 1, count).chars().count(),
None => format!("{} / {count}", self.index + 1).chars().count(),
};
said = letters as f32 * COUNTER_LETTER + CONTROL_GAP;
top = top.child(counter);
}
top = top.child(Row::new().flex(1.0));
let (go, zoom) = (self.go.clone(), self.zoom);
let closer: Action = {
let go = go.clone();
Arc::new(move || go(zoom * ZOOM_STEP))
};
let further: Action = {
let go = go.clone();
Arc::new(move || go(zoom / ZOOM_STEP))
};
let fit: Action = Arc::new(move || go(1.0));
top = top.child(self.control(icons::ZOOM_OUT, &lightbox.words.zoom_out, "zoom-out", further));
let buttons =
2 + lightbox.actions.len() + usize::from(!lightbox.on_download.is_empty()) + usize::from(lightbox.close_button);
let needed = TOP_SIDES + said + buttons as f32 * CONTROL_ROOM + LEVEL_ROOM;
let room = self.stage.width();
let level = self.part(LightboxPart::Level);
let mut fitter = pressable(&level, false)
.describe("a11y_role", "button")
.describe("a11y_name", lightbox.words.fit.clone())
.child(level.text(&format!("{}%", (self.zoom * 100.0).round())).nowrap())
.on_click(move |event: MouseEvent| {
event.stop_propagation();
fit();
});
if let Some(id) = self.id("level") {
fitter = fitter.id(id);
}
if room <= 0.0 || room >= needed {
top = top.child(fitter);
}
top = top
.child(self.control(icons::ZOOM_IN, &lightbox.words.zoom_in, "zoom-in", closer))
.with_children(lightbox.actions.iter().cloned());
if !lightbox.on_download.is_empty() {
let (handlers, index) = (lightbox.on_download.clone(), self.index);
let download: Action = Arc::new(move || handlers.iter().for_each(|handler| handler(index)));
top = top.child(self.control(icons::DOWNLOAD, &lightbox.words.download, "download", download));
}
if lightbox.close_button {
let close = self.dismisser();
top = top.child(self.control(icons::CLOSE, &lightbox.words.close, "close", Arc::new(close)));
}
top.into()
}
fn step(&self, icon: &'static str, label: &Arc<str>, id: &str, to: usize) -> Element {
let turn = self.turn.clone();
let mut button = pressable(&self.part(LightboxPart::Step), false)
.describe("a11y_role", "button")
.describe("a11y_name", label.clone())
.child(glyph(&self.part(LightboxPart::StepIcon), Name::new(icon), false))
.on_click(move |event: MouseEvent| {
event.stop_propagation();
turn(to);
});
if let Some(id) = self.id(id) {
button = button.id(id);
}
button.into()
}
pub fn caption(&self) -> Option<Element> {
let (title, description) = self.lightbox.pictures.get(self.index)?.caption_of();
if self.zoomed() || (title.is_none() && description.is_none()) {
return None;
}
let part = self.part(LightboxPart::Caption);
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 caption = Column::new()
.part(&part)
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.background_gradient(crate::node::Gradient::linear(
180.0,
[(clear, 0.0), (end, 1.0)].map(|(color, at)| crate::node::gradient::GradientStop::at(color, at)),
));
for (text, part) in [(title, LightboxPart::Title), (description, LightboxPart::Description)] {
if let Some(text) = text {
let part = self.part(part);
caption = caption.child(
part
.text(&text)
.text_align(TextAlign::Center)
.width(Dimension::Pct(100.0))
.part(&part),
);
}
}
Some(caption.into())
}
pub fn stage(&mut self) -> Element {
let full = Dimension::Pct(100.0);
let layer = || Stack::new().size(full, full).hit_test(HitTestBehavior::ContentOnly);
let name = self
.lightbox
.pictures
.get(self.index)
.and_then(Picture::label_of)
.unwrap_or_else(|| Arc::from(format!("{} / {}", self.index + 1, self.count())));
let mut room = Stack::new()
.part(&self.part(LightboxPart::Stage))
.width(full)
.flex(1.0)
.clip()
.tab_index(0)
.describe("a11y_role", "group")
.describe("a11y_name", name)
.ref_element(self.stage.clone());
if let Some(shown) = self.shown.take() {
room = room.child(shown);
}
if let Some(id) = self.id("stage") {
room = room.id(id);
}
if let Some(caption) = self.caption() {
room = room.child(
layer()
.stack_align(StackAlignment::BottomCenter)
.pointer_events_none()
.child(caption),
);
}
let (before, after) = self.neighbours();
if let Some(before) = before {
let words = self.lightbox.words.previous.clone();
room = room.child(
layer()
.stack_align(StackAlignment::CenterStart)
.part(&self.part(LightboxPart::Side))
.child(self.step(icons::CHEVRON_LEFT, &words, "previous", before)),
);
}
if let Some(after) = after {
let words = self.lightbox.words.next.clone();
room = room.child(
layer()
.stack_align(StackAlignment::CenterEnd)
.part(&self.part(LightboxPart::Side))
.child(self.step(icons::CHEVRON_RIGHT, &words, "next", after)),
);
}
let mut room: Element = room.into();
if !self.lightbox.inline {
NodeUpdate::autofocus(&mut *room.node, true);
}
room
}
pub fn filmstrip(&self) -> Option<Element> {
let count = self.count();
if !self.lightbox.filmstrip.unwrap_or(count > 1) {
return None;
}
let mut strip = Row::new()
.part(&self.part(LightboxPart::Filmstrip))
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.justify(Justify::Center);
let (first, last) = {
let (width, _) = thumb_size(&self.part(LightboxPart::Thumb));
let room = self.stage.width();
let fits = match room > 0.0 {
true => (((room - 2.0 * STRIP_INSET + STRIP_GAP) / (width + STRIP_GAP)).floor() as usize).max(1),
false => count,
};
let first = self.index.saturating_sub(fits / 2).min(count.saturating_sub(fits));
(first, (first + fits).min(count))
};
for (at, picture) in self.lightbox.pictures.iter().enumerate().take(last).skip(first) {
let recipe = if at == self.index { &self.current } else { &self.recipe };
let part = recipe.part(LightboxPart::Thumb);
let (width, height) = thumb_size(&part);
let turn = self.turn.clone();
let name = picture
.label_of()
.unwrap_or_else(|| Arc::from(format!("{} / {count}", at + 1)));
let mut thumb = pressable(&part, false)
.describe("a11y_role", "button")
.describe("a11y_name", name)
.describe("a11y_current", if at == self.index { "true" } else { "false" })
.clip()
.child(picture.clone().as_thumb(width, height).key(format!("thumb-{at}")))
.on_click(move |event: MouseEvent| {
event.stop_propagation();
turn(at);
});
if let Some(id) = self.id(&format!("thumb-{at}")) {
thumb = thumb.id(id);
}
strip = strip.child(thumb);
}
Some(strip.into())
}
pub fn phone_top(&self) -> Element {
let lightbox = &self.lightbox;
let full = Dimension::Pct(100.0);
let mut start = Row::new().flex(1.0).min_width(0.0).align_items(Alignment::Center);
if lightbox.close_button {
let close = self.dismisser();
start = start.child(self.control(icons::CLOSE, &lightbox.words.close, "close", Arc::new(close)));
}
let mut end = Row::new()
.flex(1.0)
.min_width(0.0)
.align_items(Alignment::Center)
.justify(Justify::End)
.with_children(lightbox.actions.iter().cloned());
if !lightbox.on_share.is_empty() {
let (handlers, index) = (lightbox.on_share.clone(), self.index);
let share: Action = Arc::new(move || handlers.iter().for_each(|handler| handler(index)));
end = end.child(self.control(icons::SHARE, &lightbox.words.share, "share", share));
}
let mut items = Vec::new();
if !lightbox.on_download.is_empty() {
let (handlers, index) = (lightbox.on_download.clone(), self.index);
items.push(
MenuItem::new(&lightbox.words.download)
.icon(icons::DOWNLOAD)
.on_select(move || handlers.iter().for_each(|handler| handler(index))),
);
}
items.extend(lightbox.menu_items.iter().cloned());
let mut menu = None;
if !items.is_empty() {
let open = self.more_open.clone();
let press: Action = Arc::new(move || open.set(!open.get_untracked()));
end = end.child(Row::new().ref_element(self.more.clone()).child(self.control(
icons::MORE_HORIZONTAL,
&lightbox.words.more,
"more",
press,
)));
menu = Some(
Menu::new(self.more_open.clone(), self.more.clone())
.rules(&self.recipe.lend("menu"))
.label(&lightbox.words.more)
.placement(Placement::BottomEnd)
.items(items)
.build(self.theme()),
);
}
let top = Row::new()
.part(&self.part(LightboxPart::Top))
.width(full)
.align_items(Alignment::Center)
.child(start)
.with_children(self.counter())
.child(end);
match menu {
Some(menu) => Column::new().width(full).child(top).child(menu).into(),
None => top.into(),
}
}
pub fn phone_stage(&mut self) -> Element {
let full = Dimension::Pct(100.0);
let (width, height) = self.room;
let count = self.count();
let mut shown = self.shown.take();
let content: Element = if width > 0.0 && height > 0.0 && count > 1 {
let pages = (0..count).map(|at| {
let page = Stack::new().size(width, height).stack_align(StackAlignment::Center);
if at == self.index {
page.with_children(shown.take())
} else if at + 1 == self.index || at == self.index + 1 {
page.child(self.lightbox.pictures[at].clone().in_viewer().key(format!("page-{at}")))
} else {
page
}
});
let turn = self.turn.clone();
let mut pages = Carousel::new(pages)
.gap(0.0)
.arrows(false)
.dots(false)
.index_controlled(self.index, move |to| turn(to))
.label(&self.lightbox.words.label)
.key("pages");
if let Some(id) = self.id("pages") {
pages = pages.id(id);
}
pages.into()
} else {
Stack::new().size(full, full).with_children(shown).into()
};
let name = self
.lightbox
.pictures
.get(self.index)
.and_then(Picture::label_of)
.unwrap_or_else(|| Arc::from(format!("{} / {count}", self.index + 1)));
let (dropped, close, fitted) = (self.dropped.clone(), self.dismisser(), !self.zoomed());
let taken = self.taken.clone();
let mut room = Stack::new()
.part(&self.part(LightboxPart::Stage))
.width(full)
.flex(1.0)
.clip()
.tab_index(0)
.describe("a11y_role", "group")
.describe("a11y_name", name)
.ref_element(self.stage.clone())
.on_pan(move |event: PanEvent| {
use std::sync::atomic::Ordering;
match event.phase {
GesturePhase::Start => {
let down = event.translation_y > 0.0 && event.translation_y.abs() > event.translation_x.abs();
if fitted && down && event.fingers == 1 {
event.prevent_default();
taken.store(true, Ordering::Relaxed);
dropped.set(event.translation_y);
}
}
GesturePhase::Change if taken.load(Ordering::Relaxed) => dropped.set(event.translation_y.max(0.0)),
GesturePhase::End if taken.swap(false, Ordering::Relaxed) => {
dropped.set(0.0);
if event.translation_y > DROP_CLOSES || event.velocity_y > THROW_CLOSES {
close();
}
}
_ => {}
}
})
.child({
let pictures = Stack::new().size(full, full).offset(0.0, self.drop).child(content);
match self.expand.clone() {
Some(expand) => pictures.on_tap(move |event: TapEvent| {
event.stop_propagation();
expand()
}),
None => pictures,
}
});
if let Some(expanded) = self.expanded.take() {
room = room.child(expanded);
}
if let Some(id) = self.id("stage") {
room = room.id(id);
}
let mut room: Element = room.into();
if !self.lightbox.inline {
NodeUpdate::autofocus(&mut *room.node, true);
}
room
}
pub fn phone_bottom(&self) -> Element {
let full = Dimension::Pct(100.0);
let mut bottom = Column::new()
.part(&self.part(LightboxPart::Bottom))
.width(full)
.align_items(Alignment::Center);
let (title, description) = match self.lightbox.pictures.get(self.index) {
Some(picture) => picture.caption_of(),
None => (None, None),
};
if title.is_some() || description.is_some() {
let mut caption = Column::new().part(&self.part(LightboxPart::Caption)).width(full);
for (part, text) in [(LightboxPart::Title, title), (LightboxPart::Description, description)] {
if let Some(text) = text {
let part = self.part(part);
caption = caption.child(part.text(&text).width(full).part(&part));
}
}
bottom = bottom.child(caption);
}
let count = self.count();
if count > 1 {
let shown = count.min(PAGES_SHOWN);
let first = self.index.saturating_sub(shown / 2).min(count - shown);
let mut pages = Row::new()
.part(&self.part(LightboxPart::Pages))
.align_items(Alignment::Center);
for at in first..first + shown {
let recipe = if at == self.index { &self.current } else { &self.recipe };
let mut page = Row::new().part(&recipe.part(LightboxPart::Page));
if let Some(id) = self.id(&format!("page-{at}")) {
page = page.id(id);
}
pages = pages.child(page);
}
bottom = bottom.child(pages);
}
Column::new()
.width(full)
.padding_bottom(self.safe.bottom)
.child(bottom)
.into()
}
pub fn panel(&mut self) -> Element {
let lightbox = &self.lightbox;
let theme = self.theme();
let (go, turn, shift) = (self.go.clone(), self.turn.clone(), self.shift.clone());
let (zoom, zoomed) = (self.zoom, self.zoomed());
let (before, after) = self.neighbours();
let mut panel = Column::new()
.part(&self.part(LightboxPart::Root))
.clip()
.describe("a11y_role", "dialog")
.describe("a11y_name", lightbox.words.label.clone())
.on_click(|event: MouseEvent| event.stop_propagation())
.on_key_down(move |event: KeyboardEvent| {
if !event.focus_within || event.ctrl || event.alt || event.meta {
return;
}
let handled = match event.key.as_str() {
"+" | "=" => {
go(zoom * ZOOM_STEP);
true
}
"-" | "_" => {
go(zoom / ZOOM_STEP);
true
}
"0" => {
go(1.0);
true
}
"ArrowLeft" if zoomed => {
shift(-PAN_STEP, 0.0);
true
}
"ArrowRight" if zoomed => {
shift(PAN_STEP, 0.0);
true
}
"ArrowUp" if zoomed => {
shift(0.0, -PAN_STEP);
true
}
"ArrowDown" if zoomed => {
shift(0.0, PAN_STEP);
true
}
"ArrowLeft" => before.map(|to| turn(to)).is_some(),
"ArrowRight" => after.map(|to| turn(to)).is_some(),
_ => false,
};
if handled {
event.prevent_default();
event.stop_propagation();
}
});
let full = Dimension::Pct(100.0);
let (width, height) = match lightbox.inline {
true => (
lightbox.width.and_then(|width| width.resolve(theme)).unwrap_or(full),
lightbox.height.and_then(|height| height.resolve(theme)).unwrap_or(full),
),
false => (full, full),
};
panel = panel.size(width, height).max_width(full);
if let Some(id) = &lightbox.id {
panel = panel.id(id.clone());
}
if let (Some(key), true) = (&lightbox.key, lightbox.inline) {
panel = panel.key(key.clone());
}
if self.phone {
if self.drop > 0.0 {
let black = match self.part(LightboxPart::Root).rest().background.clone() {
Some(crate::node::BackgroundColor::Color(color)) => color,
_ => Color::new(0, 0, 0, 255),
};
let left = 1.0 - (self.drop / DROP_FADES).min(0.7);
panel = panel.background(Color::new(
black.r(),
black.g(),
black.b(),
(black.a() as f32 * left) as u8,
));
}
let top = self.phone_top();
let stage = self.phone_stage();
let bottom = self.phone_bottom();
return panel
.padding_top(self.safe.top)
.padding_left(self.safe.left)
.padding_right(self.safe.right)
.child(top)
.child(stage)
.child(bottom)
.into();
}
let top = self.top();
let stage = self.stage();
panel = panel
.padding_top(self.safe.top)
.padding_left(self.safe.left)
.padding_right(self.safe.right)
.padding_bottom(self.safe.bottom)
.child(top)
.child(stage);
if let Some(strip) = self.filmstrip() {
panel = panel.child(strip);
}
panel.into()
}
pub fn render(mut self) -> Element {
let panel = self.panel();
if self.lightbox.inline {
return panel;
}
let mut veil = Column::new()
.size(Dimension::Pct(100.0), Dimension::Pct(100.0))
.part(&self.part(LightboxPart::Veil))
.child(panel);
if self.lightbox.dismiss_on_veil {
let close = self.dismisser();
veil = veil.on_click(move |_: MouseEvent| close());
}
if let Some(key) = &self.lightbox.key {
veil = veil.key(key.clone());
}
let mut modal = Modal::new(veil)
.open(self.lightbox.open.clone())
.target(Root)
.dismiss_on_escape(self.lightbox.dismiss_on_escape)
.takes_focus(true);
for handler in &self.lightbox.on_dismiss {
let handler = handler.clone();
modal = modal.on_dismiss(move || handler());
}
modal.into()
}
}
fn thumb_size(part: &ResolvedPart) -> (f32, f32) {
let px = |length: Option<Length>, or: f32| match length.and_then(|length| length.resolve(part.theme())) {
Some(Dimension::Px(px)) => px,
_ => or,
};
let rest = part.rest();
(px(rest.width, 44.0), px(rest.height, 32.0))
}
impl crate::ui::Styled for Lightbox {
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 Lightbox {
const NAME: &'static str = "lightbox";
type Renderer = LightboxRenderer;
fn parts() -> crate::ui::Declared {
LightboxPart::declared()
}
fn states() -> crate::ui::Declared {
LightboxState::declared()
}
fn recipe() -> Recipe {
use LightboxPart::*;
use LightboxState::{Current, Inline};
let white = Color::new(255, 255, 255, 255);
let white_60 = Color::new(255, 255, 255, 0x99);
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);
Recipe::new()
.base(Root, |s| s.background(Color::new(0x09, 0x09, 0x0B, 0xF2)))
.state(Inline, Root, |s| s.radius(RadiusSize::Lg))
.base(Top, |s| {
s.height(52.0)
.padding_top(8.0)
.padding_bottom(8.0)
.padding_start(16.0)
.padding_end(8.0)
.gap(4.0)
})
.base(Counter, |s| {
s.typography(TypographyStyle::Caption)
.font_family(FontFamily::Mono)
.font_size(12.0)
.foreground(white)
})
.base(Total, |s| {
s.typography(TypographyStyle::Caption)
.font_family(FontFamily::Mono)
.font_size(12.0)
.foreground(white_60)
})
.base(Control, |s| {
fading(
s.square(36.0)
.radius(RadiusSize::Md)
.foreground(white)
.cursor(CursorIcon::Pointer),
)
})
.hovered(Control, |s| s.background(white_12))
.focus_visible(Control, |s| s.outline(Outline::new(2.0, white)))
.focus_visible(Stage, |s| s.outline(Outline::new(2.0, white).offset(-2.0)))
.base(ControlIcon, |s| s.square(20.0))
.base(Level, |s| {
fading(
s.width(56.0)
.height(36.0)
.radius(RadiusSize::Md)
.typography(TypographyStyle::Body)
.font_size(13.0)
.weight(FontWeight::Medium)
.foreground(white)
.cursor(CursorIcon::Pointer),
)
})
.hovered(Level, |s| s.background(white_12))
.focus_visible(Level, |s| s.outline(Outline::new(2.0, white)))
.base(Step, |s| {
fading(
s.square(36.0)
.radius(RadiusSize::Full)
.background(black_40)
.foreground(white)
.cursor(CursorIcon::Pointer),
)
})
.hovered(Step, |s| s.background(black_60))
.focus_visible(Step, |s| s.outline(Outline::new(2.0, white)))
.base(StepIcon, |s| s.square(20.0))
.base(Side, |s| s.padding_x(12.0))
.base(Caption, |s| {
s.background(black_70)
.padding_top(20.0)
.padding_bottom(8.0)
.padding_x(16.0)
.gap(2.0)
})
.base(Title, |s| {
s.typography(TypographyStyle::Body)
.font_size(14.0)
.weight(FontWeight::Medium)
.foreground(white)
})
.base(Description, |s| {
s.typography(TypographyStyle::Body).font_size(13.0).foreground(white_60)
})
.base(Filmstrip, |s| s.height(52.0).gap(6.0))
.base(Thumb, |s| {
s.width(44.0)
.height(32.0)
.radius(RadiusSize::Sm)
.opacity(0.6)
.cursor(CursorIcon::Pointer)
.transition(PartTransition::new(Transition::opacity(), MotionDuration::Fast))
})
.hovered(Thumb, |s| s.opacity(1.0))
.focus_visible(Thumb, |s| s.outline(Outline::new(2.0, white)))
.state(Current, Thumb, |s| s.opacity(1.0).border(Border::inside(2.0, white)))
.variant(LightboxVariant::Phone, Root, |s| {
s.background(Color::new(0, 0, 0, 255)).radius(0.0)
})
.when(
Selector::new().variant(LightboxVariant::Phone).state(Inline),
Root,
|s| s.radius(0.0),
)
.variant(LightboxVariant::Phone, Top, |s| {
s.height(44.0)
.padding_top(0.0)
.padding_bottom(0.0)
.padding_start(4.0)
.padding_end(4.0)
.gap(0.0)
})
.variant(LightboxVariant::Phone, Control, |s| {
s.square(44.0).radius(RadiusSize::Full)
})
.variant(LightboxVariant::Phone, ControlIcon, |s| s.square(24.0))
.variant(LightboxVariant::Phone, Caption, |s| {
s.background(Color::new(0, 0, 0, 0))
.padding_top(0.0)
.padding_bottom(16.0)
.padding_x(16.0)
.gap(2.0)
})
.variant(LightboxVariant::Phone, Title, |s| s.font_size(15.0))
.base(Bottom, |s| s.padding_bottom(8.0))
.base(Pages, |s| s.gap(8.0))
.base(Page, |s| {
s.square(8.0)
.radius(RadiusSize::Full)
.background(Color::new(255, 255, 255, 0x59))
})
.state(Current, Page, |s| s.background(white))
}
}