Lines
100 %
Functions
50 %
Branches
//! The suggestions of a cell and what a pick writes.
use serde::Deserialize;
/// Either a shared form option or a tag suggestion (`name` stands for the
/// label).
#[derive(Deserialize)]
struct Wire {
id: Option<String>,
label: Option<String>,
alias: Option<String>,
path: Option<String>,
commodity: Option<String>,
name: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct Item {
pub(super) id: Option<String>,
pub(super) label: String,
pub(super) alias: Option<String>,
pub(super) path: Option<String>,
pub(super) commodity: Option<String>,
impl Item {
fn from_wire(wire: Wire) -> Option<Self> {
let label = wire.label.or_else(|| wire.name.clone())?;
Some(Self {
id: wire.id,
label,
alias: wire.alias,
path: wire.path,
commodity: wire.commodity,
})
/// `query` is lowercase.
pub(super) fn matches(&self, query: &str) -> bool {
let has = |text: &str| text.to_lowercase().contains(query);
has(&self.label)
|| [&self.path, &self.alias]
.into_iter()
.any(|text| text.as_deref().is_some_and(has))
/// The text shown beside the label: the whole path when it differs.
pub(super) fn context(&self) -> Option<&str> {
self.path.as_deref().filter(|path| *path != self.label)
pub(super) fn parse_items(body: &str) -> Result<Vec<Item>, serde_json::Error> {
let wires: Vec<Wire> = serde_json::from_str(body)?;
Ok(wires.into_iter().filter_map(Item::from_wire).collect())
/// The id of the one option whose label is exactly `text`.
pub(super) fn labelled_id<'a>(items: &'a [Item], text: &str) -> Option<&'a str> {
let text = text.trim();
let mut found = items.iter().filter(|item| item.label == text);
match (found.next(), found.next()) {
(Some(only), None) => only.id.as_deref(),
_ => None,
/// The id of the option `text` names: its id, else its alias or label. A step matching several options leaves the text unresolved.
pub(super) fn resolve_id<'a>(items: &'a [Item], text: &str) -> Option<&'a str> {
let named = |name: &str| name.eq_ignore_ascii_case(text);
let steps: [&dyn Fn(&Item) -> bool; 2] = [&|item| item.id.as_deref() == Some(text), &|item| {
item.alias.as_deref().is_some_and(named) || named(&item.label)
}];
for matches in steps {
let mut found = items.iter().filter(|item| matches(item));
(Some(only), None) => return only.id.as_deref(),
(Some(_), Some(_)) => return None,
_ => {}
None