diff --git a/src/app.rs b/src/app.rs index 2c46f69..e5654ff 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,16 +1,18 @@ //! Application state, page rendering, window creation and the event loop. use crate::config::{ - confirm_discard_unsaved, load_theme_choice, load_zoom, save_theme_choice, save_window_geom, - save_zoom, show_warning_dialog, ThemeChoice, + centered_geom, config_dir, confirm_discard_unsaved, geom_visible, load_theme_choice, + load_window_geom, load_zoom, save_theme_choice, save_window_geom, save_zoom, + show_warning_dialog, ThemeChoice, }; use crate::escape::{escape_js, html_escape_attr, html_escape_text}; use crate::files::{ - forget_recent_file, install_file_watcher, is_supported_document, local_document_path_from_url, - normalize_new_markdown_path, remember_recent_file, resolve_document_link, reveal_in_explorer, - save_active_file, self_write_still_matches_disk, should_protect_external_change, - SelfWriteRecord, MAX_RECENT_FILES, + forget_recent_file, install_file_watcher, is_supported_document, load_recent_files, + local_document_path_from_url, normalize_new_markdown_path, remember_recent_file, + resolve_document_link, reveal_in_explorer, save_active_file, self_write_still_matches_disk, + should_protect_external_change, SelfWriteRecord, MAX_RECENT_FILES, }; +use crate::instance; use crate::markdown::md_to_html_with_base; use crate::page::build_page; use crate::session::{self, DocumentSession}; @@ -19,9 +21,11 @@ use std::fs; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::Instant; -use tao::dpi::{PhysicalPosition, PhysicalSize}; +use tao::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}; use tao::event::{Event as TaoEvent, WindowEvent}; -use tao::event_loop::{ControlFlow, EventLoop, EventLoopProxy, EventLoopWindowTarget}; +use tao::event_loop::{ + ControlFlow, EventLoop, EventLoopBuilder, EventLoopProxy, EventLoopWindowTarget, +}; use tao::window::{Window, WindowBuilder, WindowId}; use wry::{WebContext, WebView, WebViewBuilder}; @@ -1595,3 +1599,336 @@ pub(crate) fn run_event_loop( } }); } + +fn is_help_arg(arg: &str) -> bool { + arg == "-h" || arg == "--help" +} + +fn print_help() { + println!( + "MD Preview {}\n\nUsage:\n md-preview [file.md]\n\nOptions:\n -h, --help Show this help message", + env!("CARGO_PKG_VERSION") + ); +} + +/// Parse the CLI, build the first window/webview and hand control to the loop. +pub(crate) fn run() { + // Bench instrumentation: MD_PREVIEW_BENCH=1 makes the app print + // cold-start timings to stderr and exit as soon as the first paint + // lands. Costs nothing outside bench mode. + let bench = std::env::var("MD_PREVIEW_BENCH").is_ok(); + let t0 = Instant::now(); + let bench_log = |label: &str| { + if bench { + eprintln!("[bench] +{}ms {}", t0.elapsed().as_millis(), label); + } + }; + bench_log("main_start"); + + // CLI: md-preview [--edit] [file.md ...] + let args = std::env::args().skip(1).collect::>(); + if args.iter().any(|arg| is_help_arg(arg)) { + print_help(); + return; + } + let edit_from_cli = args.iter().any(|arg| arg == "--edit"); + let cli_paths = args + .into_iter() + .filter(|arg| arg != "--edit") + .map(PathBuf::from) + .map(|path| { + if path.is_relative() { + std::env::current_dir().unwrap_or_default().join(path) + } else { + path + } + }) + .filter(|path| { + if path.exists() && is_supported_document(path) { + true + } else { + eprintln!("File not found or unsupported: {}", path.display()); + false + } + }) + .collect::>(); + + let primary = if bench { + None + } else { + match instance::acquire( + &config_dir(), + &instance::Launch { + paths: cli_paths.clone(), + edit: edit_from_cli, + }, + ) { + Ok(Some(primary)) => Some(primary), + Ok(None) => return, + Err(error) => { + show_warning_dialog("Could Not Open MD Preview", &error.to_string()); + return; + } + } + }; + + let strings = Strings::english(); + bench_log("after_register"); + + let mut initial_session = DocumentSession::default(); + for path in cli_paths { + initial_session.open(path, edit_from_cli); + } + if initial_session.tabs.is_empty() { + initial_session.open_home(); + } + + let event_loop: EventLoop = EventLoopBuilder::with_user_event().build(); + let proxy = event_loop.create_proxy(); + if let Some(primary) = primary { + let proxy = proxy.clone(); + primary.listen(move |launch| { + proxy + .send_event(UserEvent::OpenPaths(None, launch.paths, launch.edit)) + .is_ok() + }); + } + let initial_theme = load_theme_choice(); + + let title = initial_session + .active() + .and_then(|tab| tab.file_path()) + .and_then(|path| path.file_name()) + .map(|name| format!("{} — MD Preview", name.to_string_lossy())) + .unwrap_or_else(|| "MD Preview".to_string()); + + let geom = load_window_geom() + .filter(|g| geom_visible(g, &event_loop)) + .unwrap_or_else(|| centered_geom(&event_loop)); + + let mut window_builder = WindowBuilder::new() + .with_title(&title) + .with_inner_size(LogicalSize::new(geom.w, geom.h)) + .with_position(LogicalPosition::new(geom.x, geom.y)) + .with_theme(initial_theme.tao_theme()); + if let Some(icon) = load_window_icon() { + window_builder = window_builder.with_window_icon(Some(icon)); + } + let window = window_builder + .build(&event_loop) + .expect("failed to build window"); + let window_id = window.id(); + bench_log("window_built"); + let recent_files: Arc>> = Arc::new(Mutex::new(load_recent_files())); + + let initial_page = build_startup_page(&strings); + let initial_flags = EnhanceFlags::default(); + + let document_session = Arc::new(Mutex::new(initial_session)); + let enhance_flags: Arc> = Arc::new(Mutex::new(initial_flags)); + let last_self_write: Arc>> = Arc::new(Mutex::new(None)); + + // Windows: steer WebView2's cache/cookie tree into %LOCALAPPDATA% instead of + // letting it drop next to the exe. Other platforms: use default (None). + let data_dir: Option = { + let d = config_dir().join("WebView2"); + let _ = fs::create_dir_all(&d); + Some(d) + }; + let mut web_context = wry::WebContext::new(data_dir); + + let webview = match build_webview( + &window, + &mut web_context, + window_id, + Arc::clone(&document_session), + Arc::clone(&last_self_write), + Arc::clone(&recent_files), + proxy.clone(), + initial_page, + ) { + Ok(webview) => webview, + Err(error) => { + eprintln!("Could not initialize WebView: {error}"); + show_warning_dialog("Could Not Open MD Preview", &error); + return; + } + }; + bench_log("webview_built"); + // hljs + extra language packs aren't part of first-paint HTML anymore. + // We push them in via evaluate_script the moment the webview tells us + // it's painted (IPC 'ready'). Keeps ~125KB out of the HTML-parse critical + // path so the app window shows content faster on cold start. + let hljs_bootstrap = format!( + "(function(){{{hljs_js};{hljs_extra};try{{window.hljs=hljs;}}catch(e){{}}if(typeof hljs!=='undefined'&&hljs.highlightAll){{hljs.highlightAll();}}}})();", + hljs_js = HLJS_JS, + hljs_extra = HLJS_EXTRA_LANGS, + ); + + // File watcher state + let watcher_holder: Arc>> = Arc::new(Mutex::new(None)); + + let initial_dirty = document_session + .lock() + .unwrap() + .active() + .map(|tab| tab.dirty) + .unwrap_or(false); + let app = AppState { + windows: HashMap::from([( + window_id, + WindowState { + window, + webview, + session: Arc::clone(&document_session), + last_self_write: Arc::clone(&last_self_write), + watcher: Arc::clone(&watcher_holder), + enhance_flags: Arc::clone(&enhance_flags), + loaded_enhancers: EnhanceFlags::default(), + page_ready: false, + pending_launches: Vec::new(), + pending_close: false, + warned_external_change: None, + pending_external_change: None, + dirty: initial_dirty, + is_primary: true, + }, + )]), + active_window: window_id, + recent_files: Arc::clone(&recent_files), + strings, + web_context, + }; + + run_event_loop(event_loop, app, proxy, hljs_bootstrap, bench, t0); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::page::build_page; + use crate::testutil::temp_dir; + + #[test] + fn large_document_startup_stays_below_webview2_html_limit() { + let dir = temp_dir("startup-large"); + let file = dir.join("中文 large.md"); + fs::write(&file, "x".repeat(3 * 1024 * 1024)).unwrap(); + let mut session = DocumentSession::default(); + session.open(file, true); + let page = build_startup_page(&Strings::english()); + assert!( + page.len() < 2 * 1024 * 1024, + "startup HTML has {} bytes", + page.len() + ); + assert!(session.active().unwrap().editing); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn base_href_is_a_directory_file_url() { + let dir = temp_dir("base-href"); + let file = dir.join("note.md"); + fs::write(&file, "# x").unwrap(); + + let href = base_href_for_file(&file).unwrap(); + + assert!(href.starts_with("file:///"), "{href}"); + assert!(href.ends_with('/'), "{href}"); + assert!(!href.contains("%3F"), "{href}"); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn secondary_window_stays_on_source_monitor() { + assert_eq!( + clamp_secondary_position(2028, 128, 800, 600, Some((1920, 0, 1920, 1080))), + (2028, 128) + ); + assert_eq!( + clamp_secondary_position(3400, 1200, 800, 600, Some((1920, 0, 1920, 1080))), + (3040, 480) + ); + assert_eq!( + clamp_secondary_position(-100, -100, 800, 600, Some((0, 0, 1920, 1080))), + (0, 0) + ); + assert_eq!(clamp_secondary_position(10, 10, 800, 600, None), (10, 10)); + } + + #[test] + fn set_content_script_matches_the_page_signature() { + let script = set_content_script( + "

