forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

links.rs80 lines, 2.6 KiBHistoryRawDownload
1//! Note links: `/notes/<id>` and `/notes/by-title/<title>` hrefs, and percent encoding.
2
3use loro::{LoroDoc, TextDelta};
4
5use crate::tree::value_str;
6
7/// A link to another note: by id (`/notes/<id>`) or by title (`/notes/by-title/<title>`).
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub enum LinkTarget {
10 Id(String),
11 Title(String),
12}
13
14/// Every note the doc links to, each target once, in document order. Hrefs that are
15/// not note links are ignored.
16pub fn note_links(doc: &LoroDoc) -> Vec<LinkTarget> {
17 links_in(&crate::flat::body(doc).to_delta())
18}
19
20/// [`note_links`] of a body already read.
21pub fn links_in(delta: &[TextDelta]) -> Vec<LinkTarget> {
22 let mut out = Vec::new();
23 for delta in delta {
24 let TextDelta::Insert { attributes: Some(attrs), .. } = delta else { continue };
25 let Some(href) = attrs.get("link").and_then(|link| link.get_by_key("href")).and_then(value_str) else {
26 continue;
27 };
28 if let Some(target) = link_target(&href)
29 && !out.contains(&target)
30 {
31 out.push(target);
32 }
33 }
34 out
35}
36
37/// The note an href points at, when it is a note link.
38pub fn link_target(href: &str) -> Option<LinkTarget> {
39 let rest = href.strip_prefix("/notes/")?;
40 if let Some(encoded) = rest.strip_prefix("by-title/") {
41 let title = percent_decode(encoded);
42 return (!title.trim().is_empty()).then_some(LinkTarget::Title(title));
43 }
44 let is_id = !rest.is_empty() && !rest.contains(['/', '?', '#']);
45 is_id.then(|| LinkTarget::Id(rest.to_owned()))
46}
47
48/// Percent-encodes everything except RFC 3986 unreserved characters.
49pub fn percent_encode(s: &str) -> String {
50 let mut out = String::with_capacity(s.len());
51 for b in s.bytes() {
52 match b {
53 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
54 out.push(b as char)
55 }
56 _ => out.push_str(&format!("%{b:02X}")),
57 }
58 }
59 out
60}
61
62/// Decodes `%XX` escapes. Malformed escapes are kept as they are.
63pub fn percent_decode(s: &str) -> String {
64 let bytes = s.as_bytes();
65 let mut out = Vec::with_capacity(bytes.len());
66 let mut i = 0;
67 while i < bytes.len() {
68 if bytes[i] == b'%' && i + 2 < bytes.len() {
69 let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok();
70 if let Some(v) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
71 out.push(v);
72 i += 3;
73 continue;
74 }
75 }
76 out.push(bytes[i]);
77 i += 1;
78 }
79 String::from_utf8_lossy(&out).into_owned()
80}