| 1 | |
| 2 | |
| 3 | use loro::{LoroDoc, TextDelta}; |
| 4 | |
| 5 | use crate::tree::value_str; |
| 6 | |
| 7 | |
| 8 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 9 | pub enum LinkTarget { |
| 10 | Id(String), |
| 11 | Title(String), |
| 12 | } |
| 13 | |
| 14 | |
| 15 | |
| 16 | pub fn note_links(doc: &LoroDoc) -> Vec<LinkTarget> { |
| 17 | links_in(&crate::flat::body(doc).to_delta()) |
| 18 | } |
| 19 | |
| 20 | |
| 21 | pub 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 | |
| 38 | pub 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 | |
| 49 | pub 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 | |
| 63 | pub 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 | } |