Skip to main content

ferroui_designer/
component_browser.rs

1//! Native component/resource browser. Catalog data and callbacks are host-owned;
2//! browsing, filtering and selection never author a document.
3use ferroui_base::input::{InputElement, Key, PointerPressedEventArgs};
4use ferroui_base::interactivity::RoutingStrategies;
5use ferroui_base::layout::{HorizontalAlignment, VerticalAlignment};
6use ferroui_base::media::{FontWeight, SolidColorBrush, TextTrimming};
7use ferroui_base::{CornerRadius, Point, Ref, Thickness};
8use ferroui_controls::automation::AutomationProperties;
9use ferroui_controls::templates::FuncDataTemplate;
10use ferroui_controls::{
11    Border, Button, ColumnDefinitions, ComboBox, Control, Grid, ListBox, RowDefinitions,
12    StackPanel, TextBlock, TextBox, ToolTip,
13};
14use ferroui_designer_core::NodeId;
15use std::cell::{Cell, RefCell};
16use std::rc::Rc;
17
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum ComponentLibraryFilter {
20    #[default]
21    All,
22    Components,
23    Templates,
24    Themes,
25    Resources,
26    Dictionaries,
27}
28impl ComponentLibraryFilter {
29    fn title(self) -> &'static str {
30        match self {
31            Self::All => "All definitions",
32            Self::Components => "Components",
33            Self::Templates => "Templates",
34            Self::Themes => "Control themes and styles",
35            Self::Resources => "Resources",
36            Self::Dictionaries => "Resource dictionaries",
37        }
38    }
39}
40const FILTERS: [ComponentLibraryFilter; 6] = [
41    ComponentLibraryFilter::All,
42    ComponentLibraryFilter::Components,
43    ComponentLibraryFilter::Templates,
44    ComponentLibraryFilter::Themes,
45    ComponentLibraryFilter::Resources,
46    ComponentLibraryFilter::Dictionaries,
47];
48
49/// A definition in the current document or an application-registered asset.
50/// IDs are host identities, independent of display names and resource aliases.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct ComponentLibraryItem {
53    pub id: String,
54    pub title: String,
55    pub kind: String,
56    pub detail: String,
57    pub filter: ComponentLibraryFilter,
58    pub node: Option<NodeId>,
59    pub asset_id: Option<String>,
60    pub swatch: Option<String>,
61    pub usages: usize,
62}
63
64type SelectItem = Rc<dyn Fn(&ComponentLibraryItem)>;
65type DragItem = Rc<dyn Fn(&ComponentLibraryItem, &PointerPressedEventArgs)>;
66
67pub struct ComponentLibrary {
68    root: Ref<Grid>,
69    search: Ref<TextBox>,
70    filter: Ref<ComboBox>,
71    list: Ref<ListBox>,
72    count: Ref<TextBlock>,
73    empty: Ref<TextBlock>,
74    items: RefCell<Vec<ComponentLibraryItem>>,
75    visible: RefCell<Vec<ComponentLibraryItem>>,
76    selected: RefCell<Option<String>>,
77    select: RefCell<Option<SelectItem>>,
78    activate: RefCell<Option<SelectItem>>,
79    drag: RefCell<Option<DragItem>>,
80    create: RefCell<Option<Rc<dyn Fn()>>>,
81    press: RefCell<Option<(ComponentLibraryItem, PointerPressedEventArgs, Point)>>,
82    guard: Cell<bool>,
83}
84
85impl ComponentLibrary {
86    pub fn new() -> Rc<Self> {
87        let root = Grid::new();
88        root.set_row_definitions(RowDefinitions::parse("Auto,Auto,*,Auto").unwrap());
89        root.set_margin(Thickness::new(8.0, 8.0, 8.0, 8.0));
90        let header = Grid::new();
91        header.set_column_definitions(ColumnDefinitions::parse("*,28").unwrap());
92        header.set_margin(Thickness::new(4.0, 0.0, 4.0, 7.0));
93        let search = TextBox::new();
94        search.set_name(Some("ComponentLibrarySearch".into()));
95        search.set_placeholder_text(Some("Search definitions and resources"));
96        search.set_margin(Thickness::new(0.0, 0.0, 4.0, 0.0));
97        AutomationProperties::set_name(&search, Some("Search component library"));
98        header.children().add(search.clone().upcast::<Control>());
99        let create = Button::new();
100        create.set_name(Some("NewComponentResource".into()));
101        create.classes().add("icon");
102        create.set_content(Some(Control::boxed(crate::icons::vector_icon(
103            crate::icons::ADD,
104            14.0,
105        ))));
106        create.set_height(26.0);
107        ToolTip::set_tip(
108            &create,
109            Some(Rc::new("Create a resource, theme or template".to_owned())),
110        );
111        AutomationProperties::set_name(&create, Some("Create resource or definition"));
112        Grid::set_column(&create, 1);
113        header.children().add(create.clone().upcast::<Control>());
114        root.children().add(header.upcast::<Control>());
115        let filter = ComboBox::new();
116        filter.set_name(Some("ComponentLibraryFilter".into()));
117        filter.set_horizontal_alignment(HorizontalAlignment::Stretch);
118        filter.set_margin(Thickness::new(4.0, 0.0, 4.0, 8.0));
119        AutomationProperties::set_name(&filter, Some("Definition category"));
120        for choice in FILTERS {
121            filter.items().add(Some(Rc::new(choice.title().to_owned())));
122        }
123        filter.set_selected_index(0);
124        Grid::set_row(&filter, 1);
125        root.children().add(filter.clone().upcast::<Control>());
126        let list = ListBox::new();
127        list.set_name(Some("ComponentLibraryList".into()));
128        list.classes().add("designer-library-list");
129        list.set_background(Some(SolidColorBrush::from_uint32(0x0025262b).into()));
130        list.set_border_thickness(Thickness::uniform(0.0));
131        list.set_padding(Thickness::uniform(0.0));
132        Grid::set_row(&list, 2);
133        root.children().add(list.clone().upcast::<Control>());
134        let empty = TextBlock::new();
135        empty.set_text(Some(
136            "No matching definitions.\nCreate a resource or register a custom control asset.",
137        ));
138        empty.set_text_wrapping(ferroui_base::media::TextWrapping::Wrap);
139        empty.set_foreground(Some(SolidColorBrush::from_uint32(0xff979caa).into()));
140        empty.set_font_size(11.0);
141        empty.set_margin(Thickness::uniform(12.0));
142        empty.set_is_hit_test_visible(false);
143        empty.set_vertical_alignment(VerticalAlignment::Top);
144        Grid::set_row(&empty, 2);
145        root.children().add(empty.clone().upcast::<Control>());
146        let footer = StackPanel::new();
147        footer.set_spacing(4.0);
148        footer.set_margin(Thickness::new(4.0, 8.0, 4.0, 2.0));
149        let count = TextBlock::new();
150        count.set_font_size(11.0);
151        count.set_foreground(Some(SolidColorBrush::from_uint32(0xffa9adba).into()));
152        footer.children().add(count.clone().upcast::<Control>());
153        let hint = TextBlock::new();
154        hint.set_text(Some("Enter to edit · Drag resources to properties"));
155        hint.set_text_wrapping(ferroui_base::media::TextWrapping::Wrap);
156        hint.set_font_size(10.0);
157        hint.set_foreground(Some(SolidColorBrush::from_uint32(0xff979caa).into()));
158        footer.children().add(hint.upcast::<Control>());
159        Grid::set_row(&footer, 3);
160        root.children().add(footer.upcast::<Control>());
161        let this = Rc::new(Self {
162            root,
163            search,
164            filter,
165            list,
166            count,
167            empty,
168            items: RefCell::new(Vec::new()),
169            visible: RefCell::new(Vec::new()),
170            selected: RefCell::new(None),
171            select: RefCell::new(None),
172            activate: RefCell::new(None),
173            drag: RefCell::new(None),
174            create: RefCell::new(None),
175            press: RefCell::new(None),
176            guard: Cell::new(false),
177        });
178        let weak = Rc::downgrade(&this);
179        this.list
180            .set_item_template(Some(FuncDataTemplate::for_type::<ComponentLibraryItem>(
181                move |item, _| weak.upgrade().map(|this| this.item_control(item)),
182                false,
183            )));
184        let weak = Rc::downgrade(&this);
185        this.search.text_changing(move |_, _| {
186            if let Some(this) = weak.upgrade() {
187                this.refresh();
188            }
189        });
190        let weak = Rc::downgrade(&this);
191        this.filter.selection_changed(move |_, _| {
192            if let Some(this) = weak.upgrade() {
193                if !this.guard.get() {
194                    this.refresh();
195                }
196            }
197        });
198        let weak = Rc::downgrade(&this);
199        this.list.selection_changed(move |_, _| {
200            let Some(this) = weak.upgrade().filter(|this| !this.guard.get()) else {
201                return;
202            };
203            let item = this
204                .list
205                .selected_item()
206                .and_then(|item| item.downcast_ref::<ComponentLibraryItem>().cloned());
207            *this.selected.borrow_mut() = item.as_ref().map(|item| item.id.clone());
208            if let Some(item) = item {
209                let callback = this.select.borrow().clone();
210                if let Some(callback) = callback {
211                    callback(&item);
212                }
213            }
214        });
215        let weak = Rc::downgrade(&this);
216        this.list
217            .add_handler(InputElement::key_down_event(), move |_, event| {
218                let Some(this) = weak.upgrade() else {
219                    return;
220                };
221                if event.key == Key::Enter {
222                    if let Some(item) = this.selected_item() {
223                        let callback = this.activate.borrow().clone();
224                        if let Some(callback) = callback {
225                            callback(&item);
226                            event.set_handled(true);
227                        }
228                    }
229                }
230                if event.key == Key::Escape {
231                    this.cancel_pending_drag();
232                }
233            });
234        let weak = Rc::downgrade(&this);
235        create.click(move |_, _| {
236            if let Some(this) = weak.upgrade() {
237                let callback = this.create.borrow().clone();
238                if let Some(callback) = callback {
239                    callback();
240                }
241            }
242        });
243        this.refresh();
244        this
245    }
246
247    pub fn control(&self) -> Ref<Control> {
248        self.root.clone().upcast::<Control>()
249    }
250    pub fn list(&self) -> Ref<ListBox> {
251        self.list.clone()
252    }
253    pub fn on_select(&self, callback: impl Fn(&ComponentLibraryItem) + 'static) {
254        *self.select.borrow_mut() = Some(Rc::new(callback));
255    }
256    pub fn on_activate(&self, callback: impl Fn(&ComponentLibraryItem) + 'static) {
257        *self.activate.borrow_mut() = Some(Rc::new(callback));
258    }
259    pub fn on_begin_drag(
260        &self,
261        callback: impl Fn(&ComponentLibraryItem, &PointerPressedEventArgs) + 'static,
262    ) {
263        *self.drag.borrow_mut() = Some(Rc::new(callback));
264    }
265    pub fn on_create(&self, callback: impl Fn() + 'static) {
266        *self.create.borrow_mut() = Some(Rc::new(callback));
267    }
268    /// Retire an in-progress pointer gesture when the host changes document,
269    /// revision, scope or editing permissions without replacing the catalog.
270    pub fn cancel_pending_drag(&self) {
271        let press = self.press.borrow_mut().take();
272        if let Some((_, event, _)) = press {
273            if event
274                .pointer()
275                .captured()
276                .is_some_and(|captured| self.root.is_visual_ancestor_of(&captured))
277            {
278                event.pointer().capture(None);
279            }
280        }
281    }
282    pub fn set_query(&self, query: &str) {
283        self.search.set_text(Some(query));
284    }
285    pub fn set_filter(&self, filter: ComponentLibraryFilter) {
286        self.filter.set_selected_index(
287            FILTERS
288                .iter()
289                .position(|value| *value == filter)
290                .unwrap_or(0) as i32,
291        );
292    }
293    pub fn visible_items(&self) -> Vec<ComponentLibraryItem> {
294        self.visible.borrow().clone()
295    }
296    pub fn selected_item(&self) -> Option<ComponentLibraryItem> {
297        self.selected.borrow().as_ref().and_then(|id| {
298            self.items
299                .borrow()
300                .iter()
301                .find(|item| &item.id == id)
302                .cloned()
303        })
304    }
305    pub fn select(&self, id: &str) -> bool {
306        let Some(index) = self.visible.borrow().iter().position(|item| item.id == id) else {
307            return false;
308        };
309        self.list.set_selected_index(index as i32);
310        self.list.scroll_into_view(index as i32);
311        true
312    }
313    pub fn replace_items(&self, mut items: Vec<ComponentLibraryItem>) {
314        items.sort_by(|a, b| {
315            a.title
316                .to_lowercase()
317                .cmp(&b.title.to_lowercase())
318                .then(a.id.cmp(&b.id))
319        });
320        if *self.items.borrow() == items {
321            return;
322        }
323        self.cancel_pending_drag();
324        *self.items.borrow_mut() = items;
325        self.refresh();
326    }
327    fn refresh(&self) {
328        self.cancel_pending_drag();
329        let query = self.search.text().unwrap_or_default().to_lowercase();
330        let terms = query.split_whitespace().collect::<Vec<_>>();
331        let filter = FILTERS
332            .get(self.filter.selected_index().max(0) as usize)
333            .copied()
334            .unwrap_or_default();
335        let items = self
336            .items
337            .borrow()
338            .iter()
339            .filter(|item| {
340                (filter == ComponentLibraryFilter::All || item.filter == filter)
341                    && terms.iter().all(|term| {
342                        format!("{} {} {}", item.title, item.kind, item.detail)
343                            .to_lowercase()
344                            .contains(term)
345                    })
346            })
347            .cloned()
348            .collect::<Vec<_>>();
349        let selected = self.selected.borrow().clone();
350        self.guard.set(true);
351        self.list.items().clear();
352        for item in &items {
353            self.list.items().add(Some(Rc::new(item.clone())));
354        }
355        self.list.set_selected_index(
356            selected
357                .as_ref()
358                .and_then(|selected| items.iter().position(|item| &item.id == selected))
359                .map_or(-1, |index| index as i32),
360        );
361        self.guard.set(false);
362        self.empty.set_is_visible(items.is_empty());
363        self.count.set_text(Some(&format!(
364            "{} of {} definitions",
365            items.len(),
366            self.items.borrow().len()
367        )));
368        *self.visible.borrow_mut() = items;
369    }
370    fn item_control(self: &Rc<Self>, item: &ComponentLibraryItem) -> Ref<Control> {
371        let row = Grid::new();
372        row.set_column_definitions(ColumnDefinitions::parse("22,*,Auto").unwrap());
373        row.set_min_height(46.0);
374        row.set_margin(Thickness::new(7.0, 3.0, 7.0, 3.0));
375        let color = match item.filter {
376            ComponentLibraryFilter::Components | ComponentLibraryFilter::Templates => 0xffb6a2f6,
377            ComponentLibraryFilter::Themes => 0xff79a8ff,
378            _ => 0xff7fcbb4,
379        };
380        let icon: Ref<Control> = if let Some(swatch) = item
381            .swatch
382            .as_ref()
383            .and_then(|value| ferroui_base::media::Color::parse(value).ok())
384        {
385            let square = Border::new();
386            square.set_width(14.0);
387            square.set_height(14.0);
388            square.set_corner_radius(CornerRadius::uniform(3.0));
389            square.set_background(Some(SolidColorBrush::with_color(swatch).into()));
390            square.upcast::<Control>()
391        } else {
392            let icon = crate::icons::vector_icon(
393                match item.filter {
394                    ComponentLibraryFilter::Components => {
395                        "F1 M8,0 L16,8 8,16 0,8 Z M8,3 L3,8 8,13 13,8 Z"
396                    }
397                    ComponentLibraryFilter::Templates => {
398                        "F1 M1,1 L15,1 15,15 1,15 Z M3,3 L3,13 13,13 13,3 Z M5,5 L11,5 11,7 5,7 Z M5,9 L9,9 9,11 5,11 Z"
399                    }
400                    ComponentLibraryFilter::Themes => "F1 M8,0 L16,8 8,16 0,8 Z M8,3 L3,8 8,13 Z",
401                    ComponentLibraryFilter::Dictionaries => {
402                        "F1 M1,2 L7,2 9,4 15,4 15,15 1,15 Z M3,6 L3,13 13,13 13,6 Z"
403                    }
404                    _ => {
405                        "F1 M1,1 L15,1 15,15 1,15 Z M3,3 L3,13 13,13 13,3 Z M5,5 L11,5 11,11 5,11 Z"
406                    }
407                },
408                14.0,
409            );
410            icon.set_foreground(Some(SolidColorBrush::from_uint32(color).into()));
411            icon.upcast::<Control>()
412        };
413        icon.set_vertical_alignment(VerticalAlignment::Center);
414        row.children().add(icon);
415        let labels = StackPanel::new();
416        labels.set_spacing(2.0);
417        labels.set_vertical_alignment(VerticalAlignment::Center);
418        let title = TextBlock::new();
419        title.set_text(Some(&item.title));
420        title.set_font_size(12.0);
421        title.set_font_weight(FontWeight::SemiBold);
422        title.set_text_trimming(<dyn TextTrimming>::character_ellipsis());
423        labels.children().add(title.upcast::<Control>());
424        let detail = TextBlock::new();
425        detail.set_text(Some(&item.kind));
426        detail.set_font_size(10.0);
427        detail.set_foreground(Some(SolidColorBrush::from_uint32(0xffa9adba).into()));
428        detail.set_text_trimming(<dyn TextTrimming>::character_ellipsis());
429        labels.children().add(detail.upcast::<Control>());
430        Grid::set_column(&labels, 1);
431        row.children().add(labels.upcast::<Control>());
432        if item.usages > 0 {
433            let count = TextBlock::new();
434            count.set_text(Some(&item.usages.to_string()));
435            count.set_font_size(10.0);
436            count.set_foreground(Some(SolidColorBrush::from_uint32(0xffa9adba).into()));
437            count.set_margin(Thickness::new(5.0, 0.0, 0.0, 0.0));
438            count.set_vertical_alignment(VerticalAlignment::Center);
439            Grid::set_column(&count, 2);
440            row.children().add(count.upcast::<Control>());
441        }
442        let description = format!(
443            "{} · {} · {} · {} references",
444            item.title, item.kind, item.detail, item.usages
445        );
446        ToolTip::set_tip(&row, Some(Rc::new(description.clone())));
447        AutomationProperties::set_name(&row, Some(&description));
448        let weak = Rc::downgrade(self);
449        let pressed_row = row.downgrade();
450        let item = item.clone();
451        row.add_handler_with(
452            InputElement::pointer_pressed_event(),
453            move |_, event| {
454                if !event.properties().is_left_button_pressed {
455                    return;
456                }
457                if let Some(this) = weak.upgrade() {
458                    this.cancel_pending_drag();
459                    if event.click_count() == 2 {
460                        let callback = this.activate.borrow().clone();
461                        if let Some(callback) = callback {
462                            callback(&item);
463                            event.set_handled(true);
464                        }
465                    } else {
466                        if let Some(row) = pressed_row.upgrade() {
467                            event.pointer().capture(Some(&row.upcast::<InputElement>()));
468                        }
469                        *this.press.borrow_mut() = Some((
470                            item.clone(),
471                            event.clone(),
472                            event.get_position(Some(&this.list)),
473                        ));
474                    }
475                }
476            },
477            RoutingStrategies::TUNNEL,
478            false,
479        );
480        let weak = Rc::downgrade(self);
481        row.add_handler(InputElement::pointer_moved_event(), move |_, event| {
482            let Some(this) = weak.upgrade() else {
483                return;
484            };
485            if !event.properties().is_left_button_pressed {
486                if this
487                    .press
488                    .borrow()
489                    .as_ref()
490                    .is_some_and(|(_, press, _)| press.pointer().id() == event.pointer().id())
491                {
492                    this.cancel_pending_drag();
493                }
494                return;
495            }
496            let moved = this
497                .press
498                .borrow()
499                .as_ref()
500                .is_some_and(|(_, press, point)| {
501                    if press.pointer().id() != event.pointer().id() {
502                        return false;
503                    }
504                    let current = event.get_position(Some(&this.list));
505                    (current.x - point.x).abs() + (current.y - point.y).abs() > 6.0
506                });
507            if moved {
508                let press = this.press.borrow_mut().take();
509                if let Some((item, press, _)) = press {
510                    let callback = this.drag.borrow().clone();
511                    if let Some(callback) = callback {
512                        callback(&item, &press);
513                        event.set_handled(true);
514                    }
515                    // Native drag/drop and the design surface transfer capture to
516                    // their own control. If no host accepted the drag, release ours.
517                    if press
518                        .pointer()
519                        .captured()
520                        .is_some_and(|captured| this.root.is_visual_ancestor_of(&captured))
521                    {
522                        press.pointer().capture(None);
523                    }
524                }
525            }
526        });
527        let weak = Rc::downgrade(self);
528        row.add_handler(InputElement::pointer_released_event(), move |_, event| {
529            if let Some(this) = weak.upgrade() {
530                if this
531                    .press
532                    .borrow()
533                    .as_ref()
534                    .is_some_and(|(_, press, _)| press.pointer().id() == event.pointer().id())
535                {
536                    this.cancel_pending_drag();
537                }
538            }
539        });
540        let weak = Rc::downgrade(self);
541        row.add_handler(
542            InputElement::pointer_capture_lost_event(),
543            move |_, event| {
544                if let Some(this) = weak.upgrade() {
545                    if this
546                        .press
547                        .borrow()
548                        .as_ref()
549                        .is_some_and(|(_, press, _)| press.pointer().id() == event.pointer().id())
550                    {
551                        this.press.borrow_mut().take();
552                    }
553                }
554            },
555        );
556        row.upcast::<Control>()
557    }
558}
559
560#[cfg(test)]
561#[path = "component_browser_tests.rs"]
562mod tests;