use std::{marker::PhantomData, sync::Arc};
use parking_lot::Mutex;
use super::{
Lightbox, Picture, PictureSize, names,
part_style::Length,
recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe},
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::Ctx,
events::{KeyboardEvent, MouseEvent},
theme::Theme,
},
components::{Column, Row},
core::{ElementRef, Signal},
node::{Element, FocusGroup, dimension::Dimension},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum GalleryPart {
Root,
Row,
Cell,
}
names!(GalleryPart {
Root => "root",
Row => "row",
Cell => "cell",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum GalleryState {
Selectable,
Disabled,
}
names!(GalleryState {
Selectable => "selectable",
Disabled => "disabled",
});
pub type GalleryRenderer = Arc<dyn Fn(GalleryView) -> Element + Send + Sync>;
type Told<T> = Arc<dyn Fn(T) + Send + Sync>;
pub const GALLERY_LEAST_PICTURE: f32 = 92.0;
fn fitting(columns: usize, least: f32, gap: f32, room: f32) -> usize {
if least <= 0.0 {
return columns;
}
(((room + gap) / (least + gap)).floor() as usize).clamp(1, columns)
}
pub trait GalleryKey: Clone + PartialEq + Send + Sync + 'static {}
impl<T: Clone + PartialEq + Send + Sync + 'static> GalleryKey for T {}
pub struct Gallery<K = usize> {
items: Vec<(K, Picture)>,
columns: usize,
least: f32,
gap: f32,
aspect_ratio: f32,
size: Name,
width: Option<Length>,
max_shown: Option<usize>,
more_text: Option<Arc<dyn Fn(usize) -> String + Send + Sync>>,
selectable: bool,
selected: Option<Signal<Vec<K>>>,
controlled: Option<Vec<K>>,
on_selection_change: Vec<Arc<dyn Fn(&[K]) + Send + Sync>>,
lightbox: bool,
open: Option<Signal<Option<usize>>>,
on_open_change: Vec<Told<Option<usize>>>,
on_select: Vec<Told<usize>>,
label: Option<Arc<str>>,
disabled: bool,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl<K: Clone> Clone for Gallery<K> {
fn clone(&self) -> Self {
Self {
items: self.items.clone(),
columns: self.columns,
least: self.least,
gap: self.gap,
aspect_ratio: self.aspect_ratio,
size: self.size,
width: self.width,
max_shown: self.max_shown,
more_text: self.more_text.clone(),
selectable: self.selectable,
selected: self.selected.clone(),
controlled: self.controlled.clone(),
on_selection_change: self.on_selection_change.clone(),
lightbox: self.lightbox,
open: self.open.clone(),
on_open_change: self.on_open_change.clone(),
on_select: self.on_select.clone(),
label: self.label.clone(),
disabled: self.disabled,
states: self.states.clone(),
rules: self.rules.clone(),
id: self.id.clone(),
key: self.key.clone(),
}
}
}
impl Gallery<usize> {
pub fn new(pictures: impl IntoIterator<Item = Picture>) -> Self {
Self::keyed(pictures.into_iter().enumerate())
}
pub fn picture(mut self, picture: Picture) -> Self {
self.items.push((self.items.len(), picture));
self
}
pub fn pictures(mut self, pictures: impl IntoIterator<Item = Picture>) -> Self {
for picture in pictures {
self = self.picture(picture);
}
self
}
}
impl<K: GalleryKey> Gallery<K> {
pub fn keyed(items: impl IntoIterator<Item = (K, Picture)>) -> Self {
Self {
items: items.into_iter().collect(),
columns: 4,
least: GALLERY_LEAST_PICTURE,
gap: 8.0,
aspect_ratio: 92.0 / 68.0,
size: PictureSize::Sm.into(),
width: None,
max_shown: None,
more_text: None,
selectable: false,
selected: None,
controlled: None,
on_selection_change: Vec::new(),
lightbox: true,
open: None,
on_open_change: Vec::new(),
on_select: Vec::new(),
label: None,
disabled: false,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
pub fn item(mut self, key: K, picture: Picture) -> Self {
self.items.push((key, picture));
self
}
pub fn columns(mut self, columns: usize) -> Self {
self.columns = columns.max(1);
self
}
pub fn min_picture_width(mut self, width: f32) -> Self {
self.least = width.max(0.0);
self
}
pub fn gap(mut self, gap: f32) -> Self {
self.gap = gap.max(0.0);
self
}
pub fn aspect_ratio(mut self, ratio: f32) -> Self {
if ratio.is_finite() && ratio > 0.0 {
self.aspect_ratio = ratio;
}
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
pub fn width(mut self, width: impl Into<Length>) -> Self {
self.width = Some(width.into());
self
}
pub fn max_shown(mut self, max: usize) -> Self {
self.max_shown = Some(max.max(1));
self
}
pub fn more_text(mut self, text: impl Fn(usize) -> String + Send + Sync + 'static) -> Self {
self.more_text = Some(Arc::new(text));
self
}
pub fn selectable(mut self, selectable: bool) -> Self {
self.selectable = selectable;
self
}
pub fn selected(mut self, selected: Signal<Vec<K>>) -> Self {
self.selected = Some(selected);
self
}
pub fn selected_controlled(mut self, keys: Vec<K>, on_change: impl Fn(&[K]) + Send + Sync + 'static) -> Self {
self.controlled = Some(keys);
self.on_selection_change.push(Arc::new(on_change));
self
}
pub fn on_selection_change(mut self, handler: impl Fn(&[K]) + Send + Sync + 'static) -> Self {
self.on_selection_change.push(Arc::new(handler));
self
}
pub fn lightbox(mut self, lightbox: bool) -> Self {
self.lightbox = lightbox;
self
}
pub fn open(mut self, open: Signal<Option<usize>>) -> Self {
self.open = Some(open);
self
}
pub fn on_open_change(mut self, handler: impl Fn(Option<usize>) + Send + Sync + 'static) -> Self {
self.on_open_change.push(Arc::new(handler));
self
}
pub fn on_select(mut self, handler: impl Fn(usize) + Send + Sync + 'static) -> Self {
self.on_select.push(Arc::new(handler));
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(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 = GalleryProps(self);
match key {
Some(key) => ctx.mount_keyed::<GalleryHost<K>>(&key, props),
None => ctx.mount::<GalleryHost<K>>(props),
}
}
}
impl<K: GalleryKey> From<Gallery<K>> for Element {
fn from(gallery: Gallery<K>) -> Self {
let key = gallery.key.clone();
let props = GalleryProps(gallery);
match key {
Some(key) => Element::component_keyed::<GalleryHost<K>>(key, props),
None => Element::component::<GalleryHost<K>>(props),
}
}
}
struct GalleryProps<K>(Gallery<K>);
impl<K: Clone> Clone for GalleryProps<K> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<K> PartialEq for GalleryProps<K> {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl<K> crate::app::component::DevtoolsInspectable for GalleryProps<K> {}
struct GalleryHost<K> {
selected: Signal<Vec<K>>,
open: Signal<Option<usize>>,
shown: Signal<bool>,
root: ElementRef,
fit: Arc<Mutex<Fit>>,
refit: Signal<u64>,
_keys: PhantomData<fn() -> K>,
}
#[derive(Clone, Copy, Default)]
struct Fit {
room: Option<f32>,
columns: usize,
least: f32,
gap: f32,
in_a_row: usize,
}
impl Fit {
fn settle(&mut self) -> bool {
let in_a_row = match self.room {
Some(room) => fitting(self.columns.max(1), self.least, self.gap, room),
None => self.columns.max(1),
};
let changed = in_a_row != self.in_a_row;
self.in_a_row = in_a_row;
changed
}
}
impl<K: GalleryKey> Component for GalleryHost<K> {
type Props = GalleryProps<K>;
fn create(ctx: &mut Ctx) -> Self {
let (root, fit, refit) = (
ElementRef::new(),
Arc::new(Mutex::new(Fit::default())),
ctx.signal(0u64),
);
{
let (fit, refit) = (fit.clone(), refit.clone());
root.observe_rect_before_paint(move |rect| {
let changed = {
let mut fit = fit.lock();
fit.room = Some(rect.width);
fit.settle()
};
if changed {
refit.update(|refit| *refit = refit.wrapping_add(1));
}
});
}
Self {
selected: ctx.signal(Vec::new()),
open: ctx.signal(None),
shown: ctx.signal(false),
root,
fit,
refit,
_keys: PhantomData,
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let gallery = ctx.props::<GalleryProps<K>>().0.clone();
let theme = current_theme();
let total = gallery.items.len();
let _ = self.refit.get();
let in_a_row = {
let mut fit = self.fit.lock();
(fit.columns, fit.least, fit.gap) = (gallery.columns, gallery.least, gallery.gap);
fit.settle();
fit.in_a_row
};
let open_signal = gallery.open.clone().unwrap_or_else(|| self.open.clone());
let opened = open_signal.get().filter(|at| *at < total);
let selected_signal = gallery.selected.clone().unwrap_or_else(|| self.selected.clone());
let chosen = gallery.controlled.clone().unwrap_or_else(|| selected_signal.get());
if self.shown.get_untracked() != opened.is_some() {
self.shown.set(opened.is_some());
}
let show: Told<Option<usize>> = {
let (open, shown, told) = (open_signal.clone(), self.shown.clone(), gallery.on_open_change.clone());
Arc::new(move |at: Option<usize>| {
if open.get_untracked() != at {
open.set(at);
}
if shown.get_untracked() != at.is_some() {
shown.set(at.is_some());
}
told.iter().for_each(|tell| tell(at));
})
};
let choose: Arc<dyn Fn(&K, bool) + Send + Sync> = {
let (signal, controlled, told) = (
selected_signal.clone(),
gallery.controlled.is_some(),
gallery.on_selection_change.clone(),
);
let chosen = chosen.clone();
Arc::new(move |key: &K, on: bool| {
let mut next = chosen.clone();
next.retain(|held| held != key);
if on {
next.push(key.clone());
}
if !controlled {
signal.set(next.clone());
}
told.iter().for_each(|tell| tell(&next));
})
};
let shown_count = gallery.max_shown.map_or(total, |max| max.min(total));
let more = (total > shown_count).then(|| total - shown_count + 1);
let mut cells = Vec::with_capacity(shown_count);
for (at, (key, picture)) in gallery.items.iter().enumerate().take(shown_count) {
let stands_for_more = more.filter(|_| at + 1 == shown_count);
let mut cell = picture
.clone()
.in_grid()
.size(gallery.size)
.disabled(gallery.disabled)
.key(format!("picture-{at}"));
if let Some(id) = &gallery.id {
cell = cell.id(format!("{id}-{at}"));
}
let opens = gallery.lightbox;
if let Some(more) = stands_for_more {
let text = match &gallery.more_text {
Some(text) => text(more),
None => format!("+{more}"),
};
cell = cell.count(&text);
}
if gallery.selectable && stands_for_more.is_none() {
let (choose, key) = (choose.clone(), key.clone());
cell = cell
.selectable(true)
.selected(chosen.contains(&key))
.on_change(move |on| choose(&key, on));
} else if opens {
let show = show.clone();
cell = cell.on_click(move |_: MouseEvent| show(Some(at)));
} else if !gallery.on_select.is_empty() {
let told = gallery.on_select.clone();
cell = cell.on_click(move |_: MouseEvent| told.iter().for_each(|tell| tell(at)));
}
let enter = (opens && gallery.selectable && !gallery.disabled).then(|| show.clone());
cells.push((Element::from(cell), enter.map(|show| (show, at))));
}
let viewer = (gallery.lightbox && total > 0).then(|| {
let (turn, close) = (show.clone(), show.clone());
let mut viewer = Lightbox::new(
self.shown.clone(),
gallery.items.iter().map(|(_, picture)| picture.clone()),
)
.index_controlled(opened.unwrap_or(0), move |at| turn(Some(at)))
.on_dismiss(move || close(None))
.key("viewer");
if let Some(label) = &gallery.label {
viewer = viewer.label(label);
}
if let Some(id) = &gallery.id {
viewer = viewer.id(format!("{id}-viewer"));
}
Element::from(viewer)
});
let case = Case {
variant: None,
size: Some(gallery.size),
density: None,
breakpoint: super::current_breakpoint(),
states: gallery.states.clone(),
}
.state(GalleryState::Selectable, gallery.selectable)
.state(GalleryState::Disabled, gallery.disabled);
let view = GalleryView {
recipe: theme
.resolve::<Gallery<K>>(&case, Some(&gallery.rules))
.owned_by(gallery.id.as_ref()),
cells,
viewer,
columns: in_a_row,
gap: gallery.gap,
root: self.root.clone(),
aspect_ratio: gallery.aspect_ratio,
width: gallery.width,
selectable: gallery.selectable,
label: gallery.label.clone(),
id: gallery.id.clone(),
key: gallery.key.clone(),
};
match theme.renderer::<Gallery<K>>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
pub struct GalleryView {
pub recipe: ResolvedRecipe,
cells: Vec<(Element, Option<(Told<Option<usize>>, usize)>)>,
viewer: Option<Element>,
pub columns: usize,
pub gap: f32,
pub aspect_ratio: f32,
pub width: Option<Length>,
pub selectable: bool,
label: Option<Arc<str>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
root: ElementRef,
}
impl GalleryView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn render(self) -> Element {
let full = Dimension::Pct(100.0);
let width = self.width.and_then(|width| width.resolve(self.theme())).unwrap_or(full);
let (row_part, cell_part) = (self.part(GalleryPart::Row), self.part(GalleryPart::Cell));
let mut root = Column::new()
.part(&self.part(GalleryPart::Root))
.width(width)
.max_width(full)
.spacing(self.gap)
.focus_group(FocusGroup::both().one_stop(true))
.ref_element(self.root.clone())
.describe("a11y_role", if self.selectable { "listbox" } else { "list" });
if let Some(label) = &self.label {
root = root.describe("a11y_name", label.clone());
}
if self.selectable {
root = root.describe("a11y_multiselectable", "true");
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
let columns = self.columns.max(1);
let mut cells = self.cells.into_iter().peekable();
while cells.peek().is_some() {
let mut row = Row::new().part(&row_part).width(full).spacing(self.gap);
for _ in 0..columns {
let mut room = Row::new()
.part(&cell_part)
.flex(1.0)
.min_width(0.0)
.aspect_ratio(self.aspect_ratio);
if let Some((picture, enter)) = cells.next() {
if let Some((show, at)) = enter {
room = room.on_key_down(move |event: KeyboardEvent| {
if event.key == "Enter" && event.focus_within {
event.prevent_default();
event.stop_propagation();
show(Some(at));
}
});
}
room = room.child(picture);
}
row = row.child(room);
}
root = root.child(row);
}
if let Some(viewer) = self.viewer {
root = root.child(viewer);
}
root.into()
}
}
impl<K: GalleryKey> crate::ui::Styled for Gallery<K> {
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<K: Send + Sync + 'static> Themed for Gallery<K> {
const NAME: &'static str = "gallery";
type Renderer = GalleryRenderer;
fn parts() -> crate::ui::Declared {
GalleryPart::declared()
}
fn states() -> crate::ui::Declared {
GalleryState::declared()
}
fn recipe() -> Recipe {
Recipe::new()
}
}