Skip to main content

jump_core/
web.rs

1// Copyright 2026 entro314-labs
2// SPDX-License-Identifier: MPL-2.0
3
4//! Web links: quicklinks and fallback searches.
5//!
6//! Both are the same mechanism — a named URL template with a `{query}` hole —
7//! used two ways. A **quicklink** carries a keyword and claims the query the
8//! way a plugin keyword does: `yt cats` opens a YouTube search and nothing
9//! else answers. A **fallback** has no keyword; the frontend appends fallbacks
10//! below the results of an ordinary search, so a query that matched little
11//! still ends somewhere useful.
12//!
13//! Templates come from the user's own configuration, so any scheme `xdg-open`
14//! understands is allowed — `https:` mostly, but a `zotero:` or `obsidian:`
15//! template is deliberate, not an accident to filter out.
16
17use std::process::Stdio;
18
19use serde::{Deserialize, Serialize};
20
21use tokio::process::Command;
22
23/// A named URL template. `{query}` is replaced with the percent-encoded query.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct Link {
26    /// Display name — "YouTube", "Wikipedia".
27    pub name: String,
28    /// Word that claims the query. Empty for fallbacks, which are not
29    /// addressed but appended.
30    #[serde(default)]
31    pub keyword: String,
32    /// URL with an optional `{query}` placeholder.
33    pub template: String,
34}
35
36impl Link {
37    /// Whether this link's keyword claims `query`, and the text after it.
38    ///
39    /// Same word-boundary rule as plugin keywords: the keyword must be
40    /// followed by a space or end the query, so `youtube` is not read as a
41    /// `yt` quicklink plus `outube`.
42    #[must_use]
43    pub fn match_query<'a>(&self, query: &'a str) -> Option<&'a str> {
44        if self.keyword.is_empty() {
45            return None;
46        }
47        let rest = query.strip_prefix(self.keyword.as_str())?;
48        match rest.strip_prefix(' ') {
49            Some(rest) => Some(rest.trim_start()),
50            None if rest.is_empty() => Some(""),
51            None => None,
52        }
53    }
54
55    /// The template with `{query}` filled in.
56    #[must_use]
57    pub fn url_for(&self, query: &str) -> String {
58        self.template.replace("{query}", &encode_component(query))
59    }
60}
61
62/// Percent-encode `text` for use inside one URL component.
63///
64/// Everything outside RFC 3986's unreserved set is encoded, spaces included —
65/// query strings are where this lands, and `+` for space is a convention some
66/// engines do not share, while `%20` is understood by all of them.
67#[must_use]
68pub fn encode_component(text: &str) -> String {
69    let mut encoded = String::with_capacity(text.len());
70    for byte in text.bytes() {
71        match byte {
72            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
73                encoded.push(byte as char);
74            }
75            _ => {
76                // Uppercase hex is the RFC 3986 normal form.
77                encoded.push('%');
78                encoded.push(
79                    char::from_digit(u32::from(byte >> 4), 16)
80                        .unwrap_or('0')
81                        .to_ascii_uppercase(),
82                );
83                encoded.push(
84                    char::from_digit(u32::from(byte & 0xf), 16)
85                        .unwrap_or('0')
86                        .to_ascii_uppercase(),
87                );
88            }
89        }
90    }
91    encoded
92}
93
94/// Open `url` with the user's default handler, detached from the caller.
95pub fn open(url: &str) {
96    let result = Command::new("xdg-open")
97        .arg(url)
98        .stdin(Stdio::null())
99        .stdout(Stdio::null())
100        .stderr(Stdio::null())
101        .spawn();
102
103    match result {
104        Ok(mut child) => {
105            tokio::spawn(async move {
106                let _ = child.wait().await;
107            });
108        }
109        Err(error) => tracing::error!(%error, url, "could not open URL"),
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    fn link(keyword: &str, template: &str) -> Link {
118        Link {
119            name: "Test".to_owned(),
120            keyword: keyword.to_owned(),
121            template: template.to_owned(),
122        }
123    }
124
125    #[test]
126    fn keyword_claims_with_word_boundary() {
127        let yt = link("yt", "https://youtube.com/results?search_query={query}");
128        assert_eq!(yt.match_query("yt cats"), Some("cats"));
129        assert_eq!(yt.match_query("yt"), Some(""));
130        assert_eq!(yt.match_query("youtube"), None);
131        assert_eq!(yt.match_query("firefox"), None);
132    }
133
134    #[test]
135    fn fallbacks_have_no_keyword_and_claim_nothing() {
136        let ddg = link("", "https://duckduckgo.com/?q={query}");
137        assert_eq!(ddg.match_query("anything"), None);
138    }
139
140    #[test]
141    fn query_is_encoded_into_the_template() {
142        let ddg = link("", "https://duckduckgo.com/?q={query}");
143        assert_eq!(
144            ddg.url_for("caffè & crème"),
145            "https://duckduckgo.com/?q=caff%C3%A8%20%26%20cr%C3%A8me"
146        );
147    }
148
149    #[test]
150    fn template_without_placeholder_is_left_alone() {
151        let home = link("home", "https://example.com/dashboard");
152        assert_eq!(home.url_for("ignored"), "https://example.com/dashboard");
153    }
154
155    #[test]
156    fn unreserved_characters_pass_through() {
157        assert_eq!(encode_component("abc-XYZ_0.9~"), "abc-XYZ_0.9~");
158        assert_eq!(encode_component("a/b?c=d"), "a%2Fb%3Fc%3Dd");
159    }
160}