use std::{
marker::PhantomData,
sync::{
Arc, Mutex,
atomic::{AtomicU64, Ordering},
},
};
use super::{
icons, names,
part_style::{FontFamily, Length, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
selection::{ListSelection, Pick, select_all_handler},
shared::{ChangeHandler, fading, glyph, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::Ctx,
events::MouseEvent,
theme::{BorderSize, Density, IconSize, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::{self, Column, Row, ScrollVertical, SelectOption, VirtualizedList},
core::{Signal, SignalValue},
layout::{
Alignment,
layout_kind::{Justify, ScrollState},
text_style::FontWeight,
},
node::{
CursorIcon, Element, FocusGroup, FocusRows, SelectAdornmentState, SpacingValue, border::Border, color::Color,
dimension::Dimension, node_kind::TextOverflow, outline::Outline,
},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ListboxPart {
Root,
Content,
Group,
Option,
Leading,
Label,
Detail,
Hint,
Trailing,
Check,
}
names!(ListboxPart {
Root => "root",
Content => "content",
Group => "group",
Option => "option",
Leading => "leading",
Label => "label",
Detail => "detail",
Hint => "hint",
Trailing => "trailing",
Check => "check",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ListboxState {
Chosen,
OptionDisabled,
Detail,
Checkboxes,
Disabled,
Invalid,
Multiple,
FullWidth,
}
names!(ListboxState {
Chosen => "chosen",
OptionDisabled => "option_disabled",
Detail => "detail",
Checkboxes => "checkboxes",
Disabled => "disabled",
Invalid => "invalid",
Multiple => "multiple",
FullWidth => "full_width",
});
pub type ListboxRenderer = Arc<dyn Fn(ListboxView) -> Element + Send + Sync>;
type Tell<T, V> = fn(&[T], &[ChangeHandler<V>]);
type Write<T> = Arc<dyn Fn(Vec<T>) + Send + Sync>;
fn tell_one<T>(next: &[T], handlers: &[ChangeHandler<T>]) {
if let Some(value) = next.last() {
for handler in handlers {
handler(value);
}
}
}
fn tell_optional<T: Clone>(next: &[T], handlers: &[ChangeHandler<Option<T>>]) {
let value = next.last().cloned();
for handler in handlers {
handler(&value);
}
}
fn tell_many<T>(next: &[T], handlers: &[ChangeHandler<[T]>]) {
for handler in handlers {
handler(next);
}
}
pub struct Listbox<T, V: ?Sized = T> {
options: Vec<SelectOption<T>>,
chosen: Vec<T>,
write: Write<T>,
many: bool,
tell: Tell<T, V>,
follow_focus: bool,
checkboxes: bool,
on_change: Vec<ChangeHandler<V>>,
label: Option<Arc<str>>,
description: Option<Arc<str>>,
invalid: bool,
disabled: bool,
full_width: 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> Listbox<T, T> {
pub fn new(value: Signal<T>, options: impl IntoIterator<Item = impl Into<SelectOption<T>>>) -> Self
where
T: SignalValue,
{
let chosen = vec![value.get()];
let write = Arc::new(move |next: Vec<T>| {
if let Some(next) = next.into_iter().last()
&& value.get_untracked() != next
{
value.set(next);
}
});
Self::of(options, chosen, write, false, tell_one::<T>)
}
pub fn controlled(
value: T,
options: impl IntoIterator<Item = impl Into<SelectOption<T>>>,
on_change: impl Fn(&T) + Send + Sync + 'static,
) -> Self {
Self::of(options, vec![value], Arc::new(|_| {}), false, tell_one::<T>).on_change(on_change)
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> Listbox<T, Option<T>> {
pub fn optional(value: Signal<Option<T>>, options: impl IntoIterator<Item = impl Into<SelectOption<T>>>) -> Self
where
Option<T>: SignalValue,
{
let chosen = value.get().into_iter().collect();
let write = Arc::new(move |next: Vec<T>| {
let next = next.into_iter().last();
if next.is_some() && value.get_untracked() != next {
value.set(next);
}
});
Self::of(options, chosen, write, false, tell_optional::<T>)
}
pub fn controlled_optional(
value: Option<T>,
options: impl IntoIterator<Item = impl Into<SelectOption<T>>>,
on_change: impl Fn(&Option<T>) + Send + Sync + 'static,
) -> Self {
let chosen = value.into_iter().collect();
Self::of(options, chosen, Arc::new(|_| {}), false, tell_optional::<T>).on_change(on_change)
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> Listbox<T, [T]> {
pub fn multiple(values: Signal<Vec<T>>, options: impl IntoIterator<Item = impl Into<SelectOption<T>>>) -> Self
where
Vec<T>: SignalValue,
{
let chosen = values.get();
let write = Arc::new(move |next: Vec<T>| values.set(next));
Self::of(options, chosen, write, true, tell_many::<T>)
}
pub fn controlled_multiple(
values: impl IntoIterator<Item = T>,
options: impl IntoIterator<Item = impl Into<SelectOption<T>>>,
on_change: impl Fn(&[T]) + Send + Sync + 'static,
) -> Self {
let chosen = values.into_iter().collect();
Self::of(options, chosen, Arc::new(|_| {}), true, tell_many::<T>).on_change(on_change)
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> Listbox<T, V> {
fn of(
options: impl IntoIterator<Item = impl Into<SelectOption<T>>>,
chosen: Vec<T>,
write: Write<T>,
many: bool,
tell: Tell<T, V>,
) -> Self {
Self {
options: options.into_iter().map(Into::into).collect(),
chosen,
write,
many,
tell,
follow_focus: true,
checkboxes: false,
on_change: Vec::new(),
label: None,
description: None,
invalid: false,
disabled: false,
full_width: false,
density: None,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn follow_focus(mut self, follow: bool) -> Self {
self.follow_focus = follow;
self
}
pub fn checkboxes(mut self, checkboxes: bool) -> Self {
self.checkboxes = checkboxes;
self
}
pub fn on_change(mut self, handler: impl Fn(&V) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.invalid = invalid;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
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 view = self.view(theme);
match theme.renderer::<Self>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
fn view(&self, theme: &Theme) -> ListboxView {
let base = Case {
variant: None,
size: None,
density: self.density.map(|density| Name::new(density.as_str())),
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(ListboxState::Multiple, self.many)
.state(ListboxState::Checkboxes, self.checks())
.state(ListboxState::Disabled, self.disabled)
.state(ListboxState::Invalid, self.invalid)
.state(ListboxState::FullWidth, self.full_width);
let root = theme
.resolve::<Self>(&base, Some(&self.rules))
.owned_by(self.id.as_ref());
let resolve = |chosen: bool, disabled: bool, detail: bool| {
let case = base
.clone()
.state(ListboxState::Chosen, chosen)
.state(ListboxState::OptionDisabled, disabled)
.state(ListboxState::Detail, detail);
theme.resolve::<Self>(&case, Some(&self.rules)).owned_like(&root)
};
let cases = [false, true]
.map(|chosen| [false, true].map(|disabled| [false, true].map(|detail| resolve(chosen, disabled, detail))));
let many = self.many;
let ids: Vec<T> = self.options.iter().map(|option| option.value().clone()).collect();
let enabled: Vec<bool> = self
.options
.iter()
.map(|option| !self.disabled && !option.is_disabled())
.collect();
let chosen: Vec<T> = self
.chosen
.iter()
.filter(|value| ids.contains(value))
.cloned()
.collect();
let entry = (0..ids.len()).find(|index| enabled[*index] && chosen.contains(&ids[*index]));
let write = {
let (write, tell, on_change) = (self.write.clone(), self.tell, self.on_change.clone());
Arc::new(move |next: Vec<T>| {
write(next.clone());
tell(&next, &on_change);
}) as Write<T>
};
let checks = self.checks();
let selection =
Arc::new(ListSelection::new(ids, enabled.clone(), chosen.clone(), many, Some(write)).adding(checks));
let boxes = checks.then(|| {
[false, true].map(|checked| {
[false, true].map(|disabled| {
theme.resolve::<super::Checkbox>(
&Case::new()
.state(super::CheckboxState::Checked, checked)
.state(super::CheckboxState::Disabled, disabled)
.breakpoint(super::current_breakpoint()),
None,
)
})
})
});
let mut position = 0;
let options = self
.options
.iter()
.enumerate()
.map(|(index, option)| {
let is_chosen = chosen.contains(option.value());
let disabled = !enabled[index];
let id: Option<Arc<str>> = self.id.as_ref().map(|id| Arc::from(format!("{id}-{index}")));
let recipe = cases[usize::from(is_chosen)][usize::from(option.is_disabled())]
[usize::from(option.detail_text().is_some())]
.item(id.as_ref(), ListboxPart::Option);
let state = SelectAdornmentState {
selected: is_chosen,
disabled,
..SelectAdornmentState::default()
};
let (leading, trailing) = option.adornments(&state);
position += 1;
let pick = (!disabled).then(|| {
let selection = selection.clone();
Arc::new(move |pick: Pick| selection.pick(index, pick)) as Arc<dyn Fn(Pick) + Send + Sync>
});
let select_all = (!disabled && many).then(|| {
let selection = selection.clone();
Arc::new(move || selection.select_all()) as Arc<dyn Fn() + Send + Sync>
});
ListboxOption {
label: Arc::from(option.label()),
group: option.starts_group().map(Arc::from),
detail: option.detail_text().cloned(),
hint: option.hint_text().cloned(),
leading,
trailing,
chosen: is_chosen,
disabled,
entry: entry == Some(index),
position: (position, 0),
multiple: many,
checkbox: boxes.as_ref().map(|boxes| {
boxes[usize::from(is_chosen)][usize::from(disabled)]
.clone()
.owned_like(&recipe)
}),
recipe,
forced: self.forced,
pick,
select_all,
row: None,
id,
}
})
.collect::<Vec<_>>();
let count = options.len();
let options = options
.into_iter()
.map(|mut option| {
option.position.1 = count;
option
})
.collect();
ListboxView {
options,
multiple: many,
follow_focus: self.follow_focus && !many,
disabled: self.disabled,
label: self.label.clone(),
description: self.description.clone(),
recipe: root,
id: self.id.clone(),
key: self.key.clone(),
}
}
fn checks(&self) -> bool {
self.checkboxes && self.many
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> From<Listbox<T, V>> for Element {
fn from(listbox: Listbox<T, V>) -> Self {
listbox.build(¤t_theme())
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> super::FieldControl for Listbox<T, V> {
fn in_field(mut self, field: &super::InField) -> Element {
if self.label.is_none() && !field.label.is_empty() {
self.label = Some(field.label.clone());
}
self.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.disabled |= field.disabled;
if self.description.is_none() {
self.description = field.description.clone();
}
self.into()
}
fn mount_in_field(mut self, field: &super::InField, ctx: &mut Ctx) -> Element {
if self.label.is_none() && !field.label.is_empty() {
self.label = Some(field.label.clone());
}
self.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.disabled |= field.disabled;
if self.description.is_none() {
self.description = field.description.clone();
}
self.mount(ctx)
}
}
pub struct ListboxView {
pub options: Vec<ListboxOption>,
pub multiple: bool,
pub follow_focus: bool,
pub disabled: bool,
pub label: Option<Arc<str>>,
pub description: Option<Arc<str>>,
pub recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl ListboxView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn root(&self, content: Column) -> Column {
let scroll = ScrollVertical::new(content)
.width(Dimension::Pct(100.0))
.flex_full(0.0, 1.0, None);
self.frame().child(scroll)
}
pub fn frame(&self) -> Column {
let mut root = Column::new()
.align_items(Alignment::Stretch)
.describe("a11y_role", "listbox")
.part(&self.part(ListboxPart::Root));
if let Some(label) = &self.label {
root = root.describe("a11y_name", label.clone());
}
if let Some(description) = &self.description {
root = root.describe("a11y_description", description.clone());
}
if self.multiple {
root = root.describe("a11y_multiselectable", "true");
}
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());
}
root
}
pub fn content(&self) -> Column {
Column::new()
.align_items(Alignment::Stretch)
.width(Dimension::Pct(100.0))
.focus_group(
FocusGroup::vertical()
.one_stop(true)
.typeahead(true)
.wrap(false)
.pages(true)
.activate(self.follow_focus)
.shift_extends(self.multiple),
)
.part(&self.part(ListboxPart::Content))
}
pub fn render(mut self) -> Element {
let mut content = self.content();
for option in std::mem::take(&mut self.options) {
if let Some(group) = option.group_label() {
content = content.child(group);
}
content = content.child(option.render());
}
self.root(content).into()
}
}
#[derive(Clone)]
pub struct ListboxOption {
pub label: Arc<str>,
pub group: Option<Arc<str>>,
pub detail: Option<Arc<str>>,
pub hint: Option<Arc<str>>,
pub leading: Option<Element>,
pub trailing: Option<Element>,
pub chosen: bool,
pub disabled: bool,
pub entry: bool,
pub position: (usize, usize),
pub multiple: bool,
pub checkbox: Option<ResolvedRecipe>,
pub recipe: ResolvedRecipe,
forced: Option<Interaction>,
pick: Option<Arc<dyn Fn(Pick) + Send + Sync>>,
select_all: Option<Arc<dyn Fn() + Send + Sync>>,
row: Option<usize>,
id: Option<Arc<str>>,
}
impl ListboxOption {
fn again(mut self) -> Self {
self.recipe = self.recipe.item(self.id.as_ref(), ListboxPart::Option);
self.checkbox = self.checkbox.map(|checkbox| checkbox.owned_like(&self.recipe));
self
}
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self
.recipe
.part(part)
.forced(if self.disabled { None } else { self.forced })
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn group_label(&self) -> Option<Row> {
let label = self.group.as_ref().filter(|label| !label.is_empty())?;
let part = self.part(ListboxPart::Group);
Some(
Row::new()
.align_items(Alignment::Center)
.describe("a11y_role", "group")
.describe("a11y_name", label.clone())
.part(&part)
.child(part.text(label).nowrap()),
)
}
pub fn button(&self) -> components::Button {
let mut option = pressable(&self.part(ListboxPart::Option), self.disabled)
.justify(Justify::Start)
.align_items(Alignment::Center)
.describe("a11y_role", "option")
.describe("a11y_name", self.label.clone())
.describe("a11y_selected", if self.chosen { "true" } else { "false" })
.describe("a11y_posinset", self.position.0.to_string())
.describe("a11y_setsize", self.position.1.to_string())
.focus_label(self.label.clone())
.focus_entry(self.entry);
if let Some(row) = self.row {
option = option.focus_row(row);
}
if self.disabled {
option = option.describe("a11y_disabled", "true");
}
if let Some(detail) = &self.detail {
option = option.describe("a11y_description", detail.clone());
}
if self.checkbox.is_some() {
option = option.describe("a11y_checked", if self.chosen { "true" } else { "false" });
}
if let Some(pick) = self.pick.clone() {
let (multiple, checks) = (self.multiple, self.checkbox.is_some());
option = option.on_click(move |event: MouseEvent| {
pick(if checks {
Pick::of_check(&event)
} else {
Pick::of(&event, multiple)
})
});
}
if let Some(select_all) = self.select_all.clone() {
option = option.on_select_all(select_all_handler(select_all));
}
if let Some(id) = &self.id {
option = option.id(id.clone());
}
option
}
pub fn text(&self) -> Column {
let fill = Dimension::Pct(100.0);
let label = self.part(ListboxPart::Label);
let mut text = Column::new().flex(1.0).min_width(Dimension::Px(0.0)).child(
Column::new()
.width(fill)
.min_width(Dimension::Px(0.0))
.part(&label)
.child(label.text(&self.label).nowrap().text_overflow(TextOverflow::Elipsis)),
);
if let Some(detail) = &self.detail {
let part = self.part(ListboxPart::Detail);
text = text.child(
Column::new()
.width(fill)
.min_width(Dimension::Px(0.0))
.part(&part)
.child(part.text(detail).nowrap().text_overflow(TextOverflow::Elipsis)),
);
}
text
}
pub fn check(&self) -> Option<Element> {
(self.chosen && self.checkbox.is_none())
.then(|| glyph(&self.part(ListboxPart::Check), Name::new(icons::CHECK), false))
}
pub fn checkbox(&self) -> Option<Element> {
let checkbox = self.checkbox.as_ref()?;
let mut square = Row::new()
.justify(Justify::Center)
.align_items(Alignment::Center)
.flex_shrink(0.0)
.pointer_events_none()
.part(&checkbox.part(super::CheckboxPart::Box));
if self.chosen {
square = square.child(glyph(
&checkbox.part(super::CheckboxPart::Indicator),
Name::new(icons::CHECK),
false,
));
}
Some(square.into())
}
pub fn render(mut self) -> Element {
let mut option = self.button();
if let Some(checkbox) = self.checkbox() {
option = option.child(checkbox);
}
if let Some(leading) = self.leading.take() {
option = option.child(
Row::new()
.align_items(Alignment::Center)
.part(&self.part(ListboxPart::Leading))
.child(leading),
);
}
option = option.child(self.text());
if let Some(hint) = &self.hint {
let part = self.part(ListboxPart::Hint);
option = option.child(Row::new().part(&part).child(part.text(hint).nowrap()));
}
if let Some(trailing) = self.trailing.take() {
option = option.child(
Row::new()
.align_items(Alignment::Center)
.part(&self.part(ListboxPart::Trailing))
.child(trailing),
);
}
if let Some(check) = self.check() {
option = option.child(check);
}
option.into()
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> crate::ui::Styled for Listbox<T, V> {
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, V: ?Sized + 'static> Themed for Listbox<T, V> {
const NAME: &'static str = "listbox";
type Renderer = ListboxRenderer;
fn parts() -> crate::ui::Declared {
ListboxPart::declared()
}
fn states() -> crate::ui::Declared {
ListboxState::declared()
}
fn recipe() -> Recipe {
use ListboxPart::{Check, Content, Detail, Group, Hint, Label, Leading, Option, Root, Trailing};
use ListboxState::{Chosen, Disabled, FullWidth, Invalid, OptionDisabled};
let detail = ListboxState::Detail;
use PaletteColor::{Background, Destructive, Foreground, Highlight, Muted, MutedForeground, Ring, StatePressed};
let edge = |color: PaletteColor| Border::inside(BorderSize::Sm, color);
Recipe::new()
.base(Root, |s| {
s.width(220.0)
.background(Background)
.border(edge(PaletteColor::Border))
.radius(RadiusSize::Lg)
.foreground(Foreground)
})
.state(FullWidth, Root, |s| s.width(Length::Fill))
.state(Invalid, Root, |s| s.border(edge(Destructive)))
.state(Disabled, Root, |s| s.opacity(OpacityLevel::Disabled))
.base(Content, |s| s.padding_x(4.0).padding_y(4.0).gap(1.0))
.base(Option, |s| {
fading(
s.height(32.0)
.padding_x(8.0)
.gap(8.0)
.radius(RadiusSize::Sm)
.cursor(CursorIcon::Pointer),
)
})
.density(Density::Compact, Option, |s| s.height(24.0))
.density(Density::Comfortable, Option, |s| s.height(40.0))
.density(Density::Touch, Option, |s| s.height(44.0))
.state(detail, Option, |s| s.height(48.0))
.when(Selector::new().density(Density::Compact).state(detail), Option, |s| s.height(40.0))
.when(Selector::new().density(Density::Comfortable).state(detail), Option, |s| s.height(56.0))
.when(Selector::new().density(Density::Touch).state(detail), Option, |s| s.height(60.0))
.hovered(Option, |s| s.background(Muted))
.pressed(Option, |s| s.veil(StatePressed))
.focus_visible(Option, |s| s.outline(Outline::new(BorderSize::Md, Ring).offset(-2.0)))
.state(Chosen, Option, |s| s.background(Highlight))
.when(Selector::new().state(Chosen).hovered(), Option, |s| s.background(Highlight))
.state(OptionDisabled, Option, |s| s.cursor(CursorIcon::Default))
.when(Selector::new().state(OptionDisabled).hovered(), Option, |s| {
s.background(Color::new(0, 0, 0, 0))
})
.state(Disabled, Option, |s| s.cursor(CursorIcon::Default))
.base(Leading, |s| s.gap(4.0).foreground(MutedForeground))
.base(Label, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(Foreground)
})
.state(Chosen, Label, |s| s.weight(FontWeight::Medium))
.state(OptionDisabled, Label, |s| s.foreground(MutedForeground).opacity(0.6))
.when(Selector::new().state(Chosen).state(ListboxState::Checkboxes), Option, |s| {
s.background(Color::new(0, 0, 0, 0))
})
.when(
Selector::new().state(Chosen).state(ListboxState::Checkboxes).hovered(),
Option,
|s| s.background(Muted),
)
.when(Selector::new().state(Chosen).state(ListboxState::Checkboxes), Label, |s| {
s.weight(FontWeight::Normal)
})
.base(Detail, |s| s.typography(TypographyStyle::Caption).foreground(MutedForeground))
.base(Hint, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(Trailing, |s| s.gap(4.0).foreground(MutedForeground))
.base(Check, |s| s.square(IconSize::Sm).foreground(Foreground))
.base(Group, |s| {
s.padding_x(8.0)
.padding_top(6.0)
.padding_bottom(4.0)
.typography(TypographyStyle::Caption)
.font_size(11.0)
.weight(FontWeight::SemiBold)
.foreground(MutedForeground)
})
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> Listbox<T, V> {
pub fn mount(self, ctx: &mut Ctx) -> Element {
ctx.mount::<ListboxHost<T, V>>(ListboxHostProps { listbox: self })
}
}
struct ListboxHostProps<T, V: ?Sized> {
listbox: Listbox<T, V>,
}
impl<T, V: ?Sized> PartialEq for ListboxHostProps<T, V> {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl<T, V: ?Sized> crate::app::component::DevtoolsInspectable for ListboxHostProps<T, V> {
fn inspect(&self, formatter: &mut crate::app::component::DevtoolsFormatter<'_>) {
formatter.value("Listbox", format!("{} options", self.listbox.options.len()));
}
}
#[derive(Default)]
struct Shown {
options: Vec<ListboxOption>,
gap: SpacingValue,
}
struct HostRows {
data: Mutex<RowsData>,
reveal_key: Signal<Option<String>>,
reveal_request: Signal<u64>,
scroll: ScrollState,
}
#[derive(Default)]
struct RowsData {
labels: Vec<Arc<str>>,
enabled: Vec<bool>,
step: f32,
}
impl FocusRows for HostRows {
fn count(&self) -> usize {
self.data.lock().unwrap().labels.len()
}
fn label(&self, row: usize) -> Option<String> {
self.data.lock().unwrap().labels.get(row).map(|label| label.to_string())
}
fn enabled(&self, row: usize) -> bool {
self.data.lock().unwrap().enabled.get(row).copied().unwrap_or(false)
}
fn page(&self) -> usize {
let step = self.data.lock().unwrap().step.max(1.0);
((self.scroll.viewport_height() / step).floor() as usize).max(1)
}
fn reveal(&self, row: usize) {
if row >= self.count() {
return;
}
self.reveal_key.set(Some(row.to_string()));
self.reveal_request.update(|request| *request = request.wrapping_add(1));
}
}
struct ListboxHost<T, V: ?Sized> {
shown: Arc<Mutex<Shown>>,
rows: Arc<HostRows>,
generation: AtomicU64,
_values: PhantomData<fn(&V) -> T>,
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> Component for ListboxHost<T, V> {
type Props = ListboxHostProps<T, V>;
fn create(ctx: &mut Ctx) -> Self {
Self {
shown: Arc::default(),
rows: Arc::new(HostRows {
data: Mutex::default(),
reveal_key: ctx.signal(None),
reveal_request: ctx.signal(0),
scroll: ScrollState::new(),
}),
generation: AtomicU64::new(0),
_values: PhantomData,
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let theme = current_theme();
let mut view = ctx.props::<ListboxHostProps<T, V>>().listbox.view(&theme);
for (index, option) in view.options.iter_mut().enumerate() {
option.row = Some(index);
}
let (step, group) = option_steps(&view);
let plain = px_height(&view.part(ListboxPart::Option), &theme).unwrap_or(32.0);
*self.rows.data.lock().unwrap() = RowsData {
labels: view.options.iter().map(|option| option.label.clone()).collect(),
enabled: view.options.iter().map(|option| !option.disabled).collect(),
step,
};
let entry = view
.options
.iter()
.position(|option| option.entry)
.map(|index| index.to_string());
let generation = self.generation.fetch_add(1, Ordering::Relaxed) + 1;
let items: Arc<Vec<OptionItem>> = Arc::new(
view
.options
.iter()
.enumerate()
.map(|(index, option)| OptionItem {
index,
grouped: option.group.as_ref().is_some_and(|label| !label.is_empty()),
taller: px_height(&option.part(ListboxPart::Option), &theme).map_or(0.0, |height| (height - plain).max(0.0)),
generation,
})
.collect(),
);
*self.shown.lock().unwrap() = Shown {
options: std::mem::take(&mut view.options),
gap: view.part(ListboxPart::Content).rest().gap.unwrap_or_default(),
};
let shown = self.shown.clone();
let list = VirtualizedList::new_shared(ctx, items)
.with_scroll_state(self.rows.scroll.clone())
.reveal_key(self.rows.reveal_key.get().or(entry))
.reveal_request(self.rows.reveal_request.get())
.estimate_height(move |item: &OptionItem| step + item.taller + if item.grouped { group } else { 0.0 })
.width(Dimension::Pct(100.0))
.flex(1.0)
.mount_keyed::<ListboxOptionHost, _, _, _>(
|item: &OptionItem| item.index.to_string(),
move |item: &OptionItem| ListboxOptionProps {
index: item.index,
generation: item.generation,
shown: shown.clone(),
},
);
let rows: Arc<dyn FocusRows> = self.rows.clone();
let content = view
.content()
.flex(1.0)
.min_height(Dimension::Px(0.0))
.focus_rows(rows)
.child(list);
view.frame().child(content)
}
}
fn option_steps(view: &ListboxView) -> (f32, f32) {
let theme = view.theme();
let spacing = theme.spacing();
let px = |value: Option<&SpacingValue>| value.map(|value| value.resolve(&spacing, 0.0)).unwrap_or(0.0);
let option = px_height(&view.part(ListboxPart::Option), theme).unwrap_or(32.0);
let content = view.part(ListboxPart::Content).rest();
let group = view.part(ListboxPart::Group).rest();
let line = group.text.size.unwrap_or(11.0) * 1.5;
(
option + px(content.gap.as_ref()),
px(group.padding_top.as_ref()) + px(group.padding_bottom.as_ref()) + line,
)
}
fn px_height(part: &ResolvedPart, theme: &Theme) -> Option<f32> {
match part.rest().height?.resolve(theme)? {
Dimension::Px(px) => Some(px),
_ => None,
}
}
#[derive(Clone, PartialEq)]
struct OptionItem {
index: usize,
grouped: bool,
taller: f32,
generation: u64,
}
struct ListboxOptionProps {
index: usize,
generation: u64,
shown: Arc<Mutex<Shown>>,
}
impl PartialEq for ListboxOptionProps {
fn eq(&self, other: &Self) -> bool {
self.index == other.index && self.generation == other.generation && Arc::ptr_eq(&self.shown, &other.shown)
}
}
impl crate::app::component::DevtoolsInspectable for ListboxOptionProps {
fn inspect(&self, formatter: &mut crate::app::component::DevtoolsFormatter<'_>) {
formatter.value("ListboxOption", format!("option {}", self.index));
}
}
struct ListboxOptionHost;
impl Component for ListboxOptionHost {
type Props = ListboxOptionProps;
fn create(_: &mut Ctx) -> Self {
Self
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let props = ctx.props::<ListboxOptionProps>();
let (option, gap) = {
let shown = props.shown.lock().unwrap();
(shown.options.get(props.index).cloned(), shown.gap.clone())
};
let Some(option) = option.map(ListboxOption::again) else {
return Column::new();
};
let mut column = Column::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Stretch);
if let Some(group) = option.group_label() {
column = column.child(group);
}
column.child(
Column::new()
.align_items(Alignment::Stretch)
.spacing(gap)
.child(option.render())
.child(Row::new()),
)
}
}