use std::sync::Arc;
use parking_lot::Mutex;
use super::{
button::{Button, ButtonSize, ButtonState, ButtonVariant},
checkbox::Checkbox,
icons,
listbox::{Listbox, ListboxPart},
names,
part_style::{FontFamily, Length, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::ChangeHandler,
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::Ctx,
theme::{BorderSize, ControlSize, Density, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::{Column, Row, SelectOption},
core::{ElementRef, Signal, SignalValue},
layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
node::{Element, FocusGroup, border::Border, dimension::Dimension, node_kind::TextOverflow},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TransferPart {
Root,
List,
Header,
Title,
Count,
Items,
Item,
ItemLabel,
Empty,
Actions,
}
names!(TransferPart {
Root => "root",
List => "list",
Header => "header",
Title => "title",
Count => "count",
Items => "items",
Item => "item",
ItemLabel => "item_label",
Empty => "empty",
Actions => "actions",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TransferState {
Disabled,
Stacked,
}
names!(TransferState {
Disabled => "disabled",
Stacked => "stacked",
});
pub type TransferRenderer = Arc<dyn Fn(TransferView) -> Element + Send + Sync>;
type Write<T> = Arc<dyn Fn(Vec<T>) + Send + Sync>;
type CountText = Arc<dyn Fn(usize, usize) -> String + Send + Sync>;
const WINDOWED: usize = 200;
#[derive(Clone)]
pub struct Transfer<T: 'static = ()> {
items: Vec<SelectOption<T>>,
value: Vec<T>,
write: Option<Write<T>>,
on_change: Vec<ChangeHandler<[T]>>,
checked: Option<(Vec<T>, Option<Write<T>>)>,
on_checked_change: Vec<ChangeHandler<[T]>>,
source_title: Option<Arc<str>>,
target_title: Option<Arc<str>>,
count_text: CountText,
select_all_label: Option<Arc<str>>,
add_label: Option<Arc<str>>,
remove_label: Option<Arc<str>>,
empty_text: Option<Arc<str>>,
locale: Option<crate::core::InputWords>,
label: Option<Arc<str>>,
disabled: bool,
density: Option<Density>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl<T: Clone + PartialEq + Send + Sync + 'static> Transfer<T> {
pub fn new(value: Signal<Vec<T>>, items: impl IntoIterator<Item = impl Into<SelectOption<T>>>) -> Self
where
Vec<T>: SignalValue,
{
let mut transfer = Self::of(items);
transfer.value = value.get();
transfer.write = Some(Arc::new(move |next| value.set(next)));
transfer
}
pub fn controlled(
value: impl IntoIterator<Item = T>,
items: impl IntoIterator<Item = impl Into<SelectOption<T>>>,
on_change: impl Fn(&[T]) + Send + Sync + 'static,
) -> Self {
let mut transfer = Self::of(items);
transfer.value = value.into_iter().collect();
transfer.on_change(on_change)
}
fn of(items: impl IntoIterator<Item = impl Into<SelectOption<T>>>) -> Self {
Self {
items: items.into_iter().map(Into::into).collect(),
value: Vec::new(),
write: None,
on_change: Vec::new(),
checked: None,
on_checked_change: Vec::new(),
source_title: None,
target_title: None,
count_text: Arc::new(|checked, total| format!("{checked}/{total}")),
select_all_label: None,
add_label: None,
remove_label: None,
empty_text: None,
locale: None,
label: None,
disabled: false,
density: None,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn on_change(mut self, handler: impl Fn(&[T]) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn checked(mut self, checked: Signal<Vec<T>>) -> Self
where
Vec<T>: SignalValue,
{
self.checked = Some((checked.get(), Some(Arc::new(move |next| checked.set(next)))));
self
}
pub fn checked_controlled(
mut self,
checked: impl IntoIterator<Item = T>,
on_checked_change: impl Fn(&[T]) + Send + Sync + 'static,
) -> Self {
self.checked = Some((checked.into_iter().collect(), None));
self.on_checked_change(on_checked_change)
}
pub fn on_checked_change(mut self, handler: impl Fn(&[T]) + Send + Sync + 'static) -> Self {
self.on_checked_change.push(Arc::new(handler));
self
}
pub fn source_title(mut self, title: &str) -> Self {
self.source_title = Some(Arc::from(title));
self
}
pub fn target_title(mut self, title: &str) -> Self {
self.target_title = Some(Arc::from(title));
self
}
pub fn count_text(mut self, text: impl Fn(usize, usize) -> String + Send + Sync + 'static) -> Self {
self.count_text = Arc::new(text);
self
}
pub fn select_all_label(mut self, label: &str) -> Self {
self.select_all_label = Some(Arc::from(label));
self
}
pub fn add_label(mut self, label: &str) -> Self {
self.add_label = Some(Arc::from(label));
self
}
pub fn remove_label(mut self, label: &str) -> Self {
self.remove_label = Some(Arc::from(label));
self
}
pub fn empty_text(mut self, text: &str) -> Self {
self.empty_text = Some(Arc::from(text));
self
}
pub fn locale(mut self, locale: &crate::core::Locale) -> Self {
self.locale = Some(locale.input.clone());
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 density(mut self, density: Density) -> Self {
self.density = Some(density);
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
let kept = Kept {
checked: Arc::default(),
revision: None,
stacked: false,
need: None,
buttons: None,
};
let (view, lists) = self.view(theme, kept);
self.finish(view, lists.map(|list| list.map(|(listbox, _)| listbox.build(theme))))
}
pub fn mount(self, ctx: &mut Ctx) -> Element {
let key = self.key.clone();
let props = TransferProps { transfer: self };
match key {
Some(key) => ctx.mount_keyed::<TransferHost<T>>(&key, props).key(key),
None => ctx.mount::<TransferHost<T>>(props),
}
}
fn finish(&self, mut view: TransferView, lists: [Option<Element>; 2]) -> Element {
let [source, target] = lists;
view.source.list = source;
view.target.list = target;
let theme = view.theme().clone();
match theme.renderer::<Transfer<T>>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
fn case(&self, stacked: bool) -> Case {
Case {
variant: None,
size: None,
density: self.density.map(|density| Name::new(density.as_str())),
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(TransferState::Disabled, self.disabled)
.state(TransferState::Stacked, stacked)
}
fn need(&self, theme: &Theme) -> f32 {
let recipe = theme.resolve::<Transfer<T>>(&self.case(false), Some(&self.rules));
let px = |length: Option<Length>| super::select::px(length, theme).unwrap_or(0.0);
let gap = super::select::spacing(recipe.part(TransferPart::Root).rest().gap, theme).unwrap_or(0.0);
2.0 * px(recipe.part(TransferPart::List).rest().width) + 2.0 * gap + theme.control_size_value(ControlSize::Sm)
}
fn view(&self, theme: &Theme, kept: Kept<T>) -> (TransferView, [Option<(Listbox<T, [T]>, bool)>; 2]) {
let recipe = theme
.resolve::<Transfer<T>>(&self.case(kept.stacked), Some(&self.rules))
.owned_by(self.id.as_ref());
let words = match &self.locale {
Some(words) => words.clone(),
None => super::current_locale().input.clone(),
};
let told = |word: &Option<Arc<str>>, default: &Arc<str>| word.clone().unwrap_or_else(|| default.clone());
let ids: Vec<&T> = self.items.iter().map(SelectOption::value).collect();
let target: Vec<T> = self.value.iter().filter(|value| ids.contains(value)).cloned().collect();
let enabled = |value: &T| {
!self.disabled
&& self
.items
.iter()
.any(|item| item.value() == value && !item.is_disabled())
};
let checked: Vec<T> = match &self.checked {
Some((checked, _)) => checked.clone(),
None => kept.checked.lock().clone(),
};
let checked: Vec<T> = checked.into_iter().filter(|value| enabled(value)).collect();
let model = Arc::new(Model {
order: self.items.iter().map(|item| item.value().clone()).collect(),
value: target.clone(),
checked: checked.clone(),
write: self.write.clone(),
on_change: self.on_change.clone(),
write_checked: match &self.checked {
Some((_, write)) => write.clone(),
None => {
let (held, revision) = (kept.checked.clone(), kept.revision.clone());
Some(Arc::new(move |next| {
*held.lock() = next;
if let Some(revision) = &revision {
revision.update(|revision| *revision += 1);
}
}))
}
},
on_checked_change: self.on_checked_change.clone(),
});
let list_rules = Recipe::new()
.extend(&recipe.rules_for(TransferPart::Items, ListboxPart::Root))
.base(ListboxPart::Content, |s| s.padding_x(0.0).padding_y(0.0).gap(0.0))
.extend(&recipe.rules_for(TransferPart::Item, ListboxPart::Option))
.extend(&recipe.rules_for(TransferPart::ItemLabel, ListboxPart::Label));
let most = super::select::px(recipe.part(TransferPart::Items).rest().max_height, theme);
let side = |is_target: bool| {
let items: Vec<SelectOption<T>> = if is_target {
target
.iter()
.filter_map(|value| self.items.iter().find(|item| item.value() == value).cloned())
.collect()
} else {
self
.items
.iter()
.filter(|item| !target.contains(item.value()))
.cloned()
.collect()
};
let held: Vec<T> = items.iter().map(|item| item.value().clone()).collect();
let on: Vec<T> = checked.iter().filter(|value| held.contains(value)).cloned().collect();
let can: Vec<T> = held.iter().filter(|value| enabled(value)).cloned().collect();
let title = if is_target {
told(&self.target_title, &words.selected)
} else {
told(&self.source_title, &words.available)
};
let name = if is_target { "target" } else { "source" };
let id = self.id.as_ref().map(|id| Arc::<str>::from(format!("{id}-{name}")));
let count = items.len();
let list = (count > 0).then(|| {
let model = model.clone();
let side_values = held.clone();
let mut listbox = Listbox::controlled_multiple(on.clone(), items, move |next: &[T]| {
model.check_in(&side_values, next.to_vec());
})
.checkboxes(true)
.disabled(self.disabled)
.label(&title)
.force(self.forced)
.rules(&list_rules);
if let Some(density) = self.density {
listbox = listbox.density(density);
}
if let Some(id) = &id {
listbox = listbox.id(id.clone());
}
match most {
Some(most) if count > WINDOWED => (listbox.style(ListboxPart::Root, |s| s.height(most)), true),
_ => (listbox, false),
}
});
let all = {
let model = model.clone();
let (side_values, can) = (held.clone(), can.clone());
Arc::new(move |on: bool| model.check_in(&side_values, if on { can.clone() } else { Vec::new() }))
as Arc<dyn Fn(bool) + Send + Sync>
};
let side = TransferList {
title,
count: (self.count_text)(on.len(), count),
checked: on.len(),
can: can.len(),
all_checked: !can.is_empty() && can.iter().all(|value| on.contains(value)),
list: None,
empty_text: told(&self.empty_text, &words.no_items),
select_all_label: told(&self.select_all_label, &words.select_all),
disabled: self.disabled,
all,
recipe: recipe.item(id.as_ref(), TransferPart::List),
id,
};
(side, list)
};
let (source, source_list) = side(false);
let (target_list, target_items) = side(true);
let moving = |to_target: bool| {
let model = model.clone();
Arc::new(move || model.move_checked(to_target)) as Arc<dyn Fn() + Send + Sync>
};
let view = TransferView {
add: (source.checked > 0 && !self.disabled).then(|| moving(true)),
remove: (target_list.checked > 0 && !self.disabled).then(|| moving(false)),
source,
target: target_list,
add_label: told(&self.add_label, &words.add),
remove_label: told(&self.remove_label, &words.remove),
stacked: kept.stacked,
label: self.label.clone(),
disabled: self.disabled,
recipe,
buttons: kept.buttons.clone(),
room: kept.need.map(|(room, need)| {
*need.lock() = self.need(theme);
room
}),
id: self.id.clone(),
key: self.key.clone(),
};
(view, [source_list, target_items])
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> From<Transfer<T>> for Element {
fn from(transfer: Transfer<T>) -> Self {
let key = transfer.key.clone();
let props = TransferProps { transfer };
match key {
Some(key) => Element::component_keyed::<TransferHost<T>>(key, props),
None => Element::component::<TransferHost<T>>(props),
}
}
}
struct Kept<T> {
checked: Arc<Mutex<Vec<T>>>,
revision: Option<Signal<u64>>,
stacked: bool,
need: Option<(ElementRef, Arc<Mutex<f32>>)>,
buttons: Option<[ElementRef; 2]>,
}
struct Model<T> {
order: Vec<T>,
value: Vec<T>,
checked: Vec<T>,
write: Option<Write<T>>,
on_change: Vec<ChangeHandler<[T]>>,
write_checked: Option<Write<T>>,
on_checked_change: Vec<ChangeHandler<[T]>>,
}
impl<T: Clone + PartialEq> Model<T> {
fn set_checked(&self, next: Vec<T>) {
if next == self.checked {
return;
}
if let Some(write) = &self.write_checked {
write(next.clone());
}
for handler in &self.on_checked_change {
handler(&next);
}
}
fn check_in(&self, side: &[T], next: Vec<T>) {
let mut all: Vec<T> = self
.checked
.iter()
.filter(|value| !side.contains(value))
.cloned()
.collect();
all.extend(next);
self.set_checked(all);
}
fn move_checked(&self, to_target: bool) {
let from = if to_target { &self.order } else { &self.value };
let moving: Vec<T> = from
.iter()
.filter(|value| self.checked.contains(value) && self.value.contains(value) != to_target)
.cloned()
.collect();
if moving.is_empty() {
return;
}
let next: Vec<T> = if to_target {
self.value.iter().chain(&moving).cloned().collect()
} else {
self
.value
.iter()
.filter(|value| !moving.contains(value))
.cloned()
.collect()
};
if let Some(write) = &self.write {
write(next.clone());
}
for handler in &self.on_change {
handler(&next);
}
self.set_checked(
self
.checked
.iter()
.filter(|value| !moving.contains(value))
.cloned()
.collect(),
);
}
}
pub struct TransferView {
pub source: TransferList,
pub target: TransferList,
pub stacked: bool,
pub label: Option<Arc<str>>,
pub disabled: bool,
pub recipe: ResolvedRecipe,
add: Option<Arc<dyn Fn() + Send + Sync>>,
remove: Option<Arc<dyn Fn() + Send + Sync>>,
add_label: Arc<str>,
remove_label: Arc<str>,
room: Option<ElementRef>,
buttons: Option<[ElementRef; 2]>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl TransferView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn button(&self, to_target: bool) -> Element {
let (run, label, variant) = if to_target {
(&self.add, &self.add_label, ButtonVariant::Primary)
} else {
(&self.remove, &self.remove_label, ButtonVariant::Outline)
};
let icon = match (to_target, self.stacked) {
(true, false) => icons::CHEVRON_RIGHT,
(true, true) => icons::CHEVRON_DOWN,
(false, false) => icons::CHEVRON_LEFT,
(false, true) => icons::CHEVRON_UP,
};
let element = self
.buttons
.as_ref()
.map(|buttons| buttons[usize::from(!to_target)].clone());
let held = run.is_none() && element.as_ref().is_some_and(ElementRef::focused);
let mut button = Button::new(label)
.variant(variant)
.size(ButtonSize::Sm)
.icon(icon)
.icon_only(true)
.disabled(run.is_none() && !held)
.state(ButtonState::Disabled, held);
if let Some(run) = run.clone() {
button = button.on_click(move |_: crate::app::events::MouseEvent| run());
}
if let Some(element) = element {
button = button.ref_element(element);
}
if let Some(id) = &self.id {
button = button.id(format!("{id}-{}", if to_target { "add" } else { "remove" }));
}
let button = button.build(self.theme());
if held {
button.decorate_root(|mut node| {
crate::node::NodeUpdate::describe(&mut node, Arc::from("a11y_disabled"), Arc::from("true"));
node
})
} else {
button
}
}
pub fn actions(&self) -> Element {
let part = self.part(TransferPart::Actions);
let buttons = [self.button(true), self.button(false)];
if self.stacked {
Row::new()
.justify(Justify::Center)
.align_items(Alignment::Center)
.focus_group(FocusGroup::horizontal().wrap(false))
.part(&part)
.with_children(buttons)
.into()
} else {
Column::new()
.align_items(Alignment::Center)
.flex_shrink(0.0)
.focus_group(FocusGroup::vertical().wrap(false))
.part(&part)
.with_children(buttons)
.into()
}
}
pub fn render(mut self) -> Element {
let actions = self.actions();
let (source, target) = (
std::mem::replace(&mut self.source.list, None),
std::mem::replace(&mut self.target.list, None),
);
let (source, target) = (self.source.render(source), self.target.render(target));
let part = self.part(TransferPart::Root);
let fill = Dimension::Pct(100.0);
let mut root = if self.stacked {
Column::new()
.width(fill)
.align_items(Alignment::Stretch)
.part(&part)
.child(source)
.child(actions)
.child(target)
} else {
Column::new().child(
Row::new()
.align_items(Alignment::Center)
.part(&part)
.child(source)
.child(actions)
.child(target),
)
}
.describe("a11y_role", "group");
if let Some(label) = &self.label {
root = root.describe("a11y_name", label.clone());
}
if self.disabled {
root = root.describe("a11y_disabled", "true");
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
match self.room {
Some(room) => Column::new()
.width(fill)
.align_items(if self.stacked {
Alignment::Stretch
} else {
Alignment::Start
})
.ref_element(room)
.child(root)
.into(),
None => root.into(),
}
}
}
pub struct TransferList {
pub title: Arc<str>,
pub count: String,
pub checked: usize,
pub can: usize,
pub all_checked: bool,
pub list: Option<Element>,
pub disabled: bool,
empty_text: Arc<str>,
select_all_label: Arc<str>,
all: Arc<dyn Fn(bool) + Send + Sync>,
pub recipe: ResolvedRecipe,
id: Option<Arc<str>>,
}
impl TransferList {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn select_all(&self) -> Element {
let all = self.all.clone();
let mut checkbox = Checkbox::new(&self.select_all_label)
.label_hidden(true)
.checked(self.all_checked)
.indeterminate(self.checked > 0 && !self.all_checked)
.disabled(self.disabled || self.can == 0)
.on_change(move |on| all(on));
if let Some(id) = &self.id {
checkbox = checkbox.id(format!("{id}-all"));
}
checkbox.build(self.theme())
}
pub fn header(&self) -> Row {
let (title, count) = (self.part(TransferPart::Title), self.part(TransferPart::Count));
Row::new()
.align_items(Alignment::Center)
.part(&self.part(TransferPart::Header))
.child(Row::new().flex_shrink(0.0).child(self.select_all()))
.child(
Row::new()
.flex_full(1.0, 1.0, Some(0.0))
.min_width(0.0)
.part(&title)
.child(title.text(&self.title).nowrap().text_overflow(TextOverflow::Elipsis)),
)
.child(
Row::new()
.flex_shrink(0.0)
.part(&count)
.child(count.text(&self.count).nowrap()),
)
}
pub fn render(&self, list: Option<Element>) -> Element {
let body: Element = match list {
Some(list) => list,
None => {
let empty = self.part(TransferPart::Empty);
Row::new().part(&empty).child(empty.text(&self.empty_text)).into()
}
};
Column::new()
.align_items(Alignment::Stretch)
.part(&self.part(TransferPart::List))
.child(self.header())
.child(body)
.into()
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> crate::ui::Styled for Transfer<T> {
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<T: Send + Sync + 'static> Themed for Transfer<T> {
const NAME: &'static str = "transfer";
type Renderer = TransferRenderer;
fn parts() -> crate::ui::Declared {
TransferPart::declared()
}
fn states() -> crate::ui::Declared {
TransferState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{Background, Foreground, MutedForeground};
use TransferPart::{Actions, Count, Empty, Header, Item, ItemLabel, Items, List, Root, Title};
let edge = |width: f32| Border::inside(width, PaletteColor::Border);
Recipe::new()
.base(Root, |s| s.gap(12.0))
.base(List, |s| {
s.width(190.0)
.max_width(Length::Fill)
.background(Background)
.foreground(Foreground)
.border(Border::inside(BorderSize::Sm, PaletteColor::Border))
.radius(RadiusSize::Lg)
})
.state(TransferState::Stacked, List, |s| s.width(Length::Fill))
.base(Header, |s| {
s.height(36.0)
.padding_x(12.0)
.gap(8.0)
.background(PaletteColor::Bar)
.underline(edge(1.0))
})
.base(Title, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.weight(FontWeight::Medium)
.foreground(Foreground)
})
.base(Count, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(Items, |s| {
s.width(Length::Fill)
.max_height(264.0)
.padding_y(4.0)
.radius(0.0)
.border(edge(0.0))
.background(Background)
})
.base(Item, |s| s.height(32.0).padding_x(12.0).gap(8.0).radius(0.0))
.row_density(Selector::new(), Item, 32.0)
.base(ItemLabel, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(Foreground)
})
.base(Empty, |s| {
s.padding_x(12.0)
.padding_y(12.0)
.font_size(13.0)
.foreground(MutedForeground)
})
.base(Actions, |s| s.gap(8.0))
.state(TransferState::Disabled, Root, |s| s.opacity(OpacityLevel::Disabled))
}
}
#[derive(Clone)]
struct TransferProps<T: 'static> {
transfer: Transfer<T>,
}
impl<T> PartialEq for TransferProps<T> {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl<T> crate::app::component::DevtoolsInspectable for TransferProps<T> {
fn inspect(&self, formatter: &mut crate::app::component::DevtoolsFormatter<'_>) {
formatter.value("Transfer", format!("{} items", self.transfer.items.len()));
}
}
struct TransferHost<T> {
buttons: [ElementRef; 2],
checked: Arc<Mutex<Vec<T>>>,
revision: Signal<u64>,
stacked: Signal<bool>,
room: ElementRef,
need: Arc<Mutex<f32>>,
}
impl<T: Clone + PartialEq + Send + Sync + 'static> Component for TransferHost<T> {
type Props = TransferProps<T>;
fn create(ctx: &mut Ctx) -> Self {
let (room, stacked, need) = (ElementRef::new(), ctx.signal(false), Arc::new(Mutex::new(0.0_f32)));
let (watch, needed) = (stacked.clone(), need.clone());
room.observe_rect_before_paint(move |rect| {
let now = rect.width < *needed.lock() - 0.5;
if watch.get_untracked() != now {
watch.set(now);
}
});
Self {
buttons: [ElementRef::new(), ElementRef::new()],
checked: Arc::default(),
revision: ctx.signal(0_u64),
stacked,
room,
need,
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
self.revision.get();
for button in &self.buttons {
button.focus_signal().get();
}
let kept = Kept {
checked: self.checked.clone(),
revision: Some(self.revision.clone()),
stacked: self.stacked.get(),
need: Some((self.room.clone(), self.need.clone())),
buttons: Some(self.buttons.clone()),
};
let theme = current_theme();
let (view, lists) = ctx.props::<TransferProps<T>>().transfer.view(&theme, kept);
let lists = lists.map(|list| {
list.map(|(listbox, long)| {
if long {
listbox.mount(ctx)
} else {
listbox.build(&theme)
}
})
});
ctx.props::<TransferProps<T>>().transfer.finish(view, lists)
}
}