floem 0.2.0

A native Rust UI library with fine-grained reactivity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
#![deny(missing_docs)]
//! A view that allows the user to select an item from a list of items.
//!
//! The [Dropdown] struct provides several constructors, each offering different levels of customization and ease of use
//!
//! The [DropdownCustomStyle] struct allows for easy and advanced customization of the dropdown's appearance
use std::{any::Any, rc::Rc};

use floem_reactive::{
    as_child_of_current_scope, create_effect, create_updater, Scope, SignalGet, SignalUpdate,
};
use floem_winit::keyboard::{Key, NamedKey};
use peniko::{
    kurbo::{Point, Rect},
    Color,
};

use crate::{
    action::{add_overlay, remove_overlay},
    event::{Event, EventListener, EventPropagation},
    id::ViewId,
    prop, prop_extractor,
    style::{CustomStylable, Style, StyleClass, Width},
    style_class,
    unit::PxPctAuto,
    view::{default_compute_layout, IntoView, View},
    views::{container, scroll, stack, svg, text, Decorators},
    AnyView,
};

use super::list;

type ChildFn<T> = dyn Fn(T) -> (AnyView, Scope);
type ListViewFn<T> = Rc<dyn Fn(&dyn Fn(T) -> AnyView) -> AnyView>;

style_class!(
    /// A Style class that is applied to all dropdowns.
    pub DropdownClass
);

prop!(
    /// A property that determines whether the dropdown should close automatically when an item is selected.
    pub CloseOnAccept: bool {} = true
);
prop_extractor!(DropdownStyle {
    close_on_accept: CloseOnAccept,
});

/// # A customizable dropdown view for selecting an item from a list.
///
/// The `Dropdown` struct provides several constructors, each offering different levels of
/// customization and ease of use:
///
/// - [`Dropdown::new_rw`]: The simplest constructor, ideal for quick setup with minimal customization.
///   It uses default views and assumes direct access to a signal that can be both read from and written to for driving the selection of an item.
///
/// - [`Dropdown::new`]: Similar to `new_rw`, but uses a read-only function for the active item, and requires that you manually provide an `on_accept` callback.
///
/// - [`Dropdown::new`]: Offers full customization, letting you define custom view functions for
///   both the main display and list items. Uses a read-only function for the active item and requires that you manually provide an `on_accept` callback.
///
/// - The dropdown also has methods [`Dropdown::main_view`] and [`Dropdown::list_item_view`] that let you override the main view function and list item view function respectively.
///
/// Choose the constructor that best fits your needs based on the level of customization required.
///
/// **Styling**:
/// You can modify the behavior of the dropdown through the `CloseOnAccept` property.
/// If the property is set to `true` the dropdown will automatically close when an item is selected.
/// If the property is set to `false` the dropwown will not automatically close when an item is selected.
/// The default is `true`.
/// Styling Example:
/// ```rust
/// # use floem::views::dropdown;
/// # use floem::views::empty;
/// # use floem::views::Decorators;
/// // root view
/// empty().style(|s| {
///     s.class(dropdown::DropdownClass, |s| {
///         s.set(dropdown::CloseOnAccept, false)
///     })
/// });
/// ```
pub struct Dropdown<T: 'static> {
    id: ViewId,
    current_value: T,
    main_view: ViewId,
    main_view_scope: Scope,
    main_fn: Box<ChildFn<T>>,
    list_view: ListViewFn<T>,
    list_item_fn: Rc<dyn Fn(T) -> AnyView>,
    list_style: Style,
    overlay_id: Option<ViewId>,
    window_origin: Option<Point>,
    on_accept: Option<Box<dyn Fn(T)>>,
    on_open: Option<Box<dyn Fn(bool)>>,
    style: DropdownStyle,
}

enum Message {
    OpenState(bool),
    ActiveElement(Box<dyn Any>),
    ListFocusLost,
    ListSelect(Box<dyn Any>),
}

