Skip to main content

tilo_actions/
send_to.rs

1//! Who a message sent from a window goes to: a person, an agent the workspace keeps, an agent the
2//! send makes, a conversation, or the one place a report goes.
3//!
4//! It is an action argument ([`crate::Recipient`] travels in a typed effect's parameters), so it
5//! lives with the other argument values an app publishes, and the window that shows the chip and
6//! the shell that delivers the message read the one definition.
7
8use serde::{Deserialize, Serialize};
9
10/// What a recipient of a sent message is: someone the search found, or the agent the person is
11/// making by sending.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
13#[serde(rename_all = "kebab-case")]
14pub enum RecipientKind {
15    /// An agent this send makes, kept by the person sending.
16    NewAgent,
17    /// An agent the workspace keeps and the search found.
18    Agent,
19    /// A person the workspace knows, by their root identity.
20    Person,
21    /// A conversation, opened where it is and posted in.
22    Conversation,
23    /// The one place a report about Tilo itself goes, which the session names
24    /// when it opens the box there: the search never finds it, and it never
25    /// sits beside another recipient.
26    Feedback,
27}
28
29impl RecipientKind {
30    /// The word a row of the box shows for it, when it needs one.
31    #[must_use]
32    pub fn label(self) -> &'static str {
33        match self {
34            Self::NewAgent => "New agent",
35            Self::Agent => "Agent",
36            Self::Person => "Person",
37            Self::Conversation => "Conversation",
38            Self::Feedback => "Feedback",
39        }
40    }
41}
42
43/// One recipient of a message sent from a window: who it goes to, and what the person reads on its
44/// chip.
45#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
46pub struct Recipient {
47    pub kind: RecipientKind,
48    /// The agent's id, the person's root identity or the conversation's id; empty for
49    /// [`RecipientKind::NewAgent`], which the shell makes.
50    #[serde(default, skip_serializing_if = "String::is_empty")]
51    pub id: String,
52    /// The name the chip shows: the agent's or the person's, the conversation's, or the name the new
53    /// agent takes — empty for a new agent nobody named, which the shell names by what it is asked.
54    pub name: String,
55    /// A line under the name in the search's rows (who keeps an agent, who
56    /// is in a conversation); never on the chip.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub detail: Option<String>,
59}
60
61impl Recipient {
62    /// The agent this send makes, named `name`.
63    #[must_use]
64    pub fn new_agent(name: impl Into<String>) -> Self {
65        Self {
66            kind: RecipientKind::NewAgent,
67            id: String::new(),
68            name: name.into(),
69            detail: None,
70        }
71    }
72
73    /// Someone or something the search found.
74    #[must_use]
75    pub fn found(kind: RecipientKind, id: impl Into<String>, name: impl Into<String>) -> Self {
76        Self {
77            kind,
78            id: id.into(),
79            name: name.into(),
80            detail: None,
81        }
82    }
83
84    /// The same recipient with a line under its name.
85    #[must_use]
86    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
87        let detail = detail.into();
88        self.detail = (!detail.trim().is_empty()).then_some(detail);
89        self
90    }
91}
92
93/// The recipients of `all` that `query` names, best first: what is called exactly that, then what
94/// a name starts with it, then a word of a name, then the conversations whose people hold it, then
95/// the rest. Among equals `all`'s own order (the most recent first) stands. An empty `query` names
96/// none.
97#[must_use]
98pub fn recipients_matching(all: &[Recipient], query: &str) -> Vec<Recipient> {
99    let needle = query.trim().to_lowercase();
100    let rank = |recipient: &Recipient| {
101        let name = recipient.name.to_lowercase();
102        if name == needle {
103            return Some(4);
104        }
105        if name.starts_with(&needle) {
106            return Some(3);
107        }
108        if name
109            .split(|c: char| !c.is_alphanumeric())
110            .any(|word| word.starts_with(&needle))
111        {
112            return Some(2);
113        }
114        let detail = recipient
115            .detail
116            .as_deref()
117            .unwrap_or_default()
118            .to_lowercase();
119        needle
120            .split_whitespace()
121            .all(|word| name.contains(word) || detail.contains(word))
122            .then_some(u8::from(recipient.kind == RecipientKind::Conversation))
123    };
124    if needle.is_empty() {
125        return Vec::new();
126    }
127    let mut found: Vec<(u8, &Recipient)> = all
128        .iter()
129        .filter_map(|recipient| Some((rank(recipient)?, recipient)))
130        .collect();
131    found.sort_by_key(|(rank, _)| std::cmp::Reverse(*rank));
132    found
133        .into_iter()
134        .take(12)
135        .map(|(_, recipient)| recipient.clone())
136        .collect()
137}