//! Note links: `/notes/` and `/notes/by-title/` hrefs, and percent encoding. use loro::{LoroDoc, TextDelta}; use crate::tree::value_str; /// A link to another note: by id (`/notes/<id>`) or by title (`/notes/by-title/<title>`). #[derive(Clone, Debug, PartialEq, Eq)] pub enum LinkTarget { Id(String), Title(String), } /// Every note the doc links to, each target once, in document order. Hrefs that are /// not note links are ignored. pub fn note_links(doc: &LoroDoc) -> Vec<LinkTarget> { links_in(&crate::flat::body(doc).to_delta()) } /// [`note_links`] of a body already read. pub fn links_in(delta: &[TextDelta]) -> Vec<LinkTarget> { let mut out = Vec::new(); for delta in delta { let TextDelta::Insert { attributes: Some(attrs), .. } = delta else { continue }; let Some(href) = attrs.get("link").and_then(|link| link.get_by_key("href")).and_then(value_str) else { continue; }; if let Some(target) = link_target(&href) && !out.contains(&target) { out.push(target); } } out } /// The note an href points at, when it is a note link. pub fn link_target(href: &str) -> Option<LinkTarget> { let rest = href.strip_prefix("/notes/")?; if let Some(encoded) = rest.strip_prefix("by-title/") { let title = percent_decode(encoded); return (!title.trim().is_empty()).then_some(LinkTarget::Title(title)); } let is_id = !rest.is_empty() && !rest.contains(['/', '?', '#']); is_id.then(|| LinkTarget::Id(rest.to_owned())) } /// Percent-encodes everything except RFC 3986 unreserved characters. pub fn percent_encode(s: &str) -> String { let mut out = String::with_capacity(s.len()); for b in s.bytes() { match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { out.push(b as char) } _ => out.push_str(&format!("%{b:02X}")), } } out } /// Decodes `%XX` escapes. Malformed escapes are kept as they are. pub fn percent_decode(s: &str) -> String { let bytes = s.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut i = 0; while i < bytes.len() { if bytes[i] == b'%' && i + 2 < bytes.len() { let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok(); if let Some(v) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) { out.push(v); i += 3; continue; } } out.push(bytes[i]); i += 1; } String::from_utf8_lossy(&out).into_owned() }