impl<T: 'static + Clone> View for Dropdown<T> {
    fn id(&self) -> ViewId {
        self.id
    }

    fn debug_name(&self) -> std::borrow::Cow<'static, str> {
        "DropDown".into()
    }

    fn style_pass(&mut self, cx: &mut crate::context::StyleCx<'_>) {
        if self.style.read(cx) {
            cx.app_state_mut().request_paint(self.id);
        }
        self.list_style = cx
            .indirect_style()
            .clone()
            .apply_classes_from_context(&[scroll::ScrollClass::class_ref()], cx.indirect_style());

        for child in self.id.children() {
            cx.style_view(child);
        }
    }

    fn compute_layout(&mut self, cx: &mut crate::context::ComputeLayoutCx) -> Option<Rect> {
        self.window_origin = Some(cx.window_origin);

        default_compute_layout(self.id, cx)
    }

    fn update(&mut self, cx: &mut crate::context::UpdateCx, state: Box<dyn std::any::Any>) {
        if let Ok(state) = state.downcast::<Message>() {
            match *state {
                Message::OpenState(true) => self.open_dropdown(cx),
                Message::OpenState(false) => self.close_dropdown(),
                Message::ListFocusLost => self.close_dropdown(),
                Message::ListSelect(val) => {
                    if let Ok(val) = val.downcast::<T>() {
                        if self.style.close_on_accept() {
                            self.close_dropdown();
                        }
                        if let Some(on_select) = &self.on_accept {
                            on_select(*val);
                        }
                    }
                }
                Message::ActiveElement(val) => {
                    if let Ok(val) = val.downcast::<T>() {
                        let old_child_scope = self.main_view_scope;
                        let old_main_view = self.main_view;
                        let (main_view, main_view_scope) = (self.main_fn)(*val);
                        let main_view_id = main_view.id();
                        self.id.set_children(vec![main_view]);
                        self.main_view = main_view_id;
                        self.main_view_scope = main_view_scope;

                        cx.app_state_mut().remove_view(old_main_view);
                        old_child_scope.dispose();
                        self.id.request_all();
                    }
                }
            }
        }
    }

    fn event_before_children(
        &mut self,
        _cx: &mut crate::context::EventCx,
        event: &Event,
    ) -> EventPropagation {
        match event {
            Event::PointerDown(_) => {
                self.swap_state();
                return EventPropagation::Stop;
            }
            Event::KeyUp(ref key_event)
                if matches!(
                    key_event.key.logical_key,
                    Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
                ) =>
            {
                self.swap_state()
            }
            _ => {}
        }

        EventPropagation::Continue
    }
}

impl<T: Clone> Dropdown<T> {
    /// Creates a default main view for the dropdown.
    ///
    /// This function generates a view that displays the given item as text,
    /// along with a chevron-down icon to indicate that it's a dropdown.
    pub fn default_main_view(item: T) -> AnyView
    where
        T: std::fmt::Display,
    {
        const CHEVRON_DOWN: &str = r##"
            <svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" viewBox="0 0 185.344 185.344">
                <path fill="#010002" d="M92.672 144.373a10.707 10.707 0 0 1-7.593-3.138L3.145 59.301c-4.194-4.199
                -4.194-10.992 0-15.18a10.72 10.72 0 0 1 15.18 0l74.347 74.341 74.347-74.341a10.72 10.72 0 0 1
                15.18 0c4.194 4.194 4.194 10.981 0 15.18l-81.939 81.934a10.694 10.694 0 0 1-7.588 3.138z"/>
            </svg>
        "##;

        // TODO: this should be more customizable
        stack((
            text(item),
            container(svg(CHEVRON_DOWN).style(|s| s.size(12, 12).color(Color::BLACK))).style(|s| {
                s.items_center()
                    .padding(3.)
                    .border_radius(5)
                    .hover(move |s| s.background(Color::LIGHT_GRAY))
            }),
        ))
        .style(|s| s.items_center().justify_between().size_full())
        .into_any()
    }

