Skip to main content

rok_ui/query/
key.rs

1//! Hierarchical query keys.
2
3use std::{fmt, sync::Arc};
4
5use gpui::SharedString;
6
7/// Identifies cached data: a list of parts, such as `["notes", "3"]`.
8///
9/// Keys are hierarchical: [`invalidate`](super::invalidate) with `["notes"]` affects every key
10/// that starts with it (`["notes", "3"]`, `["notes", "list", ..]`). Build keys with
11/// [`query_key!`](crate::query_key):
12///
13/// ```
14/// use rok_ui::query_key;
15///
16/// let list = query_key!["notes", "list", 2];
17/// assert!(list.starts_with(&query_key!["notes"]));
18/// assert_eq!(list.to_string(), "notes/list/2");
19/// ```
20#[derive(Clone, PartialEq, Eq, Hash, Default)]
21pub struct QueryKey(Arc<[SharedString]>);
22
23impl QueryKey {
24    /// A key from its parts.
25    #[must_use]
26    pub fn from_parts(parts: Vec<SharedString>) -> Self {
27        Self(parts.into())
28    }
29
30    /// The empty key. It is a prefix of every key, so invalidating it invalidates everything.
31    #[must_use]
32    pub fn root() -> Self {
33        Self::default()
34    }
35
36    /// The parts, outermost first.
37    #[must_use]
38    pub fn parts(&self) -> &[SharedString] {
39        &self.0
40    }
41
42    /// Whether `prefix`'s parts are the first parts of this key.
43    #[must_use]
44    pub fn starts_with(&self, prefix: &QueryKey) -> bool {
45        self.0.starts_with(&prefix.0)
46    }
47
48    /// This key with one more part.
49    #[must_use]
50    pub fn child(&self, part: &impl fmt::Debug) -> Self {
51        let mut parts = self.0.to_vec();
52        parts.push(key_part(part));
53        Self(parts.into())
54    }
55}
56
57impl fmt::Display for QueryKey {
58    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
59        for (index, part) in self.0.iter().enumerate() {
60            if index > 0 {
61                formatter.write_str("/")?;
62            }
63            formatter.write_str(part)?;
64        }
65        Ok(())
66    }
67}
68
69impl fmt::Debug for QueryKey {
70    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
71        formatter.debug_list().entries(self.0.iter()).finish()
72    }
73}
74
75/// One key part: the value's `Debug` text, without the quotes strings get.
76#[doc(hidden)]
77pub fn key_part(value: &impl fmt::Debug) -> SharedString {
78    let text = format!("{value:?}");
79    match text
80        .strip_prefix('"')
81        .and_then(|rest| rest.strip_suffix('"'))
82    {
83        Some(inner) => inner.to_string().into(),
84        None => text.into(),
85    }
86}
87
88/// Build a [`QueryKey`](crate::query::QueryKey) from parts. Any `Debug` value is a part:
89/// strings, numbers, ids and search structs.
90///
91/// ```
92/// # use rok_ui::query_key;
93/// let id = 7_u64;
94/// assert_eq!(query_key!["notes", id].to_string(), "notes/7");
95/// ```
96#[macro_export]
97macro_rules! query_key {
98    [$($part:expr),* $(,)?] => {
99        $crate::query::QueryKey::from_parts(::std::vec![$($crate::query::key::key_part(&$part)),*])
100    };
101}