Skip to main content

tilo_actions/tree/
names.rs

1//! The names a caller writes, read as what they mean: an app by any spelling a
2//! model writes for it, an action by the ids close to one nobody offers, a
3//! choice by the label a person reads, and a resource by the name a path
4//! writes for it.
5//!
6//! An app is named exactly by its id, by the last part of its id and by the name the listing
7//! shows it by. A model asked to work in the word processor writes `word-processor`,
8//! `word_processor`, `Word Processor`, `WordProcessor`, `Word` or `so.tilo.word_processor`, and
9//! each of those is that one app: a name is compared in lower case and without the hyphens,
10//! underscores and blanks that part its words, and the start of a name stands for it where one
11//! app alone begins so.
12//!
13//! A name is only ever read among the apps the caller was listed already, so reading it more
14//! freely finds no app a stricter spelling could not have named; what the caller may do with
15//! the app it finds is decided where it always was. A name that fits several apps equally well
16//! chooses none of them.
17
18use crate::ActionDescriptor;
19use serde_json::Value;
20
21/// What a bound UI resource's id starts with (ui-core's publication prefix).
22pub const BOUND_PREFIX: &str = "tilo-ui-bound:v1:";
23
24/// A name written into a path: `/`, `#` and `\` escaped.
25#[must_use]
26pub fn path_name(name: &str) -> String {
27    let mut written = String::with_capacity(name.len());
28    for character in name.chars() {
29        if matches!(character, '/' | '#' | '\\') {
30            written.push('\\');
31        }
32        written.push(character);
33    }
34    written
35}
36
37/// The logical id a bound UI resource's id carries in hex at its end
38/// (`tilo-ui-bound:v1:<publication>:<instance>:<hex>`): what the app calls
39/// the resource, which survives the publication the rest of the id names.
40#[must_use]
41pub fn bound_key(id: &str) -> Option<String> {
42    let hex = id.strip_prefix(BOUND_PREFIX)?;
43    let hex = hex.rsplit(':').next()?;
44    if hex.is_empty() || hex.len() % 2 != 0 {
45        return None;
46    }
47    let bytes = (0..hex.len())
48        .step_by(2)
49        .map(|at| u8::from_str_radix(hex.get(at..at.checked_add(2)?)?, 16).ok())
50        .collect::<Option<Vec<u8>>>()?;
51    String::from_utf8(bytes)
52        .ok()
53        .filter(|key| !key.is_empty() && !key.chars().any(char::is_control))
54}
55
56/// The fewest letters the start of a name stands for the name with.
57const START_CHARS: usize = 3;
58
59/// `name` as names are compared: in lower case, without the hyphens, underscores and blanks
60/// that part its words.
61#[must_use]
62pub fn folded(name: &str) -> String {
63    name.trim()
64        .chars()
65        .filter(|character| !matches!(character, '-' | '_' | ' '))
66        .flat_map(char::to_lowercase)
67        .collect()
68}
69
70/// The app `name` means among `apps`, each an id with the name the listing shows it by (empty
71/// where it shows none): the app whose id it is, else whose id ends in it, else that is listed
72/// by it, else the one whose name begins with it. `None` when it names none of them. A name
73/// with a dot in it is an id and is compared with ids whole.
74///
75/// # Errors
76/// `name` fits several apps equally well: they are named, and none is chosen.
77pub fn app_meant(name: &str, apps: &[(&str, &str)]) -> Result<Option<String>, String> {
78    let wanted = folded(name);
79    if wanted.is_empty() {
80        return Ok(None);
81    }
82    let dotted = wanted.contains('.');
83    let begins = wanted.chars().count() >= START_CHARS;
84    let last = |app_id: &str| folded(app_id.rsplit('.').next().unwrap_or(app_id));
85    let fits = |how: u8, app_id: &str, label: &str| match how {
86        0 => folded(app_id) == wanted,
87        1 => !dotted && last(app_id) == wanted,
88        2 => !dotted && !label.is_empty() && folded(label) == wanted,
89        _ => {
90            !dotted
91                && begins
92                && (last(app_id).starts_with(&wanted)
93                    || (!label.is_empty() && folded(label).starts_with(&wanted)))
94        }
95    };
96    for how in 0..4u8 {
97        let mut meant: Vec<&str> = Vec::new();
98        for &(app_id, label) in apps {
99            if fits(how, app_id, label) && !meant.contains(&app_id) {
100                meant.push(app_id);
101            }
102        }
103        match meant.as_slice() {
104            [] => {}
105            [one] => return Ok(Some((*one).to_owned())),
106            several => {
107                return Err(format!(
108                    "{name} names several apps: {}; name one",
109                    several.join(", ")
110                ));
111            }
112        }
113    }
114    Ok(None)
115}
116
117/// `arguments` with each parameter's value written as the label a person reads
118/// replaced by the value the app takes, whatever its case or spacing
119/// (`In review` for `in-review`, a status or a choice of a kind of thing alike).
120pub fn bind_choices(descriptor: &ActionDescriptor, arguments: &mut serde_json::Map<String, Value>) {
121    for param in &descriptor.params {
122        let Some(given) = arguments
123            .get(param.name.as_ref())
124            .and_then(Value::as_str)
125            .map(plain)
126        else {
127            continue;
128        };
129        let choice = param
130            .choices
131            .iter()
132            .find(|choice| plain(choice) == given)
133            .map(|choice| Value::String(choice.to_string()))
134            .or_else(|| {
135                forms(param.schema.as_deref()?)
136                    .into_iter()
137                    .find(|(name, _)| plain(name) == given)
138                    .map(|(_, value)| value)
139            });
140        if let Some(choice) = choice {
141            arguments.insert(param.name.to_string(), choice);
142        }
143    }
144}
145
146/// The action ids closest to `name`, best first, at most `limit`: those it is
147/// part of, one of whose words it is, or whose start it shares.
148#[must_use]
149pub fn close_matches(name: &str, ids: &[String], limit: usize) -> Vec<String> {
150    let lower = name.to_lowercase();
151    let mut scored: Vec<(u8, &String)> = ids
152        .iter()
153        .filter_map(|id| {
154            let named = id.to_lowercase();
155            let rank = if named.contains(&lower) {
156                0
157            } else if lower.contains(&named) {
158                1
159            } else if shared_start(&named, &lower) >= 3 {
160                2
161            } else {
162                return None;
163            };
164            Some((rank, id))
165        })
166        .collect();
167    scored.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(b.1)));
168    scored
169        .into_iter()
170        .take(limit)
171        .map(|(_, id)| id.clone())
172        .collect()
173}
174
175/// How many bytes the start of `a` and `b` share, to the last `-`.
176fn shared_start(a: &str, b: &str) -> usize {
177    let common = a
178        .bytes()
179        .zip(b.bytes())
180        .take_while(|(left, right)| left == right)
181        .count();
182    a.get(..common)
183        .and_then(|start| start.rfind('-'))
184        .unwrap_or(common)
185}
186
187/// `text` as a value is compared to a parameter's choices: its letters alone,
188/// in one case, so `In review`, `In Review` and `in-review` are one value.
189fn plain(text: &str) -> String {
190    text.chars()
191        .filter(char::is_ascii_alphanumeric)
192        .map(|character| character.to_ascii_lowercase())
193        .collect()
194}
195
196/// The values a parameter's schema offers as alternatives, each as the name a
197/// person reads it by and the value the app takes (`{"title": "In review",
198/// "const": "in-review"}`, or a one-field object with the constant).
199fn forms(schema: &Value) -> Vec<(String, Value)> {
200    let Some(alternatives) = schema
201        .get("anyOf")
202        .or_else(|| schema.get("oneOf"))
203        .and_then(Value::as_array)
204    else {
205        return Vec::new();
206    };
207    let mut forms = Vec::new();
208    for alternative in alternatives {
209        let Some(fields) = alternative.as_object() else {
210            continue;
211        };
212        let constant = fields.get("const").cloned().or_else(|| {
213            let only = fields.get("required")?.as_array()?.first()?.as_str()?;
214            fields.get("properties")?.get(only)?.get("const").cloned()
215        });
216        let name = fields
217            .get("title")
218            .and_then(Value::as_str)
219            .map(str::to_owned)
220            .or_else(|| constant.as_ref().and_then(Value::as_str).map(str::to_owned));
221        if let (Some(name), Some(constant)) = (name, constant) {
222            forms.push((name, constant));
223        }
224    }
225    forms
226}
227
228#[cfg(test)]
229mod tests {
230    use super::{app_meant, bound_key, close_matches, folded};
231    use crate::tree::CLOSE_MATCHES;
232
233    const APPS: &[(&str, &str)] = &[
234        ("so.tilo.word-processor", "Word Processor"),
235        ("so.tilo.notes", "Notes"),
236        ("so.tilo.tasks", "Tasks"),
237        ("so.tilo.file-explorer", "Files"),
238        ("so.tilo.video", "Video"),
239        ("so.tilo.video-editor", "Video Editor"),
240        ("so.tilo.word-processor", "Word Processor"),
241    ];
242
243    #[test]
244    fn a_name_is_its_app_in_every_spelling_a_model_writes() {
245        for spelled in [
246            "word-processor",
247            "word_processor",
248            "word processor",
249            "Word Processor",
250            "WordProcessor",
251            "WORD-PROCESSOR",
252            "Word",
253            " word_processor ",
254            "so.tilo.word-processor",
255            "so.tilo.word_processor",
256            "So.Tilo.Word-Processor",
257        ] {
258            assert_eq!(
259                app_meant(spelled, APPS),
260                Ok(Some("so.tilo.word-processor".to_owned())),
261                "{spelled}"
262            );
263        }
264        for spelled in [
265            "files",
266            "Files",
267            "file_explorer",
268            "File Explorer",
269            "FILE-EXPLORER",
270        ] {
271            assert_eq!(
272                app_meant(spelled, APPS),
273                Ok(Some("so.tilo.file-explorer".to_owned())),
274                "{spelled}"
275            );
276        }
277        assert_eq!(folded(" Word_Processor "), "wordprocessor");
278    }
279
280    #[test]
281    fn a_name_that_fits_several_apps_chooses_none_of_them() {
282        let several = app_meant("vid", APPS).expect_err("two apps begin so");
283        assert!(
284            several.contains("names several")
285                && several.contains("so.tilo.video")
286                && several.contains("so.tilo.video-editor"),
287            "{several}"
288        );
289        // A whole name is its app, whatever else begins with it.
290        let apps = [
291            ("so.tilo.notes", "Notes"),
292            ("so.tilo.notes-archive", "Notes Archive"),
293        ];
294        assert_eq!(
295            app_meant("Notes", &apps),
296            Ok(Some("so.tilo.notes".to_owned()))
297        );
298        assert!(app_meant("not", &apps).is_err());
299    }
300
301    #[test]
302    fn a_name_no_app_has_names_none() {
303        for spelled in [
304            "",
305            "  ",
306            "-",
307            "wo",
308            "window",
309            "processor",
310            "tilo",
311            "so.tilo",
312            "so.tilo.word",
313            "word.processor",
314            "tasks.tracker",
315        ] {
316            assert_eq!(app_meant(spelled, APPS), Ok(None), "{spelled}");
317        }
318    }
319
320    #[test]
321    fn an_action_no_resource_offers_names_at_most_five_close_matches() {
322        // An action nobody has is answered with what may have been meant, at most
323        // [`CLOSE_MATCHES`] of them, never the app's whole list.
324        let ids: Vec<String> = [
325            "mark-read",
326            "read-aloud",
327            "read",
328            "archive",
329            "reply",
330            "remove",
331            "rename",
332            "restore",
333            "reload",
334            "read-more",
335            "read-later",
336            "react",
337        ]
338        .into_iter()
339        .map(str::to_owned)
340        .collect();
341        let close = close_matches("read", &ids, CLOSE_MATCHES);
342        assert_eq!(close.len(), CLOSE_MATCHES, "{close:?}");
343        assert!(close.iter().all(|id| id.contains("read")), "{close:?}");
344        assert_eq!(close_matches("arch", &ids, CLOSE_MATCHES), ["archive"]);
345        assert!(close_matches("explode", &ids, CLOSE_MATCHES).is_empty());
346    }
347
348    #[test]
349    fn bound_ids_decode_to_the_apps_own_name_and_nothing_else_does() {
350        let key = "notes.notebook/page/Todo/body";
351        let bound = format!(
352            "tilo-ui-bound:v1:a:c0fe4ad7-b7d0-46c3-ab7e-78d12d5d86f4:{}",
353            hex::encode(key)
354        );
355        assert_eq!(bound_key(&bound).as_deref(), Some(key));
356        assert_eq!(bound_key("notes.notebook"), None);
357        assert_eq!(bound_key("tilo-ui-bound:v1:a:b:zz"), None);
358        assert_eq!(bound_key("tilo-ui-bound:v1:a:b:abc"), None);
359    }
360}