    /// Creates a new customizable dropdown.
    ///
    /// You might want to use some of the simpler constructors like [Dropdown::new] or [Dropdown::new_rw].
    ///
    /// # Example
    /// ```rust
    /// # use floem::{*, views::*, reactive::*};
    /// # use floem::views::dropdown::*;
    /// let active_item = RwSignal::new(3);
    ///
    /// Dropdown::custom(
    ///     move || active_item.get(),
    ///     |main_item| text(main_item).into_any(),
    ///     1..=5,
    ///     |list_item| text(list_item).into_any(),
    /// )
    /// .on_accept(move |item| active_item.set(item));
    /// ```
    ///
    /// This function provides full control over the dropdown's appearance and behavior
    /// by allowing custom view functions for both the main display and list items.
    ///
    /// # Arguments
    ///
    /// * `active_item` - A function that returns the currently selected item.
    ///
    /// * `main_view` - A function that takes a value of type `T` and returns an `AnyView`
    ///                 to be used as the main dropdown display.
    ///
    /// * `iterator` - An iterator that provides the items to be displayed in the dropdown list.
    ///
    /// * `list_item_fn` - A function that takes a value of type `T` and returns an `AnyView`
    ///                    to be used for each item in the dropdown list.
    pub fn custom<MF, I, LF, AIF>(
        active_item: AIF,
        main_view: MF,
        iterator: I,
        list_item_fn: LF,
    ) -> Dropdown<T>
    where
        MF: Fn(T) -> AnyView + 'static,
        I: IntoIterator<Item = T> + Clone + 'static,
        LF: Fn(T) -> AnyView + Clone + 'static,
        T: Clone + 'static,
        AIF: Fn() -> T + 'static,
    {
        let dropdown_id = ViewId::new();

        let list_item_fn = Rc::new(list_item_fn);

        let list_view = Rc::new(move |list_item_fn: &dyn Fn(T) -> AnyView| {
            let iterator = iterator.clone();
            let iter_clone = iterator.clone();
            let inner_list = list(iterator.into_iter().map(list_item_fn))
                .on_accept(move |opt_idx| {
                    if let Some(idx) = opt_idx {
                        let val = iter_clone.clone().into_iter().nth(idx).unwrap();
                        dropdown_id.update_state(Message::ActiveElement(Box::new(val.clone())));
                        dropdown_id.update_state(Message::ListSelect(Box::new(val)));
                    }
                })
                .style(|s| s.size_full())
                .keyboard_navigable()
                .on_event_stop(EventListener::PointerDown, move |_| {})
                .on_event_stop(EventListener::FocusLost, move |_| {
                    dropdown_id.update_state(Message::ListFocusLost);
                });
            let inner_list_id = inner_list.id();
            scroll(inner_list)
                .on_event_stop(EventListener::FocusGained, move |_| {
                    inner_list_id.request_focus();
                })
                .into_any()
        });

        let initial = create_updater(active_item, move |new_state| {
            dropdown_id.update_state(Message::ActiveElement(Box::new(new_state)));
        });

        let main_fn = Box::new(as_child_of_current_scope(main_view));

        let (child, main_view_scope) = main_fn(initial.clone());
        let main_view = child.id();

        dropdown_id.set_children(vec![child]);

        Self {
            id: dropdown_id,
            current_value: initial,
            main_view,
            main_view_scope,
            main_fn,
            list_view,
            list_item_fn,
            list_style: Style::new(),
            overlay_id: None,
            window_origin: None,
            on_accept: None,
            on_open: None,
            style: Default::default(),
        }
        .class(DropdownClass)
    }

    /// Creates a new dropdown with a read-only function for the active item.
    ///
    /// # Example
    /// ```rust
    /// # use floem::{*, views::*, reactive::*};
    /// # use floem::views::dropdown::*;
    /// let active_item = RwSignal::new(3);
    ///
    /// Dropdown::new(move || active_item.get(), 1..=5).on_accept(move |val| active_item.set(val));
    /// ```
    ///
    /// This function is a convenience wrapper around `Dropdown::new` that uses default views
    /// for the main and list items.
    ///
    /// See also [Dropdown::new_rw].
    ///
    /// # Arguments
    ///
    /// * `active_item` - A function that returns the currently selected item.
    ///
    /// * `iterator` - An iterator that provides the items to be displayed in the dropdown list.
    pub fn new<AIF, I>(active_item: AIF, iterator: I) -> Dropdown<T>
    where
        AIF: Fn() -> T + 'static,
        I: IntoIterator<Item = T> + Clone + 'static,
        T: Clone + std::fmt::Display + 'static,
    {
        Self::custom(active_item, Self::default_main_view, iterator, |v| {
            crate::views::text(v).into_any()
        })
    }

    /// Creates a new dropdown with a read-write signal for the active item.
    ///
    /// # Example:
    /// ```rust
    /// # use floem::{*, views::*, reactive::*};
    /// # use floem::{views::dropdown::*};
    /// let dropdown_active_item = RwSignal::new(3);
    ///
    /// Dropdown::new_rw(dropdown_active_item, 1..=5);
    /// ```
    ///
    /// This function is a convenience wrapper around `Dropdown::custom` that uses default views
    /// for the main and list items.
    ///
    /// # Arguments
    ///
    /// * `active_item` - A read-write signal representing the currently selected item.
    ///                   It must implement `SignalGet<T>` and `SignalUpdate<T>`.
    ///
    /// * `iterator` - An iterator that provides the items to be displayed in the dropdown list.
    pub fn new_rw<AI, I>(active_item: AI, iterator: I) -> Dropdown<T>
    where
        AI: SignalGet<T> + SignalUpdate<T> + Copy + 'static,
        I: IntoIterator<Item = T> + Clone + 'static,
        T: Clone + std::fmt::Display + 'static,
    {
        Self::custom(
            move || active_item.get(),
            Self::default_main_view,
            iterator,
            |t| text(t).into_any(),
        )
        .on_accept(move |nv| active_item.set(nv))
    }

