Skip to main content

tilo_resource/resource/
search_entry.rs

1//! What an app offers to search: an entry, the weights its fields rank by
2//! and the prose it is read for.
3
4use std::sync::Arc;
5
6use crate::search_index::{IndexKind, IndexPerson};
7use crate::search_preview::SearchPreview;
8
9use super::{SearchRow, scope_contains};
10
11/// A search index entry. `anchor` addresses what a hit opens (an item id);
12/// `action`, when set, is the published action a hit invokes, so choosing it
13/// goes through the same API, permissions and history as the palette.
14///
15/// How a hit reads is the entry's too: the result group it is listed under
16/// (the resource's label unless `group` names another, such as "Timeline
17/// markers"), a dimmer `subtitle` line, a named `icon` (a lucide kebab name,
18/// `"star"`), and a `boost` that floats pinned or recent items over an equal
19/// match. Long prose an entry is found by — a book's chapter, a long note —
20/// is its `body`, which the index reads in place rather than the entry
21/// copying it, and whose segments may each be a hit of their own.
22// `Clone` and `PartialEq` are written out: derived, they are inlined into
23// every app that copies or compares an entry.
24#[derive(Debug, Default, Eq)]
25pub struct SearchEntry {
26    /// The containing resource scope for a flat anchor.
27    pub within: Option<String>,
28    /// Presentation for the platform-rendered result row.
29    pub row: Option<SearchRow>,
30    pub anchor: Option<String>,
31    pub title: String,
32    pub text: String,
33    pub action: Option<tilo_actions::ActionAddress>,
34    pub group: Option<String>,
35    pub subtitle: Option<String>,
36    pub icon: Option<String>,
37    /// What kind of thing it is, where the shell's generic rows would read
38    /// poorly: an agent, a conversation, a message.
39    pub kind: Option<IndexKind>,
40    /// Who the row shows, in the order people read them: the first is its
41    /// avatar, the rest its faces.
42    pub people: Vec<IndexPerson>,
43    /// Where it is, for a message: the conversation it sits in.
44    pub place: Option<IndexPerson>,
45    /// When it happened, in seconds since the Unix epoch.
46    pub when: Option<i64>,
47    /// What the palette shows of the hit while a person is on it; `None`
48    /// shows its `text`, and an entry with neither shows no preview.
49    pub preview: Option<SearchPreview>,
50    pub boost: i32,
51    pub body: Option<SearchBody>,
52    /// More short text the entry is found by, each ranked by its own
53    /// weight: a sender's address, a book's subject, a message's labels.
54    pub fields: Vec<(String, SearchWeight)>,
55    /// Structured filter values: token key, localized group label, value.
56    pub facets: Vec<(String, String, String)>,
57    /// The entry describes a secret (a vault's login): the system index
58    /// keeps its metadata but finds it only while the app reports its
59    /// secrets unlocked ([`SearchEntry::secret_bearing`]).
60    pub secret: bool,
61    /// The picture the entry is about, as its address in the content store:
62    /// what the system's image analysis reads, so the picture is found by the
63    /// words in it and by what it shows.
64    pub picture: Option<String>,
65}
66
67impl Clone for SearchEntry {
68    fn clone(&self) -> Self {
69        Self {
70            within: self.within.clone(),
71            row: self.row.clone(),
72            anchor: self.anchor.clone(),
73            title: self.title.clone(),
74            text: self.text.clone(),
75            action: self.action.clone(),
76            group: self.group.clone(),
77            subtitle: self.subtitle.clone(),
78            icon: self.icon.clone(),
79            kind: self.kind,
80            people: self.people.clone(),
81            place: self.place.clone(),
82            when: self.when,
83            preview: self.preview.clone(),
84            boost: self.boost,
85            body: self.body.clone(),
86            fields: self.fields.clone(),
87            facets: self.facets.clone(),
88            secret: self.secret,
89            picture: self.picture.clone(),
90        }
91    }
92}
93
94impl PartialEq for SearchEntry {
95    fn eq(&self, other: &Self) -> bool {
96        self.within == other.within
97            && self.row == other.row
98            && self.anchor == other.anchor
99            && self.title == other.title
100            && self.text == other.text
101            && self.action == other.action
102            && self.group == other.group
103            && self.subtitle == other.subtitle
104            && self.icon == other.icon
105            && self.kind == other.kind
106            && self.people == other.people
107            && self.place == other.place
108            && self.when == other.when
109            && self.preview == other.preview
110            && self.boost == other.boost
111            && self.body == other.body
112            && self.fields == other.fields
113            && self.facets == other.facets
114            && self.secret == other.secret
115            && self.picture == other.picture
116    }
117}
118
119/// How much a match in one of a [`SearchEntry`]'s fields counts. The title
120/// ranks as [`Self::Title`], the subtitle as [`Self::Subtitle`] and the text
121/// as [`Self::Body`]; [`SearchEntry::field`] adds others.
122#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
123pub enum SearchWeight {
124    /// The name a person looks for.
125    Title,
126    /// A stable identity typed verbatim: an address, an id, a path.
127    Identity,
128    /// A secondary line: an author, a sender, a folder.
129    Subtitle,
130    /// Other short fields: labels, tags, a subject.
131    Metadata,
132    /// Long prose.
133    Body,
134    /// Found, but never reorders hits.
135    Unranked,
136}
137
138/// One run of a [`SearchText`] segment: styled text, say.
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub struct SearchPiece<'a> {
141    pub text: &'a str,
142    /// Whether a word break separates this piece from the text before it.
143    pub space_before: bool,
144}
145
146/// Long text a search entry is found by, owned by the app: the index reads
147/// it while indexing and never copies it. It is a sequence of segments (the
148/// unit a hit can point at: a paragraph, a block), each a sequence of
149/// pieces. It must not change once handed to an entry; changed prose is a
150/// new body.
151pub trait SearchText: Send + Sync {
152    fn segment_count(&self) -> usize;
153
154    fn piece_count(&self, segment: usize) -> usize;
155
156    fn piece(&self, segment: usize, piece: usize) -> Option<SearchPiece<'_>>;
157
158    /// Whether a match in `segment` is a hit of its own ([`Self::location`])
159    /// rather than the entry's.
160    fn locates(&self, segment: usize) -> bool {
161        let _ = segment;
162        false
163    }
164
165    /// The hit a match in `segment` is — a reading location, invoking the
166    /// action that opens the text there — when [`Self::locates`] says so.
167    fn location(&self, segment: usize) -> Option<SearchEntry> {
168        let _ = segment;
169        None
170    }
171}
172
173/// A [`SearchText`] an entry carries. Cloning one is cheap, and two bodies
174/// are the same body only when they share one text, so an app that rebuilds
175/// its entries over mostly unchanged prose keeps its bodies and hands the
176/// same ones back.
177#[derive(Clone)]
178pub struct SearchBody(Arc<dyn SearchText>);
179
180impl SearchBody {
181    #[must_use]
182    pub fn new(text: Arc<dyn SearchText>) -> Self {
183        Self(text)
184    }
185
186    #[must_use]
187    pub fn text(&self) -> &dyn SearchText {
188        self.0.as_ref()
189    }
190
191    /// The shared text, for an index that reads it later.
192    #[must_use]
193    pub fn shared(&self) -> Arc<dyn SearchText> {
194        Arc::clone(&self.0)
195    }
196}
197
198impl PartialEq for SearchBody {
199    fn eq(&self, other: &Self) -> bool {
200        Arc::ptr_eq(&self.0, &other.0)
201    }
202}
203
204impl Eq for SearchBody {}
205
206impl std::fmt::Debug for SearchBody {
207    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208        formatter
209            .debug_struct("SearchBody")
210            .field("segments", &self.0.segment_count())
211            .finish()
212    }
213}
214
215impl SearchEntry {
216    /// Offer this entry under one value of a platform search facet.
217    #[must_use]
218    pub fn facet(
219        mut self,
220        key: impl Into<String>,
221        label: impl Into<String>,
222        value: impl Into<String>,
223    ) -> Self {
224        self.facets.push((key.into(), label.into(), value.into()));
225        self
226    }
227
228    /// Whether the entry lies in `scope`: its anchor, or the scope it is
229    /// [`within`](Self::within), is the scope or lies beneath it.
230    #[must_use]
231    pub fn in_scope(&self, scope: &str) -> bool {
232        [self.within.as_deref(), self.anchor.as_deref()]
233            .into_iter()
234            .flatten()
235            .any(|anchor| scope_contains(scope, anchor))
236    }
237
238    /// An entry titled `title` whose body text is `text`.
239    pub fn new(title: impl Into<String>, text: impl Into<String>) -> Self {
240        Self::titled(title.into(), text.into())
241    }
242
243    #[inline(never)]
244    fn titled(title: String, text: String) -> Self {
245        Self {
246            title,
247            text,
248            ..Self::default()
249        }
250    }
251
252    /// List the hit inside the scope `scope` (an item's anchor) though its
253    /// own anchor lies elsewhere: an article in its feed's scope, related by
254    /// a field rather than by nesting.
255    #[must_use]
256    pub fn inside(mut self, scope: impl Into<String>) -> Self {
257        self.within = Some(scope.into());
258        self
259    }
260
261    /// The item a hit opens.
262    #[must_use]
263    pub fn anchored(mut self, anchor: impl Into<String>) -> Self {
264        self.anchor = Some(anchor.into());
265        self
266    }
267
268    /// The published action a hit invokes.
269    #[must_use]
270    pub fn invoking(mut self, action: tilo_actions::ActionAddress) -> Self {
271        self.action = Some(action);
272        self
273    }
274
275    /// Anchored at the live row `row`, opened by running `effect`, the
276    /// view effect that row offers (go to a bookmark, show a find match):
277    /// for a hit whose row is the window's own state rather than an item
278    /// of the record.
279    #[must_use]
280    pub fn opening<E: crate::Effect>(mut self, row: impl Into<String>, effect: &E) -> Self {
281        let row = row.into();
282        self.action = Some(tilo_actions::ActionAddress::new(row.clone(), effect.id()));
283        self.anchor = Some(row);
284        self
285    }
286
287    /// List hits under `group` rather than the resource's label.
288    #[must_use]
289    pub fn grouped(mut self, group: impl Into<String>) -> Self {
290        self.group = Some(group.into());
291        self
292    }
293
294    /// A secondary line under the title: where the item is, what it is.
295    #[must_use]
296    pub fn subtitled(mut self, subtitle: impl Into<String>) -> Self {
297        self.subtitle = Some(subtitle.into());
298        self
299    }
300
301    /// The glyph a hit leads with, by its lucide kebab name (`"star"`).
302    #[must_use]
303    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
304        self.icon = Some(icon.into());
305        self
306    }
307
308    /// What kind of thing it is, where the shell's generic rows would read
309    /// poorly: an agent, a conversation, a message.
310    #[must_use]
311    pub fn of_kind(mut self, kind: IndexKind) -> Self {
312        self.kind = Some(kind);
313        self
314    }
315
316    /// Who the row shows, in the order people read them: the first is its
317    /// avatar, the rest its faces.
318    #[must_use]
319    pub fn showing(mut self, people: Vec<IndexPerson>) -> Self {
320        self.people = people;
321        self
322    }
323
324    /// Where it is, for a message: the conversation it sits in.
325    #[must_use]
326    pub fn in_place(mut self, place: IndexPerson) -> Self {
327        self.place = Some(place);
328        self
329    }
330
331    /// When it happened, in seconds since the Unix epoch.
332    #[must_use]
333    pub fn at(mut self, when: i64) -> Self {
334        self.when = Some(when);
335        self
336    }
337
338    /// What the palette shows of the hit while a person is on it, in place
339    /// of its text.
340    #[must_use]
341    pub fn previewed(mut self, preview: SearchPreview) -> Self {
342        self.preview = Some(preview);
343        self
344    }
345
346    /// Rank the hit `boost` above an equal match: a nudge, never an
347    /// override of how well it matches.
348    #[must_use]
349    pub fn boosted(mut self, boost: i32) -> Self {
350        self.boost = boost;
351        self
352    }
353
354    /// Find the entry by `text` too, a match in it ranked as `weight`.
355    #[must_use]
356    pub fn field(mut self, text: impl Into<String>, weight: SearchWeight) -> Self {
357        let text = text.into();
358        if !text.trim().is_empty() {
359            self.fields.push((text, weight));
360        }
361        self
362    }
363
364    /// Find the entry by `body` too, read in place.
365    #[must_use]
366    pub fn with_body(mut self, body: SearchBody) -> Self {
367        self.body = Some(body);
368        self
369    }
370
371    /// Mark the entry as describing a secret. The app publishes metadata
372    /// only (a name, a username, a site, never the secret), and the
373    /// system's search finds the entry only while the app reports its
374    /// secrets unlocked; while they are locked a match offers to unlock
375    /// the app instead.
376    #[must_use]
377    pub fn secret_bearing(mut self) -> Self {
378        self.secret = true;
379        self
380    }
381}