Files
Thing/src-tauri/src/editor/templates.rs
T
2026-10-10 14:29:48 +08:00

305 lines
11 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 新建笔记的模板:内置默认模板 + 用户模板目录。
//!
//! # 模板为什么要落成 `.md` 文件
//!
//! 与「笔记的真相是文件」同一条原则:模板也是用户会想改的东西,做成 JSON 里的一段
//! 字符串,用户既看不到也改不了。落成 `.md` 文件后,用任意编辑器改,改完立刻生效。
//!
//! # 两个来源
//!
//! - **内置**:编译进二进制(`include_str!`),保证全新机器上「新建笔记」永远有东西可用;
//! - **用户**:`{库根}/templates/*.md`。库是可切换的,模板跟着库走 —— 一个技术笔记库
//! 和一个日记库本来就该有不同的模板集。
//!
//! 同名时用户模板覆盖内置模板。内置模板不写进库根(否则用户第一次新建笔记就会
//! 发现库里多出一堆他没建过的文件)。
//!
//! # 变量替换
//!
//! 只支持少量、无歧义的占位符(`{{date}}` / `{{time}}` / `{{title}}` / `{{datetime}}`)。
//! **不做条件、循环、包含** —— 那是一条通往「半个模板引擎」的路,收益远小于维护成本。
use std::path::Path;
use serde::{Deserialize, Serialize};
use specta::Type;
use super::library;
/// 一个模板。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct NoteTemplate {
/// 标识(内置用 `builtin:<文件名>`,用户模板用 `user:<文件名>`)
pub id: String,
/// 显示名(文件名去掉扩展名)
pub name: String,
/// 说明(内置模板手写;用户模板取正文首行非空文本)
pub description: String,
/// 是否为内置模板(前端据此提示「不可删除」)
pub builtin: bool,
/// 模板正文(含 front-matter)
pub body: String,
}
/// 内置模板(编译进二进制)。
const BUILTIN: &[(&str, &str, &str)] = &[
(
"空白笔记",
"只有 front-matter 与一级标题,适合随手记",
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: []\n---\n\n# {{title}}\n\n",
),
(
"会议纪要",
"议题 / 结论 / 待办三段式",
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [会议]\n---\n\n# {{title}}\n\n- 时间:{{datetime}}\n- 参会:\n\n## 议题\n\n## 结论\n\n## 待办\n\n- [ ] \n",
),
(
"日记",
"按日期归档的日记骨架",
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [日记]\n---\n\n# {{date}}\n\n## 今天做了什么\n\n## 明天要做什么\n\n- [ ] \n",
),
(
"读书笔记",
"书籍信息 + 摘录 + 思考",
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [读书]\n---\n\n# {{title}}\n\n- 书名:\n- 作者:\n- 进度:\n\n## 摘录\n\n> \n\n## 我的思考\n\n",
),
];
/// 列出全部模板(用户模板优先,同名覆盖内置)。
pub fn list(root: &Path) -> Vec<NoteTemplate> {
let mut out: Vec<NoteTemplate> = Vec::new();
// 用户模板:`{库根}/templates/*.md`
let dir = root.join("templates");
if dir.is_dir() {
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
.into_iter()
.flatten()
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| {
path.is_file()
&& path
.extension()
.map(|e| e.eq_ignore_ascii_case("md"))
.unwrap_or(false)
})
.collect();
files.sort();
for path in files {
let name = path
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
if name.is_empty() {
continue;
}
let Ok(body) = std::fs::read_to_string(&path) else {
continue;
};
out.push(NoteTemplate {
id: format!("user:{name}"),
description: first_meaningful_line(&body),
name,
builtin: false,
body,
});
}
}
// 内置模板:跳过已被用户模板同名的
for (name, description, body) in BUILTIN {
if out.iter().any(|item| item.name == *name) {
continue;
}
out.push(NoteTemplate {
id: format!("builtin:{name}"),
name: name.to_string(),
description: description.to_string(),
builtin: true,
body: body.to_string(),
});
}
out
}
/// 取模板 ID 对应的正文;找不到返回 `None`(调用方回退到默认模板)。
pub fn body_of(root: &Path, id: &str) -> Option<String> {
list(root).into_iter().find(|t| t.id == id).map(|t| t.body)
}
/// 把模板正文渲染成一篇新笔记的内容。
///
/// `parent_dir` 是笔记所在的库内目录(用于 `{{date}}` 之类不受影响,但保留参数
/// 以便将来加入「所在目录」变量)。
pub fn render(body: &str, title: &str, _parent_dir: &str) -> String {
let now = chrono::Local::now();
body.replace("{{title}}", title)
.replace("{{date}}", &now.format("%Y-%m-%d").to_string())
.replace("{{time}}", &now.format("%H:%M").to_string())
.replace("{{datetime}}", &now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
}
/// 日记的默认文件名(`2026-09-30`),供「今日日记」入口用。
pub fn daily_note_name() -> String {
chrono::Local::now().format("%Y-%m-%d").to_string()
}
/// 默认模板的 ID(新建笔记时未选模板就用它)。
pub fn default_template_id() -> String {
"builtin:空白笔记".to_string()
}
/// 正文里第一行有意义的文本(用户模板的说明用)。
fn first_meaningful_line(body: &str) -> String {
for line in body.lines() {
let text = line.trim();
if text.is_empty() || text == "---" || text.starts_with('#') || text.starts_with("title:") {
continue;
}
return text.chars().take(40).collect();
}
String::new()
}
/// 为「新建笔记」渲染正文:`template_id` 为空或找不到时用默认模板。
pub fn render_for_new_note(root: &Path, template_id: &str, title: &str, dir_rel: &str) -> String {
let id = if template_id.trim().is_empty() {
default_template_id()
} else {
template_id.to_string()
};
match body_of(root, &id) {
Some(body) => render(&body, title, dir_rel),
None => {
// 兜底:内置空白模板(即使模板目录被清空也能新建)
let fallback = BUILTIN
.first()
.map(|(_, _, body)| *body)
.unwrap_or("---\ntitle: {{title}}\n---\n\n# {{title}}\n\n");
render(fallback, title, dir_rel)
}
}
}
/// 确保库里的 `templates/` 目录存在(用户想自定义模板时不用自己新建目录)。
pub fn ensure_dir(root: &Path) -> Result<(), String> {
std::fs::create_dir_all(root.join("templates")).map_err(|e| format!("创建模板目录失败: {e}"))
}
/// 把内置模板写进库内 `templates/`(供「导出内置模板」按钮用;已存在的不覆盖)。
pub fn export_builtin(root: &Path) -> Result<Vec<String>, String> {
ensure_dir(root)?;
let dir = root.join("templates");
let mut written = Vec::new();
for (name, _, body) in BUILTIN {
let path = dir.join(format!("{name}.md"));
if path.exists() {
continue;
}
std::fs::write(&path, body).map_err(|e| format!("写入模板 {name} 失败: {e}"))?;
written.push(name.to_string());
}
Ok(written)
}
/// 模板文件在库内的相对路径(前端「编辑模板」用;内置模板返回 `None`)。
pub fn relative_path(id: &str) -> Option<String> {
id.strip_prefix("user:")
.map(|name| format!("templates/{name}.md"))
}
/// 校验模板名(新建模板时用)。
pub fn validate_name(name: &str) -> Result<String, String> {
library::validate_name(name)
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_root(tag: &str) -> std::path::PathBuf {
let root =
std::env::temp_dir().join(format!("thing-notes-tpl-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
root
}
#[test]
fn builtin_templates_are_available_without_files() {
let root = temp_root("builtin");
let templates = list(&root);
assert!(templates.len() >= 4, "{templates:?}");
assert!(templates.iter().all(|t| t.builtin));
assert!(templates.iter().any(|t| t.name == "日记"));
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn user_template_overrides_builtin_with_same_name() {
let root = temp_root("override");
ensure_dir(&root).unwrap();
std::fs::write(root.join("templates/空白笔记.md"), "用户自己的模板 {{title}}").unwrap();
let templates = list(&root);
let blank = templates.iter().find(|t| t.name == "空白笔记").unwrap();
assert!(!blank.builtin, "同名时用户模板应覆盖内置");
assert!(blank.body.contains("用户自己的模板"));
assert_eq!(
templates.iter().filter(|t| t.name == "空白笔记").count(),
1,
"不该出现两份同名模板"
);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn render_substitutes_variables() {
let out = render("---\ntitle: {{title}}\ncreated: {{datetime}}\n---\n\n# {{title}} {{date}}\n", "周会", "");
assert!(out.contains("title: 周会"));
assert!(out.contains("# 周会 "));
assert!(!out.contains("{{"), "所有占位符都应被替换: {out}");
}
#[test]
fn render_for_new_note_falls_back_to_blank() {
let root = temp_root("fallback");
let out = render_for_new_note(&root, "user:不存在", "标题", "");
assert!(out.contains("标题"));
assert!(!out.contains("{{"));
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn export_builtin_does_not_overwrite() {
let root = temp_root("export");
ensure_dir(&root).unwrap();
std::fs::write(root.join("templates/日记.md"), "我的日记模板").unwrap();
let written = export_builtin(&root).unwrap();
assert!(!written.contains(&"日记".to_string()), "{written:?}");
assert_eq!(
std::fs::read_to_string(root.join("templates/日记.md")).unwrap(),
"我的日记模板"
);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn relative_path_only_for_user_templates() {
assert_eq!(
relative_path("user:会议纪要"),
Some("templates/会议纪要.md".to_string())
);
assert_eq!(relative_path("builtin:日记"), None);
}
#[test]
fn daily_note_name_is_date_shaped() {
let name = daily_note_name();
assert_eq!(name.len(), 10, "{name}");
assert_eq!(name.matches('-').count(), 2);
}
}