Elffuss BraidHub

kikocis/utopia public

dev · 3.7 KiBRawPermalink
1//! Charter 语料:与前端 Docs 页同一批 markdown(单一事实来源,随二进制升级)。
2//! 新增文章 = 前端 Docs.tsx 清单加一行 + 这里 ARTICLES 加一行。
3
4use utopia_search::{DocsIndex, DocsSection};
5
6/// (slug, 标题, 正文)。slug 必须与前端 DOCS 清单一致(引用链接 /docs/{slug} 才对得上)。
7const ARTICLES: &[(&str, &str, &str)] = &[(
8 "ingest",
9 "Ingest interfaces",
10 include_str!("../../../web/src/docs/ingest.md"),
11)];
12
13/// 启动时建索引;语料是编译期常量,失败即程序错误,响亮地死。
14pub fn build_index() -> DocsIndex {
15 DocsIndex::build(&sections()).expect("Charter 文档索引构建失败")
16}
17
18/// 按 h2 切节:一节一条索引记录,命中返回具体小节而不是整篇。
19/// h2 之前的引言归入"标题节"(anchor 为空,链接落到文章顶部)。
20fn sections() -> Vec<DocsSection> {
21 let mut out = Vec::new();
22 for (slug, title, body) in ARTICLES {
23 let mut heading = (*title).to_string();
24 let mut anchor = String::new();
25 let mut buf: Vec<&str> = Vec::new();
26 let mut flush = |heading: &str, anchor: &str, buf: &mut Vec<&str>| {
27 let text = buf.join("\n").trim().to_string();
28 if !text.is_empty() {
29 out.push(DocsSection {
30 slug: (*slug).to_string(),
31 title: (*title).to_string(),
32 heading: heading.to_string(),
33 anchor: anchor.to_string(),
34 body: text,
35 });
36 }
37 buf.clear();
38 };
39 for line in body.lines() {
40 if let Some(h) = line.strip_prefix("## ") {
41 flush(&heading, &anchor, &mut buf);
42 // 与前端 tocOf 同法清洗:去掉行内 code/强调符号
43 heading = h.replace(['`', '*'], "").trim().to_string();
44 anchor = slugify(&heading);
45 } else if !line.starts_with("# ") {
46 buf.push(line);
47 }
48 }
49 flush(&heading, &anchor, &mut buf);
50 }
51 out
52}
53
54/// 与前端 Docs.tsx 的 slugify 逐字对齐(锚点跳转依赖两边一致):
55/// 小写后,[a-z0-9一-龥] 之外的连续串折成单个 '-',再去掉首尾 '-'。
56fn slugify(s: &str) -> String {
57 let mut out = String::with_capacity(s.len());
58 let mut dash = false;
59 for c in s.to_lowercase().chars() {
60 let keep =
61 c.is_ascii_lowercase() || c.is_ascii_digit() || ('\u{4e00}'..='\u{9fa5}').contains(&c);
62 if keep {
63 if dash && !out.is_empty() {
64 out.push('-');
65 }
66 dash = false;
67 out.push(c);
68 } else {
69 dash = true;
70 }
71 }
72 out
73}
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78
79 #[test]
80 fn slugify_matches_frontend() {
81 assert_eq!(slugify("Choosing between them"), "choosing-between-them");
82 assert_eq!(
83 slugify("Custom source — the pull interface"),
84 "custom-source-the-pull-interface"
85 );
86 assert_eq!(
87 slugify("API source — the push interface"),
88 "api-source-the-push-interface"
89 );
90 assert_eq!(slugify("共享语义 Shared"), "共享语义-shared");
91 }
92
93 #[test]
94 fn ingest_splits_into_sections() {
95 let secs = sections();
96 assert!(secs.len() >= 4, "ingest.md 应切出引言 + 3 个以上小节");
97 assert!(secs.iter().any(|s| s.anchor == "shared-semantics"));
98 // 引言节:anchor 空,heading 用文章标题
99 assert!(secs
100 .iter()
101 .any(|s| s.anchor.is_empty() && s.heading == "Ingest interfaces"));
102 }
103}