reflex/pulse/model/
ids.rs1use serde::{Deserialize, Serialize};
9use std::collections::{BTreeMap, BTreeSet};
10use std::fmt;
11use std::path::Path;
12
13macro_rules! id_type {
14 ($(#[$doc:meta])* $name:ident) => {
15 $(#[$doc])*
16 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
17 #[serde(transparent)]
18 pub struct $name(pub String);
19
20 impl $name {
21 pub fn new(s: impl Into<String>) -> Self {
22 Self(s.into())
23 }
24 pub fn as_str(&self) -> &str {
25 &self.0
26 }
27 }
28
29 impl fmt::Display for $name {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 f.write_str(&self.0)
32 }
33 }
34
35 impl From<&str> for $name {
36 fn from(s: &str) -> Self {
37 Self(s.to_string())
38 }
39 }
40 };
41}
42
43id_type!(
44 PageId
46);
47id_type!(
48 AnchorId
50);
51id_type!(
52 ModuleId
54);
55id_type!(
56 FactId
58);
59id_type!(
60 SymbolId
62);
63
64pub fn slugify(segment: &str) -> String {
66 let mut out = String::with_capacity(segment.len());
67 let mut dash = false;
68 for c in segment.chars() {
69 if c.is_ascii_alphanumeric() {
70 out.push(c.to_ascii_lowercase());
71 dash = false;
72 } else if !dash && !out.is_empty() {
73 out.push('-');
74 dash = true;
75 }
76 }
77 while out.ends_with('-') {
78 out.pop();
79 }
80 if out.is_empty() {
81 out.push('x');
82 }
83 out
84}
85
86pub fn anchor_for(text: &str) -> AnchorId {
88 AnchorId(slugify(text))
89}
90
91#[derive(Debug, Default, Serialize, Deserialize)]
94pub struct SlugAllocator {
95 assigned: BTreeMap<PageId, String>,
97 #[serde(skip)]
98 taken: BTreeSet<String>,
99 #[serde(skip)]
100 used: BTreeSet<PageId>,
101}
102
103impl SlugAllocator {
104 pub fn load(path: &Path) -> Self {
106 let mut me: Self = std::fs::read(path)
107 .ok()
108 .and_then(|b| serde_json::from_slice(&b).ok())
109 .unwrap_or_default();
110 me.taken = me.assigned.values().cloned().collect();
111 me
112 }
113
114 pub fn assign(&mut self, id: &PageId, wanted: &str) -> String {
119 self.used.insert(id.clone());
120 if let Some(existing) = self.assigned.get(id) {
121 return existing.clone();
122 }
123 let mut slug = wanted.to_string();
124 let mut n = 2;
125 while self.taken.contains(&slug) {
126 slug = format!("{wanted}-{n}");
127 n += 1;
128 }
129 self.taken.insert(slug.clone());
130 self.assigned.insert(id.clone(), slug.clone());
131 slug
132 }
133
134 pub fn save(&self, path: &Path) -> std::io::Result<()> {
137 let kept: BTreeMap<&PageId, &String> = self
138 .assigned
139 .iter()
140 .filter(|(id, _)| self.used.contains(*id))
141 .collect();
142 if let Some(parent) = path.parent() {
143 std::fs::create_dir_all(parent)?;
144 }
145 let tmp = crate::atomic_write::tmp_path_for(path);
146 std::fs::write(
147 &tmp,
148 serde_json::to_vec_pretty(&serde_json::json!({ "assigned": kept }))?,
149 )?;
150 crate::atomic_write::atomic_replace(&tmp, path)
151 }
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157
158 #[test]
159 fn slugify_segments() {
160 assert_eq!(slugify("src"), "src");
161 assert_eq!(slugify("Query Engine"), "query-engine");
162 assert_eq!(slugify("build.rs"), "build-rs");
163 assert_eq!(slugify("__init__"), "init");
164 assert_eq!(slugify("--"), "x");
165 assert_eq!(slugify("v2.0.1"), "v2-0-1");
166 }
167
168 #[test]
169 fn slugs_are_stable_and_collisions_deterministic() {
170 let dir = tempfile::TempDir::new().unwrap();
171 let path = dir.path().join("slugs.json");
172 let mut a = SlugAllocator::load(&path);
173 assert_eq!(a.assign(&"p1".into(), "src/a-b"), "src/a-b");
174 assert_eq!(a.assign(&"p2".into(), "src/a-b"), "src/a-b-2");
175 a.save(&path).unwrap();
176
177 let mut b = SlugAllocator::load(&path);
179 assert_eq!(b.assign(&"p2".into(), "src/a-b"), "src/a-b-2");
180 assert_eq!(b.assign(&"p1".into(), "src/a-b"), "src/a-b");
181 assert_eq!(b.assign(&"p3".into(), "src/a-b"), "src/a-b-3");
182 }
183
184 #[test]
185 fn vanished_pages_free_their_slug() {
186 let dir = tempfile::TempDir::new().unwrap();
187 let path = dir.path().join("slugs.json");
188 let mut a = SlugAllocator::load(&path);
189 a.assign(&"old".into(), "x");
190 a.save(&path).unwrap();
191 let b = SlugAllocator::load(&path);
192 b.save(&path).unwrap(); let mut c = SlugAllocator::load(&path);
194 assert_eq!(c.assign(&"new".into(), "x"), "x");
195 }
196}