    /// Override the main view for the dropdown
    pub fn main_view(mut self, main_view: impl Fn(T) -> Box<dyn View> + 'static) -> Self {
        self.main_fn = Box::new(as_child_of_current_scope(main_view));
        let (child, main_view_scope) = (self.main_fn)(self.current_value.clone());
        let main_view = child.id();
        self.main_view_scope = main_view_scope;
        self.main_view = main_view;
        self.id.set_children(vec![child]);
        self
    }

    /// Override the list view for each item in the dropdown list
    pub fn list_item_view(mut self, list_item_fn: impl Fn(T) -> Box<dyn View> + 'static) -> Self {
        self.list_item_fn = Rc::new(list_item_fn);
        self
    }

    /// Sets a reactive condition for showing or hiding the dropdown list.
    ///
    /// # Reactivity
    /// The `show` function will be re-run whenever any signal it depends on changes.
    pub fn show_list(self, show: impl Fn() -> bool + 'static) -> Self {
        let id = self.id();
        create_effect(move |_| {
            let state = show();
            id.update_state(Message::OpenState(state));
        });
        self
    }

    /// Sets a callback function to be called when an item is selected from the dropdown.
    ///
    /// Only one `on_accept` callback can be set at a time.
    pub fn on_accept(mut self, on_accept: impl Fn(T) + 'static) -> Self {
        self.on_accept = Some(Box::new(on_accept));
        self
    }

    /// Sets a callback function to be called when the dropdown is opened.
    ///
    /// Only one `on_open` callback can be set at a time.
    pub fn on_open(mut self, on_open: impl Fn(bool) + 'static) -> Self {
        self.on_open = Some(Box::new(on_open));
        self
    }

    fn swap_state(&self) {
        if self.overlay_id.is_some() {
            self.id.update_state(Message::OpenState(false));
        } else {
            self.id.request_layout();
            self.id.update_state(Message::OpenState(true));
        }
    }

    fn open_dropdown(&mut self, cx: &mut crate::context::UpdateCx) {
        if self.overlay_id.is_none() {
            self.id.request_layout();
            cx.app_state.compute_layout();
            if let Some(layout) = self.id.get_layout() {
                self.update_list_style(layout.size.width as f64);
                let point =
                    self.window_origin.unwrap_or_default() + (0., layout.size.height as f64);
                self.create_overlay(point);

                if let Some(on_open) = &self.on_open {
                    on_open(true);
                }
            }
        }
    }

    fn close_dropdown(&mut self) {
        if let Some(id) = self.overlay_id.take() {
            remove_overlay(id);
            if let Some(on_open) = &self.on_open {
                on_open(false);
            }
        }
    }

    fn update_list_style(&mut self, width: f64) {
        if let PxPctAuto::Pct(pct) = self.list_style.get(Width) {
            let new_width = width * pct / 100.0;
            self.list_style = self.list_style.clone().width(new_width);
        }
    }

    fn create_overlay(&mut self, point: Point) {
        let list = self.list_view.clone();
        let list_style = self.list_style.clone();
        let list_item_fn = self.list_item_fn.clone();
        self.overlay_id = Some(add_overlay(point, move |_| {
            let list = list(&*list_item_fn.clone())
                .style(move |s| s.apply(list_style.clone()))
                .into_view();
            let list_id = list.id();
            list_id.request_focus();
            list
        }));
    }

    /// Sets the custom style properties of the `Dropdown`.
    pub fn dropdown_style(
        self,
        style: impl Fn(DropdownCustomStyle) -> DropdownCustomStyle + 'static,
    ) -> Self {
        self.custom_style(style)
    }
}

#[derive(Debug, Clone, Default)]
/// A struct that allows for easy custom styling of the `Dropdown` using the [Dropdown::dropdown_style] method or the [Style::custom_style](crate::style::CustomStylable::custom_style) method.
pub struct DropdownCustomStyle(Style);
impl From<DropdownCustomStyle> for Style {
    fn from(val: DropdownCustomStyle) -> Self {
        val.0
    }
}
impl<T: Clone> CustomStylable<DropdownCustomStyle> for Dropdown<T> {
    type DV = Self;
}

impl DropdownCustomStyle {
    /// Creates a new `DropDownCustomStyle` with default values.
    pub fn new() -> Self {
        Self::default()
    }
    /// Sets the `CloseOnAccept` property for the dropdown, which determines whether the dropdown
    /// should automatically close when an item is selected. The default value is `true`.
    ///
    /// # Arguments
    /// * `close`: If set to `true`, the dropdown will close upon item selection. If `false`, it
    ///   will remain open after an item is selected.
    pub fn close_on_accept(mut self, close: bool) -> Self {
        self = Self(self.0.set(CloseOnAccept, close));
        self
    }
}

impl<T> Drop for Dropdown<T> {
    fn drop(&mut self) {
        if let Some(id) = self.overlay_id {
            remove_overlay(id)
        }
    }
}