x

", + "# x", + "file:///D:/tmp/", + EnhanceFlags { + math: true, + mermaid: false, + }, + true, + 0.25, + ); + assert_eq!( + script, + "if(window.__setContent)window.__setContent('

x

', '# x', 'file:///D:/tmp/', true, false, true, 0.25);" + ); + + // The page must declare the same argument order; a mismatch renders a + // wrong value as HTML and shows up as a blank window. + let page = build_page( + "", + "", + None, + EnhanceFlags::default(), + &Strings::english(), + true, + ); + assert!(page.contains( + "window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid, editing, scrollRatio)" + )); + } + + #[test] + fn empty_state_exposes_open_and_recent_files() { + let strings = Strings::english(); + let recent = vec![PathBuf::from("/tmp/example.md")]; + let html = home_preview_html(&strings, &recent); + + assert!(html.contains("Open File")); + assert!(html.contains("New File")); + assert!(html.contains("empty-actions")); + assert!(html.contains("data-new-file")); + assert!(html.contains("Recent")); + assert!(html.contains("example.md")); + assert!(html.contains("data-recent-index=\"0\"")); + assert!(html.contains(r#"
"#)); + assert!(html.contains(r#"
#
"#)); + assert!(!html.contains("empty-mark")); + + let page = build_page(&html, "", None, EnhanceFlags::default(), &strings, true); + assert!(page.contains(".empty.has-recent")); + assert!(!page.contains(".empty.has-recent .recent { max-height")); + assert!(page.contains("")); + assert!(page.contains("body.home .toolbar")); + } + + #[test] + fn tabs_json_marks_home_tabs_without_a_file_path() { + let mut session = DocumentSession::default(); + let home = session.open_home(); + + let json = tabs_json(&session); + + assert!(json.contains(&format!(r#""id":{home}"#)), "{json}"); + assert!(json.contains(r#""home":true"#), "{json}"); + assert!(json.contains(r#""path":"""#), "{json}"); + } + #[test] + fn help_flags_are_recognized() { + assert!(is_help_arg("-h")); + assert!(is_help_arg("--help")); + assert!(!is_help_arg("--edit")); + } +} diff --git a/src/config.rs b/src/config.rs index 9b67c30..478b5e1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -9,7 +9,7 @@ use tao::window::{Theme, Window}; pub const DEFAULT_W: f64 = 900.0; pub const DEFAULT_H: f64 = 700.0; -use crate::UserEvent; +use crate::app::UserEvent; #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub enum ThemeChoice { @@ -210,3 +210,26 @@ pub fn centered_geom(event_loop: &EventLoop) -> WindowGeom { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn zoom_percent_is_clamped_to_supported_range() { + assert_eq!(clamp_zoom(10), 50); + assert_eq!(clamp_zoom(50), 50); + assert_eq!(clamp_zoom(105), 105); + assert_eq!(clamp_zoom(300), 300); + assert_eq!(clamp_zoom(999), 300); + } + + #[test] + fn theme_choice_parses_menu_values() { + assert_eq!(ThemeChoice::from_str("system"), ThemeChoice::System); + assert_eq!(ThemeChoice::from_str("light"), ThemeChoice::Light); + assert_eq!(ThemeChoice::from_str("dark"), ThemeChoice::Dark); + assert_eq!(ThemeChoice::from_str("unexpected"), ThemeChoice::System); + assert_eq!(ThemeChoice::Dark.as_str(), "dark"); + } +} diff --git a/src/files.rs b/src/files.rs index ccbaca5..e3d4b28 100644 --- a/src/files.rs +++ b/src/files.rs @@ -9,8 +9,8 @@ use std::sync::{Arc, Mutex}; use tao::event_loop::EventLoopProxy; use tao::window::WindowId; +use crate::app::UserEvent; use crate::session::{self, DocumentSession}; -use crate::UserEvent; pub const MAX_RECENT_FILES: usize = 8; diff --git a/src/main.rs b/src/main.rs index d482ed2..1877761 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,793 +12,6 @@ mod session; #[cfg(test)] mod testutil; -use app::{ - build_startup_page, build_webview, load_window_icon, run_event_loop, AppState, EnhanceFlags, - Strings, UserEvent, WindowState, HLJS_EXTRA_LANGS, HLJS_JS, -}; -use config::{ - centered_geom, config_dir, geom_visible, load_theme_choice, load_window_geom, - show_warning_dialog, -}; -use files::{is_supported_document, load_recent_files, SelfWriteRecord}; -use session::DocumentSession; -use std::collections::HashMap; -use std::fs; -use std::path::PathBuf; -use std::sync::{Arc, Mutex}; -use std::time::Instant; -use tao::dpi::{LogicalPosition, LogicalSize}; -use tao::event_loop::{EventLoop, EventLoopBuilder}; -use tao::window::WindowBuilder; - -#[cfg(test)] -use markdown::md_to_html; -#[cfg(test)] -use page::build_page; - -fn is_help_arg(arg: &str) -> bool { - arg == "-h" || arg == "--help" -} - -fn print_help() { - println!( - "MD Preview {}\n\nUsage:\n md-preview [file.md]\n\nOptions:\n -h, --help Show this help message", - env!("CARGO_PKG_VERSION") - ); -} - fn main() { - // Bench instrumentation: MD_PREVIEW_BENCH=1 makes the app print - // cold-start timings to stderr and exit as soon as the first paint - // lands. Costs nothing outside bench mode. - let bench = std::env::var("MD_PREVIEW_BENCH").is_ok(); - let t0 = Instant::now(); - let bench_log = |label: &str| { - if bench { - eprintln!("[bench] +{}ms {}", t0.elapsed().as_millis(), label); - } - }; - bench_log("main_start"); - - // CLI: md-preview [--edit] [file.md ...] - let args = std::env::args().skip(1).collect::>(); - if args.iter().any(|arg| is_help_arg(arg)) { - print_help(); - return; - } - let edit_from_cli = args.iter().any(|arg| arg == "--edit"); - let cli_paths = args - .into_iter() - .filter(|arg| arg != "--edit") - .map(PathBuf::from) - .map(|path| { - if path.is_relative() { - std::env::current_dir().unwrap_or_default().join(path) - } else { - path - } - }) - .filter(|path| { - if path.exists() && is_supported_document(path) { - true - } else { - eprintln!("File not found or unsupported: {}", path.display()); - false - } - }) - .collect::>(); - - let primary = if bench { - None - } else { - match instance::acquire( - &config_dir(), - &instance::Launch { - paths: cli_paths.clone(), - edit: edit_from_cli, - }, - ) { - Ok(Some(primary)) => Some(primary), - Ok(None) => return, - Err(error) => { - show_warning_dialog("Could Not Open MD Preview", &error.to_string()); - return; - } - } - }; - - let strings = Strings::english(); - bench_log("after_register"); - - let mut initial_session = DocumentSession::default(); - for path in cli_paths { - initial_session.open(path, edit_from_cli); - } - if initial_session.tabs.is_empty() { - initial_session.open_home(); - } - - let event_loop: EventLoop = EventLoopBuilder::with_user_event().build(); - let proxy = event_loop.create_proxy(); - if let Some(primary) = primary { - let proxy = proxy.clone(); - primary.listen(move |launch| { - proxy - .send_event(UserEvent::OpenPaths(None, launch.paths, launch.edit)) - .is_ok() - }); - } - let initial_theme = load_theme_choice(); - - let title = initial_session - .active() - .and_then(|tab| tab.file_path()) - .and_then(|path| path.file_name()) - .map(|name| format!("{} — MD Preview", name.to_string_lossy())) - .unwrap_or_else(|| "MD Preview".to_string()); - - let geom = load_window_geom() - .filter(|g| geom_visible(g, &event_loop)) - .unwrap_or_else(|| centered_geom(&event_loop)); - - let mut window_builder = WindowBuilder::new() - .with_title(&title) - .with_inner_size(LogicalSize::new(geom.w, geom.h)) - .with_position(LogicalPosition::new(geom.x, geom.y)) - .with_theme(initial_theme.tao_theme()); - if let Some(icon) = load_window_icon() { - window_builder = window_builder.with_window_icon(Some(icon)); - } - let window = window_builder - .build(&event_loop) - .expect("failed to build window"); - let window_id = window.id(); - bench_log("window_built"); - let recent_files: Arc>> = Arc::new(Mutex::new(load_recent_files())); - - let initial_page = build_startup_page(&strings); - let initial_flags = EnhanceFlags::default(); - - let document_session = Arc::new(Mutex::new(initial_session)); - let enhance_flags: Arc> = Arc::new(Mutex::new(initial_flags)); - let last_self_write: Arc>> = Arc::new(Mutex::new(None)); - - // Windows: steer WebView2's cache/cookie tree into %LOCALAPPDATA% instead of - // letting it drop next to the exe. Other platforms: use default (None). - let data_dir: Option = { - let d = config_dir().join("WebView2"); - let _ = fs::create_dir_all(&d); - Some(d) - }; - let mut web_context = wry::WebContext::new(data_dir); - - let webview = match build_webview( - &window, - &mut web_context, - window_id, - Arc::clone(&document_session), - Arc::clone(&last_self_write), - Arc::clone(&recent_files), - proxy.clone(), - initial_page, - ) { - Ok(webview) => webview, - Err(error) => { - eprintln!("Could not initialize WebView: {error}"); - show_warning_dialog("Could Not Open MD Preview", &error); - return; - } - }; - bench_log("webview_built"); - // hljs + extra language packs aren't part of first-paint HTML anymore. - // We push them in via evaluate_script the moment the webview tells us - // it's painted (IPC 'ready'). Keeps ~125KB out of the HTML-parse critical - // path so the app window shows content faster on cold start. - let hljs_bootstrap = format!( - "(function(){{{hljs_js};{hljs_extra};try{{window.hljs=hljs;}}catch(e){{}}if(typeof hljs!=='undefined'&&hljs.highlightAll){{hljs.highlightAll();}}}})();", - hljs_js = HLJS_JS, - hljs_extra = HLJS_EXTRA_LANGS, - ); - - // File watcher state - let watcher_holder: Arc>> = Arc::new(Mutex::new(None)); - - let initial_dirty = document_session - .lock() - .unwrap() - .active() - .map(|tab| tab.dirty) - .unwrap_or(false); - let app = AppState { - windows: HashMap::from([( - window_id, - WindowState { - window, - webview, - session: Arc::clone(&document_session), - last_self_write: Arc::clone(&last_self_write), - watcher: Arc::clone(&watcher_holder), - enhance_flags: Arc::clone(&enhance_flags), - loaded_enhancers: EnhanceFlags::default(), - page_ready: false, - pending_launches: Vec::new(), - pending_close: false, - warned_external_change: None, - pending_external_change: None, - dirty: initial_dirty, - is_primary: true, - }, - )]), - active_window: window_id, - recent_files: Arc::clone(&recent_files), - strings, - web_context, - }; - - run_event_loop(event_loop, app, proxy, hljs_bootstrap, bench, t0); -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::app::{ - base_href_for_file, clamp_secondary_position, home_preview_html, set_content_script, - tabs_json, EnhanceFlags, Strings, - }; - use crate::config::{clamp_zoom, ThemeChoice}; - use crate::markdown::md_to_html_with_base; - use crate::testutil::temp_dir as temp_test_dir; - - #[test] - fn large_document_startup_stays_below_webview2_html_limit() { - let dir = temp_test_dir("startup-large"); - let file = dir.join("中文 large.md"); - fs::write(&file, "x".repeat(3 * 1024 * 1024)).unwrap(); - let mut session = DocumentSession::default(); - session.open(file, true); - let page = build_startup_page(&Strings::english()); - assert!( - page.len() < 2 * 1024 * 1024, - "startup HTML has {} bytes", - page.len() - ); - assert!(session.active().unwrap().editing); - fs::remove_dir_all(dir).unwrap(); - } - - #[test] - fn dollar_math_is_protected_from_markdown_escapes() { - let html = md_to_html(r"$\{x\}$"); - - assert!(html.contains(r#"\{x\}"#)); - } - - #[test] - fn dollar_math_is_protected_from_markdown_emphasis() { - let html = md_to_html(r"$\bar{\mu}_{n}$ and $x_{n}$"); - - assert!(html.contains(r#"\bar{\mu}_{n}"#)); - assert!(html.contains(r#"x_{n}"#)); - assert!(!html.contains("")); - } - - #[test] - fn multiline_display_math_is_not_split_by_hard_breaks() { - let html = md_to_html("$$\na + b\n$$"); - - assert!(html.contains(r#"class="math math-display""#), "{html}"); - assert!(html.contains("a + b"), "{html}"); - assert!(!html.contains("
"), "{html}"); - } - - #[test] - fn github_alerts_render_as_markdown_alert_blockquotes() { - let html = md_to_html("> [!IMPORTANT]\n> This is an alert"); - - assert!(html.contains(r#"
"#)); - assert!(html.contains("

This is an alert

")); - assert!(!html.contains("[!IMPORTANT]")); - } - - #[test] - fn soft_breaks_render_as_hard_breaks_in_paragraphs() { - let html = md_to_html("2.1 默认只读讨论。\n2.2 默认工作流:先读代码。"); - - assert!( - html.contains("2.1 默认只读讨论。
\n2.2 默认工作流"), - "{html}" - ); - } - - #[test] - fn blank_lines_still_create_paragraphs() { - let html = md_to_html("first line\n\nsecond line"); - - assert_eq!(html.matches("

").count(), 2, "{html}"); - assert!(!html.contains("
"), "{html}"); - } - - #[test] - fn soft_breaks_inside_headings_stay_soft() { - let html = md_to_html("First heading line\nsecond heading line\n==="); - - assert!(html.contains(""), "{html}"); - } - - #[test] - fn soft_breaks_in_list_items_become_hard_breaks() { - let html = md_to_html("- first line\n second line"); - - assert!(html.contains("

  • first line
    "), "{html}"); - assert!(html.contains("second line
  • "), "{html}"); - } - - #[test] - fn code_blocks_keep_newlines_without_br() { - let html = md_to_html("~~~text\nline one\nline two\n~~~"); - - assert!(!html.contains("
    "), "{html}"); - assert!(html.contains("line one\nline two"), "{html}"); - } - - #[test] - fn gfm_footnotes_render_reference_and_definition() { - let html = md_to_html("Text with a note[^1].\n\n[^1]: The footnote body."); - - assert!(html.contains(r#"class="footnote-reference""#), "{html}"); - assert!(html.contains(r#"class="footnote-definition""#), "{html}"); - assert!(html.contains("The footnote body."), "{html}"); - } - - #[test] - fn definition_lists_render_as_dl_dt_dd() { - let html = md_to_html("Term\n: Definition"); - - assert!(html.contains("
    "), "{html}"); - assert!(html.contains("
    Term
    "), "{html}"); - assert!(html.contains("
    Definition
    "), "{html}"); - } - - #[test] - fn utf8_bom_is_ignored_before_heading_and_front_matter() { - let heading = md_to_html("\u{feff}# BOM heading"); - assert!( - heading.contains(r#"

    BOM heading

    "#), - "{heading}" - ); - - let front_matter = md_to_html("\u{feff}---\ntitle: BOM\n---\n# Body"); - assert!( - front_matter.contains(r#"class="front-matter""#), - "{front_matter}" - ); - assert!(front_matter.contains("title: BOM"), "{front_matter}"); - assert!( - front_matter.contains(r#"

    Body

    "#), - "{front_matter}" - ); - } - - #[test] - fn double_equals_highlight_renders_mark_without_touching_code() { - let html = md_to_html("Use ==highlight & tag== here and `==literal==` there."); - - assert!(html.contains(r#"Use highlight & tag here"#)); - assert!(html.contains("==literal==")); - } - - #[test] - fn fenced_code_blocks_keep_double_equals_literal() { - let html = md_to_html("```csharp\nif (m_Profile == null) {\n return a == b;\n}\n```"); - - assert!( - html.contains("m_Profile == null"), - "comparison must stay literal" - ); - assert!( - html.contains("a == b"), - "every comparison must be preserved" - ); - assert!( - !html.contains("mdp-mark"), - "code blocks must not get highlight markup" - ); - } - - #[test] - fn base_href_is_a_directory_file_url() { - let dir = temp_test_dir("base-href"); - let file = dir.join("note.md"); - fs::write(&file, "# x").unwrap(); - - let href = base_href_for_file(&file).unwrap(); - - assert!(href.starts_with("file:///"), "{href}"); - assert!(href.ends_with('/'), "{href}"); - assert!(!href.contains("%3F"), "{href}"); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn local_relative_images_are_embedded_from_markdown_directory() { - let dir = temp_test_dir("local-image"); - let assets = dir.join("assets"); - fs::create_dir_all(&assets).unwrap(); - fs::write(assets.join("pixel.png"), b"abc").unwrap(); - - let html = md_to_html_with_base("![pixel](assets/pixel.png)", Some(&dir)); - - assert!(html.contains(r#"pixel"#)); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn local_relative_images_keep_original_src_when_unreadable() { - let dir = temp_test_dir("missing-image"); - - let html = md_to_html_with_base("![missing](assets/missing.png)", Some(&dir)); - - assert!(html.contains(r#"missing"#)); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn local_relative_images_do_not_embed_parent_traversal() { - let dir = temp_test_dir("traversal-image"); - - let html = md_to_html_with_base("![secret](../secret.png)", Some(&dir)); - - assert!(html.contains(r#"secret"#)); - assert!(!html.contains("data:image/png")); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn yaml_front_matter_keeps_metadata_readable_without_blank_lines() { - let html = md_to_html( - "---\nname: skill-creator-lite\ndescription: Skill 创建封装工具。\n---\n# Body", - ); - - assert!(html.contains(r#"