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 B1D0A1FF09F for ; Tue, 01 Dec 2026 12:44:42 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 7F650215C2; Tue, 01 Dec 2026 12:44:40 +0100 (CET) From: Dominik Csapak To: pdm-devel@lists.proxmox.com Subject: [PATCH datacenter-manager 2/3] ui: search box: show categorized search terms as chips Date: Tue, 1 Dec 2026 12:34:38 +0100 Message-ID: <20261201114434.1717720-3-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: TNKDTTMPESJLZAIEIT3QX3UEB3LUM4YR X-Message-ID-Hash: TNKDTTMPESJLZAIEIT3QX3UEB3LUM4YR 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 it's always clear which filters are active, and each of them can be removed with a single click. Terms with a category become chips in front of the text input when they're completed with a space or Enter, while plain search words stay in the input. Backspace on an empty input turns the last chip back into text, so it can be edited. Searches set from the dashboard are split the same way. Required terms are highlighted, and terms with an unknown category are shown as errors, since they never match anything. The tooltip of a chip shows the term as written in the search syntax. Signed-off-by: Dominik Csapak --- ui/css/pdm.scss | 13 ++ ui/src/widget/search_box.rs | 334 ++++++++++++++++++++++++++++++------ 2 files changed, 291 insertions(+), 56 deletions(-) diff --git a/ui/css/pdm.scss b/ui/css/pdm.scss index 88fa5c6d..cdfbedd3 100644 --- a/ui/css/pdm.scss +++ b/ui/css/pdm.scss @@ -55,6 +55,19 @@ } } +// The mini scroll arrows are sized for toolbars and would make the search field taller as soon as +// it shows a filter chip. +.pdm-search-filters { + .pwt-mini-scroll-left-arrow, + .pwt-mini-scroll-right-arrow { + font-size: inherit; + + &.visible { + padding-block: 0; + } + } +} + .pdm-type-icon { position: relative; diff --git a/ui/src/widget/search_box.rs b/ui/src/widget/search_box.rs index 413c214d..d0122adb 100644 --- a/ui/src/widget/search_box.rs +++ b/ui/src/widget/search_box.rs @@ -2,20 +2,23 @@ use std::rc::Rc; use gloo_utils::{document, window}; use wasm_bindgen::{JsCast, prelude::Closure}; -use web_sys::{Element, HtmlElement}; +use web_sys::{Element, HtmlElement, HtmlInputElement}; use yew::{ Component, NodeRef, Properties, virtual_dom::{VComp, VNode}, }; use pwt::{ - dom::{IntoHtmlElement, focus::FocusTracker}, + css::ColorScheme, + dom::focus::FocusTracker, prelude::*, props::CssLength, state::{SharedState, SharedStateObserver}, - widget::{Container, Trigger, form::Field}, + widget::{Badge, Container, Fa, Input, MiniScroll, MiniScrollMode, Trigger}, }; +use pdm_search::{Search, SearchTerm}; + use crate::search_provider::get_search_provider; use super::ResourceTree; @@ -36,22 +39,128 @@ impl From for VNode { } } +/// Returns the title of a search category, or `None` if the category is unknown. +fn category_title(category: &str) -> Option { + let title = match category.to_lowercase().as_str() { + "type" => tr!("Type"), + "remote-type" => tr!("Remote Type"), + "remote" => tr!("Remote"), + "status" => tr!("Status"), + "template" => tr!("Template"), + "name" => tr!("Name"), + "id" => tr!("ID"), + "node" => tr!("Node"), + "pool" => tr!("Pool"), + "tag" => tr!("Tag"), + "property" => tr!("Property"), + "network-type" => tr!("Network Type"), + "ha" => tr!("HA State"), + "lock" => tr!("Lock"), + "view" => tr!("View"), + _ => return None, + }; + Some(title) +} + +/// Splits the categorized terms off `text`, but not a last term that may still be typed. +/// +/// Returns `None` if there are no such terms, so that the text can be kept as typed. +fn split_filters(text: &str, complete: bool) -> Option<(Vec, String)> { + let (text, last) = if complete || text.ends_with(char::is_whitespace) { + (text, "") + } else { + text.rsplit_once(char::is_whitespace).unwrap_or(("", text)) + }; + + let mut search = Search::from(text); + let filters = search.take_terms(|term| term.category.is_some()); + if filters.is_empty() { + return None; + } + + let mut text = search.to_string(); + // keep separating the text from what is still typed + if !complete && !text.is_empty() { + text.push(' '); + } + text.push_str(last); + + Some((filters, text)) +} + pub enum Msg { - ChangeTerm(String, bool), // force value + /// The text of the input, and whether it was typed at its end. + Input(String, bool), + CommitInput, + EditLastFilter, + SetSearch(String), + RemoveFilter(usize), + Clear, FocusChange(bool), ToggleFocus, NavigatedToEntry, } pub struct PdmSearchBox { - search_field_ref: NodeRef, - search_term: String, + input_ref: NodeRef, + filters: Vec, + text: String, focus_tracker: FocusTracker, focus: bool, global_shortcut_listener: Closure, toggle_focus: bool, _observer: Option>, - force_value: bool, +} + +impl PdmSearchBox { + fn search_term(&self) -> String { + let mut terms: Vec = self.filters.iter().map(ToString::to_string).collect(); + let text = self.text.trim(); + if !text.is_empty() { + terms.push(text.to_string()); + } + terms.join(" ") + } + + fn render_filter(&self, ctx: &Context, index: usize, term: &SearchTerm) -> Html { + let category = term.category.as_deref().unwrap_or_default(); + // outline optional terms, as a filled neutral chip blends into the field in dark themes + let (title, tip, scheme, outlined) = match category_title(category) { + Some(title) if term.is_optional() => { + (title, term.to_string(), ColorScheme::Neutral, true) + } + Some(title) => ( + title, + term.to_string(), + ColorScheme::PrimaryContainer, + false, + ), + None => ( + category.to_string(), + tr!("Unknown category '{0}', matches nothing", category), + ColorScheme::ErrorContainer, + false, + ), + }; + + let remove = Fa::new("times") + .class("pwt-pointer") + .attribute("aria-label", tr!("Remove")) + .onclick(ctx.link().callback(move |event: MouseEvent| { + event.stop_propagation(); + Msg::RemoveFilter(index) + })); + + Badge::new(html! {<>{format!("{title}: {}", term.value)}{remove}}) + .color_scheme(scheme) + .tip(tip) + // 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)"), + ) + .into() + } } impl Component for PdmSearchBox { @@ -63,15 +172,13 @@ impl Component for PdmSearchBox { let link = ctx.link().clone(); let _observer = get_search_provider(ctx).map(|search| { search.add_listener(ctx.link().batch_callback(|value: SharedState| { - vec![ - Msg::ToggleFocus, - Msg::ChangeTerm(value.read().clone(), true), - ] + vec![Msg::ToggleFocus, Msg::SetSearch(value.read().clone())] })) }); Self { - search_field_ref: Default::default(), - search_term: String::new(), + input_ref: Default::default(), + filters: Vec::new(), + text: String::new(), focus_tracker: FocusTracker::new(ctx.link().callback(Msg::FocusChange)), focus: false, toggle_focus: false, @@ -84,42 +191,68 @@ impl Component for PdmSearchBox { } })), _observer, - force_value: false, } } fn update(&mut self, _ctx: &Context, msg: Self::Message) -> bool { match msg { - Msg::ChangeTerm(term, force_value) => { - self.search_term = term; - self.force_value = force_value; - true + Msg::Input(text, at_end) => { + // a term typed in front of other text may not be complete yet + match at_end.then(|| split_filters(&text, false)).flatten() { + Some((filters, text)) => { + self.filters.extend(filters); + self.text = text; + } + None => self.text = text, + } } - Msg::FocusChange(focus) => { - let changed = self.focus != focus; - self.focus = focus; - changed + Msg::CommitInput => { + if let Some((filters, text)) = split_filters(&self.text, true) { + self.filters.extend(filters); + self.text = text; + } } - Msg::ToggleFocus => { - self.toggle_focus = true; - true + Msg::EditLastFilter => match self.filters.pop() { + Some(term) => self.text = term.to_string(), + None => return false, + }, + Msg::SetSearch(search) => { + (self.filters, self.text) = + split_filters(&search, true).unwrap_or((Vec::new(), search)); } - Msg::NavigatedToEntry => { - self.focus = false; - true + Msg::RemoveFilter(index) => { + if index < self.filters.len() { + self.filters.remove(index); + } + } + Msg::Clear => { + self.filters.clear(); + self.text.clear(); } + Msg::FocusChange(focus) => { + if self.focus == focus { + return false; + } + self.focus = focus; + } + Msg::ToggleFocus => self.toggle_focus = true, + Msg::NavigatedToEntry => self.focus = false, } + true } fn view(&self, ctx: &yew::Context) -> yew::Html { + let search_term = self.search_term(); + let link = ctx.link(); + let search_result = ResourceTree::new() - .search_term(self.search_term.clone()) + .search_term(search_term.clone()) .search_only(true) .style("position", "absolute") .style("z-index", "100") .style( "display", - if self.focus && !self.search_term.is_empty() { + if self.focus && !search_term.is_empty() { "" } else { "none" @@ -128,14 +261,76 @@ impl Component for PdmSearchBox { .border(true) .width(CssLength::Fraction(0.5)) .height(400) - .on_navigate(ctx.link().callback(|_| Msg::NavigatedToEntry)) + .on_navigate(link.callback(|_| Msg::NavigatedToEntry)) .class("pwt-shadow2"); - let clear_trigger_icon = if self.search_term.is_empty() { + let filters = Container::new() + .class("pwt-d-flex pwt-align-items-center") + .style("gap", "var(--pwt-spacer-1)") + .children( + self.filters + .iter() + .enumerate() + .map(|(index, term)| self.render_filter(ctx, index, term)), + ); + let filters = MiniScroll::new(filters) + .scroll_mode(MiniScrollMode::Arrow) + .class("pdm-search-filters") + .style("flex", "0 1 auto") + .style("min-width", "0") + // avoid the gap of the field in front of the placeholder + .style("display", self.filters.is_empty().then_some("none")); + + let input = Input::new() + // Not shrinking with the filters, as their width would then depend on whether the + // mini scroll shows its arrows, which can make them appear and disappear endlessly. + .style("flex", "1 0 80px") + .attribute("type", "text") + .attribute("value", self.text.clone()) + .attribute("placeholder", tr!("Search (Ctrl+Space / Ctrl+Shift+F)")) + .oninput(link.callback(|event: InputEvent| { + let input: HtmlInputElement = event.target_unchecked_into(); + let value = input.value(); + // the selection is counted in UTF-16 code units + let at_end = input + .selection_start() + .ok() + .flatten() + .is_none_or(|pos| pos as usize == value.encode_utf16().count()); + Msg::Input(value, at_end) + })) + .onkeydown(link.batch_callback({ + let empty = self.text.is_empty() && !self.filters.is_empty(); + move |event: KeyboardEvent| match event.key().as_str() { + "Enter" => vec![Msg::CommitInput], + "Backspace" if empty => { + event.prevent_default(); + vec![Msg::EditLastFilter] + } + _ => Vec::new(), + } + })) + .into_html_with_ref(self.input_ref.clone()); + + let clear_trigger_icon = if search_term.is_empty() { "" } else { "fa fa-times" }; + let clear_trigger = + Trigger::new(clear_trigger_icon).on_activate(link.callback(|_| Msg::Clear)); + + 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 + .onmousedown(|event: MouseEvent| { + if event.target_dyn_into::().is_none() { + event.prevent_default(); + } + }) + .with_child(filters) + .with_child(input) + .with_child(clear_trigger); Container::new() .onfocusin(self.focus_tracker.get_focus_callback(true)) @@ -143,23 +338,7 @@ impl Component for PdmSearchBox { .flex(2.0) .style("flex-basis", "240px") // to avoid changing size with trigger .min_width(240) // placeholder text - .with_child( - Container::new() - .style("display", "contents") - .with_child( - Field::new() - .placeholder(tr!("Search (Ctrl+Space / Ctrl+Shift+F)")) - .value(self.force_value.then_some(self.search_term.clone())) - .with_trigger( - Trigger::new(clear_trigger_icon).on_activate( - ctx.link().callback(|_| Msg::ChangeTerm("".into(), true)), - ), - true, - ) - .on_input(ctx.link().callback(|term| Msg::ChangeTerm(term, false))), - ) - .into_html_with_ref(self.search_field_ref.clone()), - ) + .with_child(field) .with_child(search_result) .into() } @@ -177,7 +356,6 @@ impl Component for PdmSearchBox { } if self.toggle_focus { - // FIXME: ugly conversion/query code, we should be able to make that more readable if self.focus { if let Some(Ok(el)) = document() .active_element() @@ -185,12 +363,8 @@ impl Component for PdmSearchBox { { let _ = el.blur(); } - } else if let Some(el) = self.search_field_ref.clone().into_html_element() { - if let Ok(Some(el)) = el.query_selector("input") { - if let Ok(el) = el.dyn_into::() { - let _ = el.focus(); - } - } + } else if let Some(el) = self.input_ref.cast::() { + let _ = el.focus(); } self.toggle_focus = false; @@ -209,3 +383,51 @@ impl Component for PdmSearchBox { }; } } + +#[cfg(test)] +mod tests { + use super::split_filters; + + fn split(text: &str, complete: bool) -> Option<(Vec, String)> { + split_filters(text, complete) + .map(|(filters, text)| (filters.iter().map(ToString::to_string).collect(), text)) + } + + fn filters(filters: &[&str], text: &str) -> Option<(Vec, String)> { + Some(( + filters.iter().map(|f| f.to_string()).collect(), + text.to_string(), + )) + } + + #[test] + fn split_filters_while_typing() { + // the last word may still be typed + assert_eq!(split("foo type:q", false), None); + assert_eq!(split("type:qemu b", false), filters(&["type:qemu"], "b")); + assert_eq!( + split("foo type:qemu ", false), + filters(&["type:qemu"], "foo ") + ); + assert_eq!( + split("foo +bar status:running baz", false), + filters(&["status:running"], "foo +bar baz"), + ); + // plain words are kept as typed + assert_eq!(split("foo bar ", false), None); + } + + #[test] + fn split_filters_complete() { + assert_eq!( + split("foo +type:qemu", true), + filters(&["+type:qemu"], "foo") + ); + assert_eq!( + split("type:qemu foo +status:running", true), + filters(&["type:qemu", "+status:running"], "foo"), + ); + // terms without a category + assert_eq!(split(":bar cat: +", true), None); + } +} -- 2.47.3