From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 5EBC91FF09F for ; Tue, 01 Dec 2026 12:44:45 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 8E83121691; Tue, 01 Dec 2026 12:44:41 +0100 (CET) From: Dominik Csapak To: pdm-devel@lists.proxmox.com Subject: [PATCH datacenter-manager 3/3] ui: search box: add a panel to add and edit search filters Date: Tue, 1 Dec 2026 12:34:39 +0100 Message-ID: <20261201114434.1717720-4-d.csapak@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261201114434.1717720-1-d.csapak@proxmox.com> References: <20261201114434.1717720-1-d.csapak@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL 0.244 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: BGZTN2KTNBY7HX4PB5Q73YY5AB75XQZG X-Message-ID-Hash: BGZTN2KTNBY7HX4PB5Q73YY5AB75XQZG X-MailFrom: d.csapak@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox Datacenter Manager development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: so users don't have to know the search syntax and its categories to filter the search results. While the search box has the focus, the panel is shown above the search results, in the same popup and with the same width. A filter is added by choosing a category and a value. Depending on the category, the value is chosen from a list (e.g. types, remotes or views) or entered as text. Clicking a chip loads that filter into the panel to edit it, which is also how a filter can be made optional afterwards. The category is kept after adding a filter, so further values can be added quickly. The panel is kept to a single row with a short hint below, so it takes little space away from the results. Signed-off-by: Dominik Csapak --- ui/src/widget/mod.rs | 1 + ui/src/widget/search_box.rs | 106 +++++-- ui/src/widget/search_filter_panel.rs | 420 +++++++++++++++++++++++++++ 3 files changed, 507 insertions(+), 20 deletions(-) create mode 100644 ui/src/widget/search_filter_panel.rs diff --git a/ui/src/widget/mod.rs b/ui/src/widget/mod.rs index 4133644b..d97fd7ed 100644 --- a/ui/src/widget/mod.rs +++ b/ui/src/widget/mod.rs @@ -32,6 +32,7 @@ mod resource_tree; pub use resource_tree::{RedrawController, ResourceTree}; mod search_box; +mod search_filter_panel; pub use search_box::SearchBox; mod remote_selector; diff --git a/ui/src/widget/search_box.rs b/ui/src/widget/search_box.rs index d0122adb..1b35192a 100644 --- a/ui/src/widget/search_box.rs +++ b/ui/src/widget/search_box.rs @@ -22,6 +22,7 @@ use pdm_search::{Search, SearchTerm}; use crate::search_provider::get_search_provider; use super::ResourceTree; +use super::search_filter_panel::SearchFilterPanel; #[derive(Properties, PartialEq)] pub struct SearchBox {} @@ -40,7 +41,7 @@ impl From for VNode { } /// Returns the title of a search category, or `None` if the category is unknown. -fn category_title(category: &str) -> Option { +pub(super) fn category_title(category: &str) -> Option { let title = match category.to_lowercase().as_str() { "type" => tr!("Type"), "remote-type" => tr!("Remote Type"), @@ -94,6 +95,8 @@ pub enum Msg { CommitInput, EditLastFilter, SetSearch(String), + SubmitFilter(SearchTerm), + EditFilter(usize), RemoveFilter(usize), Clear, FocusChange(bool), @@ -105,10 +108,15 @@ pub struct PdmSearchBox { input_ref: NodeRef, filters: Vec, text: String, + // the index of the filter edited in the panel, a new one is added if this is `None` + editing: Option, + // counts the clicks on chips, so that the panel only reloads a filter when one is clicked + edits: usize, focus_tracker: FocusTracker, focus: bool, global_shortcut_listener: Closure, toggle_focus: bool, + focus_input: bool, _observer: Option>, } @@ -154,11 +162,17 @@ impl PdmSearchBox { Badge::new(html! {<>{format!("{title}: {}", term.value)}{remove}}) .color_scheme(scheme) .tip(tip) + .class("pwt-pointer") // inset, as the scrolling chip container clips anything drawn outside of a chip .style( "box-shadow", - outlined.then_some("inset 0 0 0 1px var(--pwt-color-border)"), + if self.editing == Some(index) { + Some("inset 0 0 0 2px var(--pwt-color-primary)") + } else { + outlined.then_some("inset 0 0 0 1px var(--pwt-color-border)") + }, ) + .onclick(ctx.link().callback(move |_| Msg::EditFilter(index))) .into() } } @@ -179,9 +193,12 @@ impl Component for PdmSearchBox { input_ref: Default::default(), filters: Vec::new(), text: String::new(), + editing: None, + edits: 0, focus_tracker: FocusTracker::new(ctx.link().callback(Msg::FocusChange)), focus: false, toggle_focus: false, + focus_input: false, global_shortcut_listener: Closure::wrap(Box::new(move |e: KeyboardEvent| { match (e.ctrl_key(), e.shift_key(), e.code().as_str()) { (true, _, "Space") | (true, true, "KeyF") => { @@ -213,30 +230,61 @@ impl Component for PdmSearchBox { } } Msg::EditLastFilter => match self.filters.pop() { - Some(term) => self.text = term.to_string(), + Some(term) => { + self.text = term.to_string(); + if self.editing == Some(self.filters.len()) { + self.editing = None; + } + } None => return false, }, Msg::SetSearch(search) => { (self.filters, self.text) = split_filters(&search, true).unwrap_or((Vec::new(), search)); + self.editing = None; + } + Msg::SubmitFilter(term) => match self.editing.take() { + Some(index) if index < self.filters.len() => self.filters[index] = term, + _ => self.filters.push(term), + }, + Msg::EditFilter(index) => { + // clicking the edited filter again goes back to adding one + self.editing = (self.editing != Some(index)).then_some(index); + self.edits = self.edits.wrapping_add(1); + // the panel is only shown while the search box has the focus + self.focus_input = true; } Msg::RemoveFilter(index) => { - if index < self.filters.len() { - self.filters.remove(index); + if index >= self.filters.len() { + return false; } + self.filters.remove(index); + // keep editing another filter + self.editing = match self.editing { + Some(editing) if editing == index => None, + Some(editing) if editing > index => Some(editing - 1), + editing => editing, + }; } Msg::Clear => { self.filters.clear(); self.text.clear(); + self.editing = None; } Msg::FocusChange(focus) => { if self.focus == focus { return false; } self.focus = focus; + if !focus { + self.editing = None; + } } Msg::ToggleFocus => self.toggle_focus = true, - Msg::NavigatedToEntry => self.focus = false, + Msg::NavigatedToEntry => { + self.focus = false; + self.editing = None; + } } true } @@ -245,24 +293,35 @@ impl Component for PdmSearchBox { let search_term = self.search_term(); let link = ctx.link(); + let show_results = self.focus && !search_term.is_empty(); + let search_result = ResourceTree::new() + .key("results") .search_term(search_term.clone()) .search_only(true) + .style("display", (!show_results).then_some("none")) + .border(true) + .height(400) + .on_navigate(link.callback(|_| Msg::NavigatedToEntry)); + + // keyed, so that showing the filter panel does not recreate the results + let filter_panel = self.focus.then(|| { + Container::new() + .key("filter-panel") + .with_child(SearchFilterPanel::new( + self.editing + .and_then(|index| Some((self.edits, self.filters.get(index)?.clone()))), + link.callback(Msg::SubmitFilter), + )) + }); + + let popup = Container::new() + .class("pwt-d-flex pwt-flex-direction-column pwt-shadow2") .style("position", "absolute") .style("z-index", "100") - .style( - "display", - if self.focus && !search_term.is_empty() { - "" - } else { - "none" - }, - ) - .border(true) .width(CssLength::Fraction(0.5)) - .height(400) - .on_navigate(link.callback(|_| Msg::NavigatedToEntry)) - .class("pwt-shadow2"); + .with_optional_child(filter_panel) + .with_child(search_result); let filters = Container::new() .class("pwt-d-flex pwt-align-items-center") @@ -322,7 +381,7 @@ impl Component for PdmSearchBox { let field = Container::new() .class("pwt-input pwt-input-type-text pwt-w-100") - // clicking the chips or the trigger must not move the focus out of the search box + // clicking the chips or triggers must not move the focus out of the search box .onmousedown(|event: MouseEvent| { if event.target_dyn_into::().is_none() { event.prevent_default(); @@ -339,7 +398,7 @@ impl Component for PdmSearchBox { .style("flex-basis", "240px") // to avoid changing size with trigger .min_width(240) // placeholder text .with_child(field) - .with_child(search_result) + .with_child(popup) .into() } @@ -369,6 +428,13 @@ impl Component for PdmSearchBox { self.toggle_focus = false; } + + if self.focus_input { + if let Some(el) = self.input_ref.cast::() { + let _ = el.focus(); + } + self.focus_input = false; + } } fn destroy(&mut self, _ctx: &Context) { diff --git a/ui/src/widget/search_filter_panel.rs b/ui/src/widget/search_filter_panel.rs new file mode 100644 index 00000000..d73ad9b6 --- /dev/null +++ b/ui/src/widget/search_filter_panel.rs @@ -0,0 +1,420 @@ +use std::rc::Rc; + +use web_sys::HtmlInputElement; +use yew::virtual_dom::{VComp, VNode}; + +use pwt::AsyncPool; +use pwt::prelude::*; +use pwt::widget::form::{Checkbox, Combobox, Field}; +use pwt::widget::{Button, Container, Panel, Row}; + +use proxmox_yew_comp::http_get; + +use pdm_api_types::views::ViewConfig; +use pdm_search::SearchTerm; + +use crate::get_remote_list; + +use super::search_box::category_title; + +#[derive(Clone, Copy, PartialEq)] +enum FilterInput { + /// A value picked from a fixed list. + Choices(&'static [&'static str]), + Boolean, + Remote, + View, + /// Free text with optional suggestions. + Text(&'static [&'static str]), +} + +const CATEGORIES: &[(&str, FilterInput)] = &[ + ( + "type", + FilterInput::Choices(&[ + "qemu", + "lxc", + "node", + "storage", + "datastore", + "network", + "remote", + ]), + ), + ("remote-type", FilterInput::Choices(&["pve", "pbs"])), + ("remote", FilterInput::Remote), + ( + "status", + FilterInput::Text(&[ + "running", + "stopped", + "online", + "offline", + "available", + "unknown", + ]), + ), + ("template", FilterInput::Boolean), + ("name", FilterInput::Text(&[])), + ("id", FilterInput::Text(&[])), + ("node", FilterInput::Text(&[])), + ("pool", FilterInput::Text(&[])), + ("tag", FilterInput::Text(&[])), + ("property", FilterInput::Text(&[])), + ("network-type", FilterInput::Text(&["zone", "fabric"])), + ("ha", FilterInput::Text(&[])), + ("lock", FilterInput::Text(&[])), + ("view", FilterInput::View), +]; + +fn choice_title(value: &str) -> String { + match value { + "qemu" => tr!("Virtual Machine"), + "lxc" => tr!("Container"), + "node" => tr!("Node"), + "storage" => tr!("Storage"), + "datastore" => tr!("Datastore"), + "network" => tr!("Network"), + "remote" => tr!("Remote"), + "pve" => tr!("Virtual Environment"), + "pbs" => tr!("Backup Server"), + "true" => tr!("Yes"), + "false" => tr!("No"), + other => other.to_string(), + } +} + +impl FilterInput { + /// Returns whether `value` can be used for this input. + fn accepts(&self, value: &str) -> bool { + match self { + FilterInput::Choices(choices) => choices.iter().any(|c| c.eq_ignore_ascii_case(value)), + FilterInput::Boolean => ["true", "false"] + .iter() + .any(|b| b.eq_ignore_ascii_case(value)), + // the views may not be loaded yet + FilterInput::View => false, + FilterInput::Remote | FilterInput::Text(_) => true, + } + } +} + +fn find_category(name: &str) -> Option<(&'static str, FilterInput)> { + CATEGORIES + .iter() + .find(|(category, _)| category.eq_ignore_ascii_case(name)) + .copied() +} + +/// Form to add a single categorized term to the resource search, or to edit an existing one. +#[derive(Properties, PartialEq, Clone)] +pub struct SearchFilterPanel { + /// The filter to edit and the number of the edit, a new one is added if this is `None`. + term: Option<(usize, SearchTerm)>, + on_submit: Callback, +} + +impl SearchFilterPanel { + pub fn new( + term: Option<(usize, SearchTerm)>, + on_submit: impl Into>, + ) -> Self { + Self { + term, + on_submit: on_submit.into(), + } + } +} + +impl From for VNode { + fn from(val: SearchFilterPanel) -> Self { + VComp::new::(Rc::new(val), None).into() + } +} + +pub enum Msg { + Views(Vec), + SetCategory(String), + SetValue(String), + SetRequired(bool), + Submit, +} + +pub struct PdmSearchFilterPanel { + category: Option<(&'static str, FilterInput)>, + value: String, + required: bool, + views: Rc>, + views_requested: bool, + async_pool: AsyncPool, +} + +impl PdmSearchFilterPanel { + fn load_term(&mut self, ctx: &Context, term: Option<&SearchTerm>) { + self.category = term.and_then(|term| find_category(term.category.as_deref()?)); + self.value = term.map(|term| term.value.clone()).unwrap_or_default(); + self.required = term.is_none_or(|term| !term.is_optional()); + self.load_views(ctx); + } + + // only once the category is chosen, as the panel is created on every focus of the search box + fn load_views(&mut self, ctx: &Context) { + if self.views_requested || !matches!(self.category, Some((_, FilterInput::View))) { + return; + } + self.views_requested = true; + self.async_pool.send_future(ctx.link().clone(), async move { + let views = http_get("/config/views", None) + .await + .map(|list: Vec| { + let mut list: Vec = + list.into_iter().map(|config| config.id.into()).collect(); + list.sort(); + list + }) + .unwrap_or_default(); + Msg::Views(views) + }); + } + + fn render_value_input(&self, ctx: &Context) -> Html { + let link = ctx.link(); + let Some((_, input)) = self.category else { + // shows the value of a filter with an unknown category + return Field::new() + .disabled(true) + .value(AttrValue::from(self.value.clone())) + .into(); + }; + let value = AttrValue::from(self.value.clone()); + let on_change = link.callback(Msg::SetValue); + + match input { + // required, as the clear trigger of an optional selector replaces its focused input + // element once a value is set, which closes the search box + FilterInput::Choices(choices) => Combobox::new() + .required(true) + .items(Rc::new(choices.iter().map(|c| (*c).into()).collect())) + .render_value(|value: &AttrValue| html! {choice_title(value)}) + .value(value) + .on_change(on_change) + .into(), + FilterInput::Boolean => Combobox::new() + .required(true) + .items(Rc::new(vec!["true".into(), "false".into()])) + .render_value(|value: &AttrValue| html! {choice_title(value)}) + .value(value) + .on_change(on_change) + .into(), + FilterInput::Remote => { + let remotes = get_remote_list(link) + .map(|list| list.iter().map(|remote| remote.id.clone().into()).collect()) + .unwrap_or_default(); + Combobox::new() + .editable(true) + .items(Rc::new(remotes)) + .value(value) + .on_change(on_change) + .into() + } + FilterInput::View => Combobox::new() + .required(true) + .items(self.views.clone()) + .value(value) + .on_change(on_change) + .into(), + FilterInput::Text([]) => Field::new().value(value).on_input(on_change).into(), + FilterInput::Text(suggestions) => Combobox::new() + .editable(true) + .items(Rc::new(suggestions.iter().map(|s| (*s).into()).collect())) + .value(value) + .on_change(on_change) + .into(), + } + } +} + +impl Component for PdmSearchFilterPanel { + type Message = Msg; + type Properties = SearchFilterPanel; + + fn create(ctx: &Context) -> Self { + let mut this = Self { + category: None, + value: String::new(), + required: true, + views: Rc::new(Vec::new()), + views_requested: false, + async_pool: AsyncPool::new(), + }; + this.load_term(ctx, ctx.props().term.as_ref().map(|(_, term)| term)); + this + } + + fn changed(&mut self, ctx: &Context, old_props: &Self::Properties) -> bool { + // with the number of the edit, so that another chip with the same term is loaded too + if ctx.props().term != old_props.term { + match &ctx.props().term { + Some((_, term)) => self.load_term(ctx, Some(term)), + // keep the category after an edit, like after adding a filter + None => self.value.clear(), + } + } + true + } + + fn update(&mut self, ctx: &Context, msg: Self::Message) -> bool { + match msg { + Msg::Views(views) => self.views = Rc::new(views), + Msg::SetCategory(name) => { + let category = find_category(&name); + if category != self.category { + // keep the value of a filter with an unknown category, to fix it in place + let keep = self.category.is_none() + && category.is_some_and(|(_, input)| input.accepts(&self.value)); + if !keep { + self.value.clear(); + } + self.category = category; + self.load_views(ctx); + } + } + Msg::SetValue(value) => self.value = value, + Msg::SetRequired(required) => self.required = required, + Msg::Submit => { + let value = self.value.trim(); + let Some((name, input)) = self.category else { + return false; + }; + // a term ends at the next whitespace, so only a single word can be used + if value.is_empty() || value.contains(char::is_whitespace) { + return false; + } + // the server always limits the results to the selected view + let required = self.required || input == FilterInput::View; + let term = SearchTerm::new(value) + .category(Some(name)) + .optional(!required); + ctx.props().on_submit.emit(term); + // Keep the category, so that further values can be added quickly. This also keeps + // the focused value input, replacing it would close the search box. + self.value.clear(); + } + } + true + } + + fn view(&self, ctx: &Context) -> Html { + let props = ctx.props(); + let link = ctx.link(); + + let value = self.value.trim(); + let valid = + self.category.is_some() && !value.is_empty() && !value.contains(char::is_whitespace); + + let category = Combobox::new() + // see the value inputs on why this is required + .required(true) + .items(Rc::new( + CATEGORIES.iter().map(|(name, _)| (*name).into()).collect(), + )) + .render_value(|name: &AttrValue| { + html! {category_title(name).unwrap_or_else(|| name.to_string())} + }) + .placeholder(tr!("Category")) + // an empty value instead of `None`, which would keep the previous category + .value(AttrValue::from( + self.category.map(|(name, _)| name).unwrap_or_default(), + )) + .on_change(link.callback(Msg::SetCategory)); + + // the server always limits the results to the selected view + let is_view = matches!(self.category, Some((_, FilterInput::View))); + let required = Checkbox::new() + .checked(self.required || is_view) + .disabled(is_view) + .box_label(tr!("Required")) + .on_input(link.callback(Msg::SetRequired)); + + let submit_text = if props.term.is_some() { + tr!("Update") + } else { + tr!("Add") + }; + + let form = Row::new() + .padding_x(2) + .padding_top(2) + .padding_bottom(1) + .gap(2) + .class("pwt-align-items-center") + // Keyed children, so that only the value input is replaced when the category changes, + // and no state of the previous one is kept. Replacing the focused category field + // would move the focus out of the search box and close the panel. + .with_child( + Container::new() + .key("category") + .width(180) + .with_child(category), + ) + .with_child( + Container::new() + .key(self.category.map(|(name, _)| name).unwrap_or_default()) + .class("pwt-flex-fill") + // Enter in a picker, including its filter field, is used to pick a value, so only + // submit from the text inputs outside of it + .onkeydown(link.batch_callback(|event: KeyboardEvent| { + let from_input = event + .target_dyn_into::() + .is_some_and(|input| matches!(input.closest("[popover]"), Ok(None))); + (event.key() == "Enter" && from_input).then_some(Msg::Submit) + })) + .with_child(self.render_value_input(ctx)), + ) + .with_child(required.key("required")) + .with_child( + Button::new(submit_text) + .key("submit") + .class("pwt-scheme-primary") + .disabled(!valid) + .onclick(link.callback(|_| Msg::Submit)), + ); + + let hint = Container::new() + .padding_x(2) + .padding_bottom(2) + .class("pwt-font-label-small pwt-opacity-75") + .with_child(tr!( + "Required filters must all match, of the others at least one. Type filters as 'category:value', with '+' for required ones." + )); + + Panel::new() + .border(true) + // let clicks on the panel keep the focus inside the search box + .attribute("tabindex", "-1") + .with_child(form) + .with_child(hint) + .into() + } +} + +#[cfg(test)] +mod tests { + use pdm_api_types::resource::SearchCategory; + + use super::{CATEGORIES, category_title}; + + #[test] + fn categories_are_known() { + for (name, _) in CATEGORIES { + assert!(category_title(name).is_some(), "no title for '{name}'"); + // 'view' is handled by the API itself, not as a category of the resources + if *name != "view" { + assert!( + name.parse::().is_ok(), + "unknown category '{name}'" + ); + } + } + } +} -- 2.47.3