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 222731FF09F for ; Tue, 01 Dec 2026 16:47:07 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 8E25E21435; Tue, 01 Dec 2026 16:47:05 +0100 (CET) From: Dominik Csapak To: pdm-devel@lists.proxmox.com Subject: [PATCH datacenter-manager v2 3/3] ui: search box: add a panel to add and edit search filters Date: Tue, 1 Dec 2026 16:45:49 +0100 Message-ID: <20261201154656.3607636-4-d.csapak@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261201154656.3607636-1-d.csapak@proxmox.com> References: <20261201154656.3607636-1-d.csapak@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL 0.241 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: GZJ5X3G7RQBN5HVCI2Y537VT2QH7ANIT X-Message-ID-Hash: GZJ5X3G7RQBN5HVCI2Y537VT2QH7ANIT 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, views or folders) 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 | 111 +++++-- ui/src/widget/search_filter_panel.rs | 427 +++++++++++++++++++++++++++ 3 files changed, 518 insertions(+), 21 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 7179fa32..a61511c2 100644 --- a/ui/src/widget/mod.rs +++ b/ui/src/widget/mod.rs @@ -35,6 +35,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 4ec5970f..78e853fb 100644 --- a/ui/src/widget/search_box.rs +++ b/ui/src/widget/search_box.rs @@ -14,7 +14,7 @@ use pwt::{ prelude::*, props::CssLength, state::{SharedState, SharedStateObserver}, - widget::{Badge, Container, Fa, Input, MiniScroll, MiniScrollMode, Row, Trigger}, + widget::{Badge, Column, Container, Fa, Input, MiniScroll, MiniScrollMode, Row, Trigger}, }; use pdm_api_types::resource::SearchCategory; @@ -23,6 +23,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 {} @@ -41,7 +42,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() { // selected by the API itself, not categories of the resources "view" => tr!("View"), @@ -98,6 +99,8 @@ pub enum Msg { CommitInput, EditLastFilter, SetSearch(String), + SubmitFilter(SearchTerm), + EditFilter(usize), RemoveFilter(usize), Clear, FocusChange(bool), @@ -109,10 +112,17 @@ 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, + // created once, as a new callback would make the panel render again on every input + on_submit_filter: Callback, _observer: Option>, } @@ -158,11 +168,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() } } @@ -183,9 +199,13 @@ 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, + on_submit_filter: ctx.link().callback(Msg::SubmitFilter), 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") => { @@ -217,30 +237,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 } @@ -249,24 +300,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()))), + self.on_submit_filter.clone(), + )) + }); + + let popup = Column::new() + .class("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 = Row::new().class(AlignItems::Center).gap(1).children( self.filters @@ -323,7 +385,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(); @@ -340,7 +402,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() } @@ -370,6 +432,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..9ff70750 --- /dev/null +++ b/ui/src/widget/search_filter_panel.rs @@ -0,0 +1,427 @@ +use std::rc::Rc; + +use web_sys::HtmlInputElement; +use yew::virtual_dom::{VComp, VNode}; + +use pwt::css::{AlignItems, ColorScheme, Flex, FontStyle, Opacity}; +use pwt::prelude::*; +use pwt::widget::form::{Checkbox, Combobox, Field}; +use pwt::widget::{Button, Container, Panel, Row}; + +use pdm_api_types::resource::SearchCategory; +use pdm_search::SearchTerm; + +use crate::folders::FolderCatalog; +use crate::{ViewListContext, 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, + Folder, + /// Free text with optional suggestions. + Text(&'static [&'static str]), +} + +/// The categories in the order they are offered. +const CATEGORIES: &[&str] = &[ + "type", + "remote-type", + "remote", + "status", + "template", + "name", + "id", + "node", + "pool", + "tag", + "property", + "network-type", + "ha", + "lock", + "view", + "folder", +]; + +/// Returns how the value of a category is entered, or `None` if the category is unknown. +fn filter_input(category: &str) -> Option { + let input = match category.to_lowercase().as_str() { + "view" => FilterInput::View, + "folder" => FilterInput::Folder, + category => match category.parse().ok()? { + SearchCategory::Type => FilterInput::Choices(&[ + "qemu", + "lxc", + "node", + "storage", + "datastore", + "network", + "remote", + ]), + SearchCategory::RemoteType => FilterInput::Choices(&["pve", "pbs"]), + SearchCategory::Remote => FilterInput::Remote, + SearchCategory::Status => FilterInput::Text(&[ + "running", + "stopped", + "online", + "offline", + "available", + "unknown", + ]), + SearchCategory::Template => FilterInput::Boolean, + SearchCategory::NetworkType => FilterInput::Text(&["zone", "fabric"]), + SearchCategory::Name + | SearchCategory::Id + | SearchCategory::Node + | SearchCategory::Pool + | SearchCategory::Tag + | SearchCategory::Property + | SearchCategory::HaState + | SearchCategory::Lock => FilterInput::Text(&[]), + }, + }; + Some(input) +} + +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)), + // only listed views and folders can be picked + FilterInput::View | FilterInput::Folder => false, + FilterInput::Remote | FilterInput::Text(_) => true, + } + } + + /// Whether the term selects the view or folder that the server always limits the results to. + fn is_scope(&self) -> bool { + matches!(self, FilterInput::View | FilterInput::Folder) + } +} + +fn find_category(name: &str) -> Option<(&'static str, FilterInput)> { + let category = CATEGORIES + .iter() + .find(|category| category.eq_ignore_ascii_case(name))?; + Some((*category, filter_input(category)?)) +} + +/// 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 { + SetCategory(String), + SetValue(String), + SetRequired(bool), + Submit, +} + +pub struct PdmSearchFilterPanel { + category: Option<(&'static str, FilterInput)>, + value: String, + required: bool, +} + +impl PdmSearchFilterPanel { + fn load_term(&mut self, 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()); + } + + 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 => { + let views = link + .context::(Callback::noop()) + .map(|(views, _)| views.ids().iter().map(|id| id.clone().into()).collect()) + .unwrap_or_default(); + Combobox::new() + .required(true) + .items(Rc::new(views)) + .value(value) + .on_change(on_change) + .into() + } + FilterInput::Folder => { + // the server rejects folders that are only listed as the parent of another one + let folders = FolderCatalog::get(link) + .folders() + .filter(|folder| folder.openable()) + .map(|folder| AttrValue::from(folder.path().to_owned())) + .collect(); + Combobox::new() + .required(true) + .items(Rc::new(folders)) + .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, + }; + this.load_term(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(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::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; + } + } + 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; + } + let required = self.required || input.is_scope(); + 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)); + + let is_scope = self.category.is_some_and(|(_, input)| input.is_scope()); + let required = Checkbox::new() + .checked(self.required || is_scope) + .disabled(is_scope) + .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(AlignItems::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(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(ColorScheme::Primary) + .disabled(!valid) + .onclick(link.callback(|_| Msg::Submit)), + ); + + let hint = Container::new() + .padding_x(2) + .padding_bottom(2) + .class(FontStyle::LabelSmall) + .class(Opacity::ThreeQuarters) + .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 super::{CATEGORIES, category_title, filter_input}; + + #[test] + fn categories_are_known() { + for name in CATEGORIES { + assert!(category_title(name).is_some(), "no title for '{name}'"); + assert!(filter_input(name).is_some(), "unknown category '{name}'"); + } + } +} -- 2.47.3