AnyBot/src/diagram.rs

124 lines
5.7 KiB
Rust
Raw Normal View History

// Mermaid diagrams in chat (```mermaid fences), like the original's own Mermaid-compatible
// engine: pure Rust (mermaid-rs-renderer → SVG), drawn with resvg using AnyBot's fonts so
// Chinese labels show. Flowcharts, sequence, class, state, ER, gantt, pie, mindmap, timeline…
use std::sync::OnceLock;
/// The original refuses diagrams over 50 000 characters.
pub const MAX_SOURCE: usize = 50_000;
fn fontdb() -> std::sync::Arc<resvg::usvg::fontdb::Database> {
static DB: OnceLock<std::sync::Arc<resvg::usvg::fontdb::Database>> = OnceLock::new();
DB.get_or_init(|| {
let mut db = resvg::usvg::fontdb::Database::new();
db.load_font_data(crate::HUNINN.to_vec());
db.load_system_fonts();
// Every family the diagram asks for falls back to 粉圓體 (it has Latin and CJK).
let found: Option<String> = db.faces().find(|f| f.families.iter().any(|(n, _)| n.to_lowercase().contains("huninn") || n.contains("粉圓"))).and_then(|f| f.families.first().map(|(n, _)| n.clone()));
if let Some(name) = found {
db.set_sans_serif_family(name.clone());
db.set_serif_family(name);
}
std::sync::Arc::new(db)
})
.clone()
}
圖表與數字卡改成閱讀向排版(Notion 風):色板、直接標數、排序、手機原生圖 研究依據(2026-10 Supernova 11 設計系統調查、IBM Carbon 資料視覺化規範、 Atlassian chart tokens、shadcn/ui chart、Tufte data-ink、EEA/Sheffield 準則): 預設單色、分類色≤6固定序、只留淡水平參考線、直接標數取代圖例與座標軸、 長條按大小排序(自有順序的標籤不排)、顏色只給意義(漲綠跌紅附箭頭)。 - theme.rs:新增 chart_cat 六色(明暗各一組,低飽和藍紫青橙粉灰)、grid、up - 桌面圖表卡:網格只剩淡水平線;單系列長條把數字標在條上、不畫 y 軸; 長條自動由大到小排序(月/季/年/W1/Q1/數字等自然序標籤不排); 多條線在線尾標系列名(取代圖例);stats 數字卡大字、↑/+綠 ↓/−紅 - Mermaid:白底卡節點、細灰連線、同套六色圓餅(house_theme) - 手機:```chart 原本掉成純文字——現在畫原生 SVG,規則與色板和桌面同款; stats 卡改白卡描邊、大字、漲綠跌紅;代幣進 :root/dark - write_page 說明:排版由渲染器接手,Bot 專心把圖標題寫成結論 - 功能地圖 pages.md/FEATURES.md 同步;layout_audit 新增「頁面(圖表)」場景 已驗證: cargo test 501 全綠;layout_audit 全綠(新場景含長條排序/多線/圓餅/stats, 664/1000/1440 三寬度無出界無疊字);手機 chartMd 用 node 跑 8 個案例(排序、 自然序不排、線尾標名、圓餅佔比、tooltip、千分位、壞輸入回空)全過; ANYBOT_SHOT=page 截圖肉眼確認 未驗證: 手機端只在 node 驗證圖表產生器,未實機開網頁看 SVG 渲染; Mermaid 新主題未逐圖型(gantt/gitGraph)目視;深色模式截圖未拍
2026-11-16 08:43:55 +00:00
/// The house look for diagrams (same spirit as the chart cards, and the same six-colour
/// series palette): quiet cards, thin grey connectors, no heavy borders — Mermaid's default
/// blues are loud and read as "report software" next to the rest of the app.
fn house_theme(dark: bool) -> mermaid_rs_renderer::Theme {
let mut t = if dark { mermaid_rs_renderer::Theme::dark() } else { mermaid_rs_renderer::Theme::neutral() };
let (card, line, ink, faint, fill2, fill3, grid) = if dark {
("#252525", "#8a8a8a", "#f5f5f5", "#3a3a3a", "#2f3438", "#2b2d31", "#1f1f1f")
} else {
("#ffffff", "#9b9a97", "#1c1c1c", "#e3e2df", "#f1f1ef", "#eff5fb", "#f7f7f5")
};
t.primary_color = card.into();
t.primary_border_color = faint.into();
t.primary_text_color = ink.into();
t.line_color = line.into();
t.secondary_color = fill2.into();
t.tertiary_color = fill3.into();
t.edge_label_background = card.into();
t.cluster_background = grid.into();
t.cluster_border = faint.into();
t.background = if dark { "#1f1f1f".into() } else { "transparent".into() };
t.sequence_actor_fill = fill2.into();
t.sequence_actor_border = faint.into();
t.sequence_actor_line = line.into();
t.sequence_note_fill = if dark { "#3a3212".into() } else { "#fff8e1".into() };
t.sequence_note_border = faint.into();
t.sequence_activation_fill = fill3.into();
t.sequence_activation_border = if dark { "#529cca" } else { "#2383e2" }.into();
t.text_color = ink.into();
// Pie and git series: the house palette (theme.rs chart_cat), in order, then repeats lighter.
let cat: [&str; 6] = if dark {
["#529cca", "#b493e5", "#4dab9a", "#e3a062", "#f291c0", "#a09e9a"]
} else {
["#2383e2", "#9065b0", "#0f7b6c", "#d9730d", "#e06b9e", "#6e6c68"]
};
t.pie_colors = std::array::from_fn(|i| cat[i % 6].to_string());
t.pie_stroke_color = card.into();
t.pie_title_text_color = ink.into();
t.pie_section_text_color = ink.into();
t.pie_legend_text_color = ink.into();
t
}
/// Mermaid source → SVG text.
pub fn svg(source: &str, dark: bool) -> Result<String, String> {
if source.len() > MAX_SOURCE {
return Err("圖表太大".into());
}
圖表與數字卡改成閱讀向排版(Notion 風):色板、直接標數、排序、手機原生圖 研究依據(2026-10 Supernova 11 設計系統調查、IBM Carbon 資料視覺化規範、 Atlassian chart tokens、shadcn/ui chart、Tufte data-ink、EEA/Sheffield 準則): 預設單色、分類色≤6固定序、只留淡水平參考線、直接標數取代圖例與座標軸、 長條按大小排序(自有順序的標籤不排)、顏色只給意義(漲綠跌紅附箭頭)。 - theme.rs:新增 chart_cat 六色(明暗各一組,低飽和藍紫青橙粉灰)、grid、up - 桌面圖表卡:網格只剩淡水平線;單系列長條把數字標在條上、不畫 y 軸; 長條自動由大到小排序(月/季/年/W1/Q1/數字等自然序標籤不排); 多條線在線尾標系列名(取代圖例);stats 數字卡大字、↑/+綠 ↓/−紅 - Mermaid:白底卡節點、細灰連線、同套六色圓餅(house_theme) - 手機:```chart 原本掉成純文字——現在畫原生 SVG,規則與色板和桌面同款; stats 卡改白卡描邊、大字、漲綠跌紅;代幣進 :root/dark - write_page 說明:排版由渲染器接手,Bot 專心把圖標題寫成結論 - 功能地圖 pages.md/FEATURES.md 同步;layout_audit 新增「頁面(圖表)」場景 已驗證: cargo test 501 全綠;layout_audit 全綠(新場景含長條排序/多線/圓餅/stats, 664/1000/1440 三寬度無出界無疊字);手機 chartMd 用 node 跑 8 個案例(排序、 自然序不排、線尾標名、圓餅佔比、tooltip、千分位、壞輸入回空)全過; ANYBOT_SHOT=page 截圖肉眼確認 未驗證: 手機端只在 node 驗證圖表產生器,未實機開網頁看 SVG 渲染; Mermaid 新主題未逐圖型(gantt/gitGraph)目視;深色模式截圖未拍
2026-11-16 08:43:55 +00:00
let mut opts = mermaid_rs_renderer::RenderOptions { theme: house_theme(dark), ..Default::default() };
opts.theme.font_family = "sans-serif".into();
// A panic inside the layout must not take the window down.
let src = source.to_string();
std::panic::catch_unwind(move || mermaid_rs_renderer::render_strict(&src, opts).map_err(|e| e.to_string()))
.map_err(|_| "圖表排版失敗".to_string())?
}
/// Mermaid source → RGBA pixels at `scale` (2.0 for sharp text on Retina).
pub fn render(source: &str, dark: bool, scale: f32) -> Result<image::RgbaImage, String> {
let svg = svg(source, dark)?;
let opt = resvg::usvg::Options { fontdb: fontdb(), font_family: "sans-serif".into(), ..Default::default() };
let tree = resvg::usvg::Tree::from_str(&svg, &opt).map_err(|e| e.to_string())?;
let size = tree.size();
let (w, h) = ((size.width() * scale).ceil().max(1.0) as u32, (size.height() * scale).ceil().max(1.0) as u32);
if w as u64 * h as u64 > 40_000_000 {
return Err("圖表太大".into());
}
let mut pm = resvg::tiny_skia::Pixmap::new(w, h).ok_or("圖表太大")?;
resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(scale, scale), &mut pm.as_mut());
// tiny-skia is premultiplied; egui wants straight alpha.
let mut px = pm.take();
for c in px.as_chunks_mut::<4>().0 {
let a = c[3] as u32;
if a > 0 && a < 255 {
for v in &mut c[..3] {
*v = ((*v as u32 * 255 + a / 2) / a).min(255) as u8;
}
}
}
image::RgbaImage::from_raw(w, h, px).ok_or_else(|| "圖表轉換失敗".into())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flowchart_and_errors() {
let img = render("flowchart TD\n A[開始] --> B{要不要出門?}\n B -->|要| C[帶傘]\n B -->|不要| D[在家看書]\n C --> E[結束]\n D --> E", false, 1.0).unwrap();
assert!(img.width() > 100 && img.height() > 100);
// Some ink in the picture (not all transparent).
assert!(img.pixels().filter(|p| p.0[3] > 0).count() > 1000);
if let Ok(out) = std::env::var("ANYBOT_DIAGRAM_OUT") {
img.save(out).unwrap();
}
assert!(render("this is not mermaid at all {{{", false, 1.0).is_err());
assert!(render(&"x".repeat(MAX_SOURCE + 1), false, 1.0).is_err());
}
}