* [PATCH datacenter-manager v2 0/3] ui: search: improve filter UX
@ 2026-12-01 15:45 Dominik Csapak
2026-12-01 15:45 ` [PATCH datacenter-manager v2 1/3] pdm-search: keep the order of the search terms Dominik Csapak
` (2 more replies)
0 siblings, 3 replies; 4+ messages in thread
From: Dominik Csapak @ 2026-12-01 15:45 UTC (permalink / raw)
To: pdm-devel
By doing two things:
* show the applied category filters as 'chips' that can be removed
easily
* show a 'filter add' panel above the search bar, so users
can easily discover which filter there are. also use the panel
to explain the search syntax and implications of required and optional
searches.
changes from v1:
* add the 'folder' category: its values are picked from the folders the
user can open, and like views, folder filters are always required,
since the server limits the results to the selected folder
* take the views for the filter panel from the view list context
instead of loading them separately
* create the submit callback for the filter panel only once, so the
panel isn't rendered again on every input in the search box
* match the category titles and value inputs on the parsed
SearchCategory, so a new category fails to compile instead of being
shown as an unknown one
* use Row/Column and the typed css helpers instead of class strings
Dominik Csapak (3):
pdm-search: keep the order of the search terms
ui: search box: show categorized search terms as chips
ui: search box: add a panel to add and edit search filters
lib/pdm-search/src/lib.rs | 62 ++--
ui/css/pdm.scss | 13 +
ui/src/widget/mod.rs | 1 +
ui/src/widget/search_box.rs | 420 ++++++++++++++++++++++----
ui/src/widget/search_filter_panel.rs | 427 +++++++++++++++++++++++++++
5 files changed, 835 insertions(+), 88 deletions(-)
create mode 100644 ui/src/widget/search_filter_panel.rs
--
2.47.3
^ permalink raw reply [flat|nested] 4+ messages in thread
* [PATCH datacenter-manager v2 1/3] pdm-search: keep the order of the search terms
2026-12-01 15:45 [PATCH datacenter-manager v2 0/3] ui: search: improve filter UX Dominik Csapak
@ 2026-12-01 15:45 ` Dominik Csapak
2026-12-01 15:45 ` [PATCH datacenter-manager v2 2/3] ui: search box: show categorized search terms as chips Dominik Csapak
2026-12-01 15:45 ` [PATCH datacenter-manager v2 3/3] ui: search box: add a panel to add and edit search filters Dominik Csapak
2 siblings, 0 replies; 4+ messages in thread
From: Dominik Csapak @ 2026-12-01 15:45 UTC (permalink / raw)
To: pdm-devel
and add `take_terms` to take out terms with an arbitrary filter.
Since the terms were stored split into required and optional ones,
serializing a search put all required terms first, regardless of the
order they were given in. Keep them in a single list instead, so the
UI can show and serialize the terms in the order they were entered.
`take_terms` generalizes `take_category`, so the UI can take out all
categorized terms of a search at once.
Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
---
lib/pdm-search/src/lib.rs | 62 ++++++++++++++++++++++++---------------
1 file changed, 38 insertions(+), 24 deletions(-)
diff --git a/lib/pdm-search/src/lib.rs b/lib/pdm-search/src/lib.rs
index 66a335bf..df35aa4c 100644
--- a/lib/pdm-search/src/lib.rs
+++ b/lib/pdm-search/src/lib.rs
@@ -6,17 +6,14 @@ use std::fmt;
#[derive(Default, Clone)]
pub struct Search {
- required_terms: Vec<SearchTerm>,
- optional_terms: Vec<SearchTerm>,
+ // in the given order, so that serializing it does not reorder the terms
+ terms: Vec<SearchTerm>,
}
impl FromIterator<SearchTerm> for Search {
fn from_iter<T: IntoIterator<Item = SearchTerm>>(iter: T) -> Self {
- let (optional_terms, required_terms) = iter.into_iter().partition(|term| term.optional);
-
Self {
- required_terms,
- optional_terms,
+ terms: iter.into_iter().collect(),
}
}
}
@@ -39,7 +36,7 @@ impl Search {
/// Returns true if no [`SearchTerm`] exist
pub fn is_empty(&self) -> bool {
- self.required_terms.is_empty() && self.optional_terms.is_empty()
+ self.terms.is_empty()
}
/// Create a new [`Search`] with the given [`SearchTerm`]s
@@ -56,13 +53,17 @@ impl Search {
return true;
}
- if self.required_terms.iter().map(&mut matches).any(|f| !f) {
+ let mut required = self.terms.iter().filter(|term| !term.is_optional());
+ if required.any(|term| !matches(term)) {
return false;
}
- if !self.optional_terms.is_empty()
- && self.optional_terms.iter().map(&mut matches).all(|f| !f)
- {
+ let mut optional = self
+ .terms
+ .iter()
+ .filter(|term| term.is_optional())
+ .peekable();
+ if optional.peek().is_some() && !optional.any(matches) {
return false;
}
@@ -71,31 +72,28 @@ impl Search {
/// Add a term to the search
pub fn add_term(&mut self, term: SearchTerm) {
- if term.is_optional() {
- self.optional_terms.push(term);
- } else {
- self.required_terms.push(term);
- }
+ self.terms.push(term);
+ }
+
+ /// Remove all [`SearchTerm`]s for which `filter` returns true and return them
+ pub fn take_terms<F: FnMut(&SearchTerm) -> bool>(&mut self, mut filter: F) -> Vec<SearchTerm> {
+ self.terms.extract_if(.., |term| filter(term)).collect()
}
/// Remove all [`SearchTerm`]s with the given category, ignoring ASCII case, and return them
pub fn take_category(&mut self, category: &str) -> Vec<SearchTerm> {
- let has_category = |term: &mut SearchTerm| {
+ self.take_terms(|term| {
term.category
.as_deref()
.is_some_and(|c| c.eq_ignore_ascii_case(category))
- };
-
- let mut terms: Vec<SearchTerm> = self.required_terms.extract_if(.., has_category).collect();
- terms.extend(self.optional_terms.extract_if(.., has_category));
- terms
+ })
}
}
impl fmt::Display for Search {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut sep = "";
- for term in self.required_terms.iter().chain(self.optional_terms.iter()) {
+ for term in &self.terms {
write!(f, "{sep}{term}")?;
sep = " ";
}
@@ -277,11 +275,27 @@ mod tests {
SearchTerm::new("b").optional(true).category(Some("View")),
]
);
- assert_eq!(search.to_string(), "+bar:view foo view:");
+ assert_eq!(search.to_string(), "foo +bar:view view:");
assert!(search.take_category("view").is_empty());
}
+ #[test]
+ fn take_terms_keeps_order() {
+ let mut search = Search::from("foo +type:qemu +bar status:running baz");
+
+ assert_eq!(
+ search.take_terms(|term| term.category.is_some()),
+ vec![
+ SearchTerm::new("qemu").category(Some("type")),
+ SearchTerm::new("running")
+ .optional(true)
+ .category(Some("status")),
+ ]
+ );
+ assert_eq!(search.to_string(), "foo +bar baz");
+ }
+
#[test]
fn test_display() {
let term = SearchTerm::new("foo");
--
2.47.3
^ permalink raw reply related [flat|nested] 4+ messages in thread
* [PATCH datacenter-manager v2 2/3] ui: search box: show categorized search terms as chips
2026-12-01 15:45 [PATCH datacenter-manager v2 0/3] ui: search: improve filter UX Dominik Csapak
2026-12-01 15:45 ` [PATCH datacenter-manager v2 1/3] pdm-search: keep the order of the search terms Dominik Csapak
@ 2026-12-01 15:45 ` Dominik Csapak
2026-12-01 15:45 ` [PATCH datacenter-manager v2 3/3] ui: search box: add a panel to add and edit search filters Dominik Csapak
2 siblings, 0 replies; 4+ messages in thread
From: Dominik Csapak @ 2026-12-01 15:45 UTC (permalink / raw)
To: pdm-devel
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 <d.csapak@proxmox.com>
---
ui/css/pdm.scss | 13 ++
ui/src/widget/search_box.rs | 335 ++++++++++++++++++++++++++++++------
2 files changed, 292 insertions(+), 56 deletions(-)
diff --git a/ui/css/pdm.scss b/ui/css/pdm.scss
index 3fcb87e5..cc86f554 100644
--- a/ui/css/pdm.scss
+++ b/ui/css/pdm.scss
@@ -262,6 +262,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..4ec5970f 100644
--- a/ui/src/widget/search_box.rs
+++ b/ui/src/widget/search_box.rs
@@ -2,20 +2,24 @@ 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::{AlignItems, ColorScheme},
+ dom::focus::FocusTracker,
prelude::*,
props::CssLength,
state::{SharedState, SharedStateObserver},
- widget::{Container, Trigger, form::Field},
+ widget::{Badge, Container, Fa, Input, MiniScroll, MiniScrollMode, Row, Trigger},
};
+use pdm_api_types::resource::SearchCategory;
+use pdm_search::{Search, SearchTerm};
+
use crate::search_provider::get_search_provider;
use super::ResourceTree;
@@ -36,22 +40,131 @@ impl From<SearchBox> for VNode {
}
}
+/// Returns the title of a search category, or `None` if the category is unknown.
+fn category_title(category: &str) -> Option<String> {
+ let title = match category.to_lowercase().as_str() {
+ // selected by the API itself, not categories of the resources
+ "view" => tr!("View"),
+ "folder" => tr!("Folder"),
+ category => match category.parse().ok()? {
+ SearchCategory::Type => tr!("Type"),
+ SearchCategory::RemoteType => tr!("Remote Type"),
+ SearchCategory::Remote => tr!("Remote"),
+ SearchCategory::Status => tr!("Status"),
+ SearchCategory::Template => tr!("Template"),
+ SearchCategory::Name => tr!("Name"),
+ SearchCategory::Id => tr!("ID"),
+ SearchCategory::Node => tr!("Node"),
+ SearchCategory::Pool => tr!("Pool"),
+ SearchCategory::Tag => tr!("Tag"),
+ SearchCategory::Property => tr!("Property"),
+ SearchCategory::NetworkType => tr!("Network Type"),
+ SearchCategory::HaState => tr!("HA State"),
+ SearchCategory::Lock => tr!("Lock"),
+ },
+ };
+ 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<SearchTerm>, 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<SearchTerm>,
+ text: String,
focus_tracker: FocusTracker,
focus: bool,
global_shortcut_listener: Closure<dyn Fn(KeyboardEvent)>,
toggle_focus: bool,
_observer: Option<SharedStateObserver<String>>,
- force_value: bool,
+}
+
+impl PdmSearchBox {
+ fn search_term(&self) -> String {
+ let mut terms: Vec<String> = 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<Self>, 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 +176,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<String>| {
- 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 +195,68 @@ impl Component for PdmSearchBox {
}
})),
_observer,
- force_value: false,
}
}
fn update(&mut self, _ctx: &Context<Self>, 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<Self>) -> 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 +265,73 @@ 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 = Row::new().class(AlignItems::Center).gap(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::<HtmlInputElement>().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 +339,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 +357,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 +364,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::<HtmlElement>() {
- let _ = el.focus();
- }
- }
+ } else if let Some(el) = self.input_ref.cast::<HtmlElement>() {
+ let _ = el.focus();
}
self.toggle_focus = false;
@@ -209,3 +384,51 @@ impl Component for PdmSearchBox {
};
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::split_filters;
+
+ fn split(text: &str, complete: bool) -> Option<(Vec<String>, 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>, 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
^ permalink raw reply related [flat|nested] 4+ messages in thread
* [PATCH datacenter-manager v2 3/3] ui: search box: add a panel to add and edit search filters
2026-12-01 15:45 [PATCH datacenter-manager v2 0/3] ui: search: improve filter UX Dominik Csapak
2026-12-01 15:45 ` [PATCH datacenter-manager v2 1/3] pdm-search: keep the order of the search terms Dominik Csapak
2026-12-01 15:45 ` [PATCH datacenter-manager v2 2/3] ui: search box: show categorized search terms as chips Dominik Csapak
@ 2026-12-01 15:45 ` Dominik Csapak
2 siblings, 0 replies; 4+ messages in thread
From: Dominik Csapak @ 2026-12-01 15:45 UTC (permalink / raw)
To: pdm-devel
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 <d.csapak@proxmox.com>
---
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<SearchBox> for VNode {
}
/// Returns the title of a search category, or `None` if the category is unknown.
-fn category_title(category: &str) -> Option<String> {
+pub(super) fn category_title(category: &str) -> Option<String> {
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<SearchTerm>,
text: String,
+ // the index of the filter edited in the panel, a new one is added if this is `None`
+ editing: Option<usize>,
+ // 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<dyn Fn(KeyboardEvent)>,
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<SearchTerm>,
_observer: Option<SharedStateObserver<String>>,
}
@@ -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::<HtmlInputElement>().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::<HtmlElement>() {
+ let _ = el.focus();
+ }
+ self.focus_input = false;
+ }
}
fn destroy(&mut self, _ctx: &Context<Self>) {
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<FilterInput> {
+ 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<SearchTerm>,
+}
+
+impl SearchFilterPanel {
+ pub fn new(
+ term: Option<(usize, SearchTerm)>,
+ on_submit: impl Into<Callback<SearchTerm>>,
+ ) -> Self {
+ Self {
+ term,
+ on_submit: on_submit.into(),
+ }
+ }
+}
+
+impl From<SearchFilterPanel> for VNode {
+ fn from(val: SearchFilterPanel) -> Self {
+ VComp::new::<PdmSearchFilterPanel>(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<Self>) -> 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::<ViewListContext>(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>) -> 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<Self>, 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<Self>, 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<Self>) -> 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::<HtmlInputElement>()
+ .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
^ permalink raw reply related [flat|nested] 4+ messages in thread
end of thread, other threads:[~2026-12-01 15:47 UTC | newest]
Thread overview: 4+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-01 15:45 [PATCH datacenter-manager v2 0/3] ui: search: improve filter UX Dominik Csapak
2026-12-01 15:45 ` [PATCH datacenter-manager v2 1/3] pdm-search: keep the order of the search terms Dominik Csapak
2026-12-01 15:45 ` [PATCH datacenter-manager v2 2/3] ui: search box: show categorized search terms as chips Dominik Csapak
2026-12-01 15:45 ` [PATCH datacenter-manager v2 3/3] ui: search box: add a panel to add and edit search filters Dominik Csapak
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.