use gpui::{App, SharedString};
use super::{location, navigate, replace, Location};
pub trait Search: Clone + PartialEq + 'static {
const FIELDS: &'static [&'static str];
fn defaults() -> Self;
fn from_query(pairs: &[(SharedString, SharedString)]) -> Self;
fn to_query(&self) -> Vec<(String, String)>;
#[must_use]
fn from_location(location: &Location) -> Self {
Self::from_query(location.query_pairs())
}
}
pub fn use_search<S: Search>(cx: &mut App) -> S {
S::from_location(&location(cx))
}
pub fn update_search<S: Search>(cx: &mut App, update: impl FnOnce(&mut S)) {
if let Some(target) = updated_location::<S>(cx, update) {
navigate(target, cx);
}
}
pub fn replace_search<S: Search>(cx: &mut App, update: impl FnOnce(&mut S)) {
if let Some(target) = updated_location::<S>(cx, update) {
replace(target, cx);
}
}
fn updated_location<S: Search>(cx: &mut App, update: impl FnOnce(&mut S)) -> Option<String> {
let current = location(cx);
let before = S::from_location(¤t);
let mut after = before.clone();
update(&mut after);
if after == before {
return None;
}
let mut pairs: Vec<(String, String)> = current
.query_pairs()
.iter()
.filter(|(key, _)| !S::FIELDS.contains(&key.as_ref()))
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect();
pairs.extend(after.to_query());
Some(Location::build(current.path(), &pairs))
}
#[doc(hidden)]
#[must_use]
pub fn parse_value<T: std::str::FromStr>(
pairs: &[(SharedString, SharedString)],
key: &str,
) -> Option<T> {
pairs
.iter()
.find(|(name, _)| name.as_ref() == key)
.and_then(|(_, value)| value.parse().ok())
}