refactor: move module tests into their files and startup into app::run
This commit is contained in:
789
src/main.rs
789
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::<Vec<_>>();
|
||||
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::<Vec<_>>();
|
||||
|
||||
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<UserEvent> = 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<Mutex<Vec<PathBuf>>> = 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<Mutex<EnhanceFlags>> = Arc::new(Mutex::new(initial_flags));
|
||||
let last_self_write: Arc<Mutex<Option<SelfWriteRecord>>> = 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<PathBuf> = {
|
||||
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<Mutex<Option<notify::RecommendedWatcher>>> = 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#"<span class="math math-inline">\{x\}</span>"#));
|
||||
}
|
||||
|
||||
#[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#"<span class="math math-inline">\bar{\mu}_{n}</span>"#));
|
||||
assert!(html.contains(r#"<span class="math math-inline">x_{n}</span>"#));
|
||||
assert!(!html.contains("<em>"));
|
||||
}
|
||||
|
||||
#[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("<br />"), "{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#"<blockquote class="markdown-alert-important">"#));
|
||||
assert!(html.contains("<p>This is an alert</p>"));
|
||||
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 默认只读讨论。<br />\n2.2 默认工作流"),
|
||||
"{html}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_lines_still_create_paragraphs() {
|
||||
let html = md_to_html("first line\n\nsecond line");
|
||||
|
||||
assert_eq!(html.matches("<p>").count(), 2, "{html}");
|
||||
assert!(!html.contains("<br />"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_breaks_inside_headings_stay_soft() {
|
||||
let html = md_to_html("First heading line\nsecond heading line\n===");
|
||||
|
||||
assert!(html.contains("<h1"), "{html}");
|
||||
assert!(!html.contains("<br />"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_breaks_in_list_items_become_hard_breaks() {
|
||||
let html = md_to_html("- first line\n second line");
|
||||
|
||||
assert!(html.contains("<li>first line<br />"), "{html}");
|
||||
assert!(html.contains("second line</li>"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_blocks_keep_newlines_without_br() {
|
||||
let html = md_to_html("~~~text\nline one\nline two\n~~~");
|
||||
|
||||
assert!(!html.contains("<br />"), "{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("<dl>"), "{html}");
|
||||
assert!(html.contains("<dt>Term</dt>"), "{html}");
|
||||
assert!(html.contains("<dd>Definition</dd>"), "{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#"<h1 id="bom-heading">BOM heading</h1>"#),
|
||||
"{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#"<h1 id="body">Body</h1>"#),
|
||||
"{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 <mark class="mdp-mark">highlight & tag</mark> here"#));
|
||||
assert!(html.contains("<code>==literal==</code>"));
|
||||
}
|
||||
|
||||
#[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("", Some(&dir));
|
||||
|
||||
assert!(html.contains(r#"<img src="data:image/png;base64,YWJj" alt="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("", Some(&dir));
|
||||
|
||||
assert!(html.contains(r#"<img src="assets/missing.png" alt="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("", Some(&dir));
|
||||
|
||||
assert!(html.contains(r#"<img src="../secret.png" alt="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#"<aside class="front-matter">"#));
|
||||
assert!(html.contains("name: skill-creator-lite"));
|
||||
assert!(html.contains("description: Skill 创建封装工具。"));
|
||||
assert!(html.contains("<h1 id=\"body\">Body</h1>"));
|
||||
assert!(!html.contains("<h2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yaml_front_matter_accepts_dots_and_escapes_html() {
|
||||
let html = md_to_html("---\ntitle: <script>alert(1)</script>\n...\nParagraph");
|
||||
|
||||
assert!(html.contains("title: <script>alert(1)</script>"));
|
||||
assert!(!html.contains("<script>alert(1)</script>"));
|
||||
assert!(html.contains("<p>Paragraph</p>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizontal_rules_and_setext_headings_are_not_front_matter() {
|
||||
let html = md_to_html("Title\n---\n\nParagraph\n\n---");
|
||||
|
||||
assert!(!html.contains(r#"<aside class="front-matter">"#));
|
||||
assert!(html.contains(r#"<h2 id="title">Title</h2>"#));
|
||||
assert!(html.contains("<hr />"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_heading_ids_support_cjk_anchor_links() {
|
||||
let html = md_to_html("1. [需求概述](#需求概述)\n\n## 需求概述");
|
||||
|
||||
assert!(html.contains(r##"<a href="#%E9%9C%80%E6%B1%82%E6%A6%82%E8%BF%B0">需求概述</a>"##));
|
||||
assert!(html.contains(r#"<h2 id="需求概述">需求概述</h2>"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_heading_ids_are_unique_and_keep_explicit_ids() {
|
||||
let html = md_to_html("## Intro\n## Intro\n## Custom {#fixed}\n## Fixed");
|
||||
|
||||
assert!(html.contains(r#"<h2 id="intro">Intro</h2>"#));
|
||||
assert!(html.contains(r#"<h2 id="intro-1">Intro</h2>"#));
|
||||
assert!(html.contains(r#"<h2 id="fixed">Custom</h2>"#));
|
||||
assert!(html.contains(r#"<h2 id="fixed-1">Fixed</h2>"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_flags_are_recognized() {
|
||||
assert!(is_help_arg("-h"));
|
||||
assert!(is_help_arg("--help"));
|
||||
assert!(!is_help_arg("--edit"));
|
||||
}
|
||||
|
||||
#[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 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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_blocks_native_preview_reload_paths() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# Hello"),
|
||||
"# Hello",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
|
||||
assert!(page.contains("document.addEventListener('contextmenu'"));
|
||||
assert!(page.contains("window.ipc.postMessage('refresh')"));
|
||||
assert!(!page.contains("id=\"btn-open\""));
|
||||
assert!(!page.contains("id=\"btn-print\""));
|
||||
assert!(!page.contains("id=\"btn-search\""));
|
||||
assert!(page.contains("window.ipc.postMessage('open')"));
|
||||
assert!(page.contains("window.__mdPreviewOpenFile = openFile"));
|
||||
assert!(page.contains("window.__mdPreviewShowFind = showFind"));
|
||||
assert!(page.contains("window.__mdPreviewToggleEdit"));
|
||||
assert!(page.contains("function selectionSeed()"));
|
||||
assert!(page.contains("showFind(seed ? seed.text : ''"));
|
||||
assert!(page.contains("function findStartIndex(anchorTop)"));
|
||||
assert!(page.contains("return lastAbove >= 0 ? lastAbove : 0"));
|
||||
assert!(page.contains("findInput.focus({ preventScroll: true })"));
|
||||
assert!(page.contains("selectFindHit(findStartIndex(anchorTop), reveal)"));
|
||||
assert!(page.contains("runFindQuery(seed, anchorTop, false)"));
|
||||
assert!(page.contains("var INDENT = ' ';"));
|
||||
assert!(page.contains("insertNewlineWithIndent"));
|
||||
assert!(page.contains("document.execCommand('insertText'"));
|
||||
assert!(page.contains("id=\"hljs-code\""));
|
||||
assert!(page.contains("#preview pre { background: #1e1e1e;"));
|
||||
assert!(!page.contains("hljs-light"));
|
||||
assert!(page.contains("ta.focus({ preventScroll: true })"));
|
||||
assert!(page.contains("window.__setEmptyPreview"));
|
||||
assert!(page.contains("id=\"tabbar\""));
|
||||
assert!(page.contains("window.__setTabs"));
|
||||
assert!(page.contains("tab-action:'));") || page.contains("'tab-action:' + action"));
|
||||
assert!(page.contains("window.__markSaved"));
|
||||
assert!(
|
||||
!page.contains("window.ipc.postMessage('save:' + ta.value);\n\t setDirty(false);")
|
||||
);
|
||||
assert!(page.contains("compositionstart"));
|
||||
assert!(page.contains("e.isComposing"));
|
||||
assert!(page.contains("focusFindInput"));
|
||||
assert!(page.contains("FIND_DEBOUNCE_MS = 300"));
|
||||
assert!(page.contains("document.createTreeWalker(previewEl, NodeFilter.SHOW_TEXT"));
|
||||
assert!(page.contains("mark.className = 'search-hit'"));
|
||||
assert!(page.contains("selectFindHit(currentFindHit + (backward ? -1 : 1))"));
|
||||
assert!(page.contains("#preview mark.search-hit.current"));
|
||||
assert!(page.contains("restoreFindInput(selectionStart, selectionEnd)"));
|
||||
assert!(page.contains("findInput.setSelectionRange(selectionStart, selectionEnd)"));
|
||||
assert!(page.contains("bindAnchorNavigation"));
|
||||
assert!(page.contains("event.target.closest('#preview a[href]')"));
|
||||
assert!(page.contains("window.ipc.postMessage('open-local-link:' + href)"));
|
||||
assert!(page.contains(".markdown-alert-important"));
|
||||
assert!(page.contains(".markdown-alert-title"));
|
||||
let light_alert = page.find("background: #dafbe1").unwrap();
|
||||
let dark_alert = page.rfind("background: #161b22; color: #d4d4d4").unwrap();
|
||||
assert!(dark_alert > light_alert);
|
||||
assert!(page.contains(".mdp-mark"));
|
||||
assert!(!page.contains("Local-first Markdown preview for AI-generated docs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_separates_new_file_from_open_and_debounces_autosave() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# Hello"),
|
||||
"# Hello",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
|
||||
assert!(page.contains("window.ipc.postMessage('new-file')"));
|
||||
assert!(page.contains("tabOpen.addEventListener('click', newTab)"));
|
||||
assert!(!page.contains("tabOpen.addEventListener('click', newFile)"));
|
||||
assert!(!page.contains("tabOpen.addEventListener('click', openFile)"));
|
||||
assert!(page.contains("requestTabAction('new-tab', 0)"));
|
||||
assert!(page.contains("data-new-file"));
|
||||
assert!(page.contains("HIDE_SINGLE_HOME_TAB = true"));
|
||||
assert!(page.contains("tabs.length === 1 && !tabs[0].home"));
|
||||
assert!(page.contains("L_HOME = 'New Tab'"));
|
||||
assert!(
|
||||
page.matches("if (document.body.classList.contains('home')) return;")
|
||||
.count()
|
||||
>= 2
|
||||
);
|
||||
assert!(page.contains("if (tabCount === 1 && isHome) close.hidden = true"));
|
||||
assert!(page.contains("tabMenuNewWindow.disabled = tabCount <= 1 || isHome"));
|
||||
assert!(page.contains("AUTOSAVE_DEBOUNCE_MS = 700"));
|
||||
assert!(page.contains("pendingAutosaveTimer = setTimeout"));
|
||||
assert!(page.contains("window.__markSaved = function(savedRaw)"));
|
||||
assert!(page.contains("window.__markSaveBlocked"));
|
||||
assert!(page.contains("var saveBlocked = false"));
|
||||
assert!(page.contains("window.__mdPreviewCannotSave"));
|
||||
assert!(page.contains("window.__mdPreviewResolveExternalChange"));
|
||||
assert!(page.contains("'external-change:' + (dirty ? 'dirty' : 'clean')"));
|
||||
assert!(page.contains("(e.key === 'n' || e.key === 'N')"));
|
||||
assert!(page.contains("id=\"doc-stats\""));
|
||||
assert!(page.contains("id=\"tab-menu\""));
|
||||
assert!(page.contains("id=\"tab-menu-path\""));
|
||||
assert!(page.contains("id=\"tab-menu-reveal\""));
|
||||
assert!(page.contains("data-tab-path"));
|
||||
assert!(page.contains("function shortenPath"));
|
||||
assert!(page.contains("tabsEl.addEventListener('pointerdown'"));
|
||||
assert!(page.contains("suppressTabClickUntil"));
|
||||
assert!(page.contains("tabCount = tabs.length"));
|
||||
assert!(page.contains("tabMenuNewWindow.disabled = tabCount <= 1"));
|
||||
assert!(page.contains("updateDocumentStats"));
|
||||
assert!(page.contains("restoreScrollProgress"));
|
||||
assert!(page.contains("postMessage('scroll:' + activeTabId"));
|
||||
assert!(page.contains("setEditMode(!!editing)"));
|
||||
assert!(page.contains("postMessage('edit-mode:' + activeTabId"));
|
||||
assert!(page.contains("postMessage('zoom:' + zoomPercent)"));
|
||||
assert!(page.contains("window.__mdPreviewSetZoom"));
|
||||
assert!(page.contains("id=\"btn-zoom-in\""));
|
||||
assert!(page.contains("id=\"btn-zoom-out\""));
|
||||
assert!(page.contains("id=\"btn-zoom-reset\""));
|
||||
assert!(page.contains("var ZOOM_MIN = 50"));
|
||||
assert!(page.contains("var ZOOM_MAX = 300"));
|
||||
assert!(page.contains("var ZOOM_STEP = 5"));
|
||||
assert!(page.contains("ZOOM_WHEEL_THROTTLE_MS = 90"));
|
||||
assert!(page.contains("if (!e.ctrlKey) return;"));
|
||||
assert!(
|
||||
page.contains("window.addEventListener('wheel', onContentWheel, { passive: false })")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headings_get_hover_fold_toggles() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# A\n\n## B\n\ntext"),
|
||||
"# A\n\n## B\n\ntext",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
|
||||
assert!(page.contains("mdp-fold-toggle"));
|
||||
assert!(page.contains("mdp-fold-body"));
|
||||
assert!(page.contains(".mdp-fold.collapsed > .mdp-fold-body { display: none; }"));
|
||||
assert!(page.contains("window.__mdPreviewFoldLabel"));
|
||||
assert!(page.contains("window.__mdPreviewExpandFold"));
|
||||
assert!(page.contains("sectionizeFolds"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_content_script_matches_the_page_signature() {
|
||||
let script = set_content_script(
|
||||
"<p>x</p>",
|
||||
"# x",
|
||||
"file:///D:/tmp/",
|
||||
EnhanceFlags {
|
||||
math: true,
|
||||
mermaid: false,
|
||||
},
|
||||
true,
|
||||
0.25,
|
||||
);
|
||||
assert_eq!(
|
||||
script,
|
||||
"if(window.__setContent)window.__setContent('<p>x</p>', '# 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 closing_the_last_editing_tab_restores_the_empty_preview() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("# Hello"),
|
||||
"# Hello",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
let empty_start = page.find("window.__setEmptyPreview = function").unwrap();
|
||||
let missing_start = page.find("window.__setMissing = function").unwrap();
|
||||
let empty_handler = &page[empty_start..missing_start];
|
||||
|
||||
assert!(empty_handler.contains("document.body.classList.add('home')"));
|
||||
assert!(empty_handler.contains("setEditMode(false)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_expands_multi_column_tables() {
|
||||
let strings = Strings::english();
|
||||
let page = build_page(
|
||||
&md_to_html("| A | B | C | D |\n|---|---|---|---|\n| 1 | 2 | 3 | 4 |"),
|
||||
"",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
false,
|
||||
);
|
||||
|
||||
assert!(page.contains("mdp-table-wrap"));
|
||||
assert!(page.contains("width: min(calc(100vw - 64px), 1280px)"));
|
||||
assert!(page.contains("if(window.__enhancePreview)window.__enhancePreview();"));
|
||||
}
|
||||
|
||||
#[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#"<div class="empty has-recent">"#));
|
||||
assert!(html.contains(r#"<div class="icon">#</div>"#));
|
||||
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("<body class=\"home\">"));
|
||||
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}");
|
||||
}
|
||||
app::run();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user