// Rendering appends explicit newlines to keep the generated HTML readable; // the `write_with_newline` style lint is therefore not useful here. #![allow(clippy::write_with_newline)] #![allow(clippy::type_complexity)] //! The one ReaderRenderer. //! //! Live and Export both call `render()`; the only difference is `LinkPolicy` //! and whether interactive controls are available (RFC-VIEW-0001 §14.3). //! Markdown is serialized here from the View-owned `DocBlock` tree, with raw //! HTML omitted by default and every URL scheme sanitized. use crate::assets::AssetBundle; use crate::document::{DocBlock, Inline, TableAlign}; use crate::presentation::{anchor_for_span, PresentationModel}; use crate::project::SafeRelativePath; use crate::semantic::{source_id, UnitKind}; use crate::source_map::SourceSpan; use std::fmt::Write as _; /// How links to other documents are resolved. This is the only Live/Export /// difference in rendered content. #[derive(Debug, Clone)] pub enum LinkPolicy { /// `GET /file?path=` on the local server. LocalServer, /// Relative links from a static page at `page_depth` directories below the /// site root (`0` for `index.html`). StaticRelative { page_depth: usize }, } impl LinkPolicy { pub fn document_href(&self, current: &SafeRelativePath, target: &SafeRelativePath) -> String { match self { LinkPolicy::LocalServer => { format!("/file?path={}", percent_encode_path(target.as_str())) } LinkPolicy::StaticRelative { page_depth } => { let _ = current; let mut prefix = String::new(); for _ in 0..*page_depth { prefix.push_str("../"); } format!("{prefix}pages/{}.html", target.as_str()) } } } fn asset_prefix(&self, page_depth: usize) -> String { match self { LinkPolicy::LocalServer => "/assets/".to_string(), LinkPolicy::StaticRelative { .. } => { let mut prefix = String::new(); for _ in 0..page_depth { prefix.push_str("../"); } format!("{prefix}assets/") } } } } /// Everything the renderer needs beyond the model. #[derive(Debug, Clone)] pub struct RenderContext { pub links: LinkPolicy, pub live: bool, pub csrf_token: Option, /// Whether a Run control may be shown as available. False until the /// explicit-run flow exists; the button then explains that it is disabled. pub run_available: bool, } impl RenderContext { pub fn live() -> Self { Self { links: LinkPolicy::LocalServer, live: true, csrf_token: None, run_available: false, } } pub fn static_site(page_depth: usize) -> Self { Self { links: LinkPolicy::StaticRelative { page_depth }, live: false, csrf_token: None, run_available: false, } } } pub struct RenderedPage { pub html: String, /// Asset hashed names actually referenced by the page. pub assets_used: Vec, } pub struct ReaderRenderer { assets: &'static AssetBundle, } impl ReaderRenderer { pub fn new() -> Self { Self { assets: AssetBundle::get(), } } pub fn render(&self, model: &PresentationModel, ctx: &RenderContext) -> RenderedPage { let asset_prefix = ctx.links.asset_prefix(match ctx.links { LinkPolicy::StaticRelative { page_depth } => page_depth, LinkPolicy::LocalServer => 0, }); let css_name = self.assets.hashed_css_name(); let js_name = self.assets.hashed_js_name(); let logo_uri = self.assets.logo().data_uri(); let navigation = &model.navigation; let document_href = format!( "{prefix}reader.{hash}.css", prefix = asset_prefix, hash = &self.assets.css_served_sha256()[..16] ); let _ = document_href; let mut html = String::with_capacity(16 * 1024 + model.document.source.len()); let page_title = if navigation.site_title.is_empty() { model.title.clone() } else { format!("{} · {}", model.title, navigation.site_title) }; let _ = write!( html, r##" {title} 跳到正文 "##, presentation_version = model.version, view_version = env!("CARGO_PKG_VERSION"), csp = csp_policy(), title = escape_text(&page_title), logo = escape_attr(&logo_uri), css = escape_attr(&format!("{asset_prefix}{css_name}")), js = escape_attr(&format!("{asset_prefix}{js_name}")), status = model.source_status.data_value(), live = if ctx.live { "true" } else { "false" }, ); self.render_topbar(&mut html, model, ctx, navigation); self.render_ornament(&mut html); let _ = write!(html, "
\n"); if navigation.welcome { self.render_welcome(&mut html, navigation); } self.render_document_meta(&mut html, model); self.render_diagnostics(&mut html, model); self.render_functions(&mut html, model); self.render_document(&mut html, model, ctx); self.render_source_pane(&mut html, model, ctx); self.render_footer(&mut html, model); let _ = write!(html, "
\n"); self.render_dock(&mut html, ctx); self.render_toast(&mut html); self.render_dialogs(&mut html, model, ctx); html.push_str("\n\n"); RenderedPage { html, assets_used: vec![css_name, js_name], } } fn render_topbar( &self, html: &mut String, model: &PresentationModel, _ctx: &RenderContext, navigation: &crate::presentation::Navigation, ) { let active = model .navigation .active .as_ref() .map(|path| path.as_str()) .unwrap_or(""); let files_count = navigation.documents.len(); let _ = write!( html, r##"
{site_title}EXECUTABLE KNOWLEDGE
"##, menu_icon = icon("M4 6h16M4 12h16M4 18h16"), site_title = escape_text(&navigation.site_title), logo = escape_attr(&self.assets.logo().data_uri()), search_icon = icon("M21 21l-5-5M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0"), run_disabled = if _ctx.run_available { "false" } else { "true" }, run_title = if _ctx.run_available { "运行文档(需要确认)" } else { "运行入口尚未启用;当前版本不会执行文档" }, ); let _ = (files_count, active); } fn render_ornament(&self, html: &mut String) { html.push_str( "
\n", ); } fn render_welcome(&self, html: &mut String, navigation: &crate::presentation::Navigation) { let _ = write!( html, r##"

WELCOME TO

{title}

代码即文档 · 文档即知识库 · 知识即可执行

"##, title = escape_text(&navigation.site_title) ); } fn render_document_meta(&self, html: &mut String, model: &PresentationModel) { let status = model.source_status; let _ = write!( html, r##"
{file} {label} "##, file = escape_text(&model.document.identity.relative_path), status_value = status.data_value(), label = escape_text(status.label()), ); if let Some(projection) = &model.semantic { if !projection.imports.is_empty() { html.push_str("
    \n"); for import in &projection.imports { let _ = write!( html, "
  • {alias} → {target}
  • \n", alias = escape_text(&import.alias), target = escape_text(&import.target) ); } html.push_str("
\n"); } } html.push_str("
\n"); if let Some(note) = &model.status_note { let _ = write!( html, "

{note}

\n", note = escape_text(note) ); } } fn render_diagnostics(&self, html: &mut String, model: &PresentationModel) { let mut items: Vec<(&str, &str, Option, Option, &str)> = Vec::new(); for diagnostic in &model.diagnostics { items.push(( &diagnostic.severity, &diagnostic.code, diagnostic.line, diagnostic.column, &diagnostic.message, )); } for warning in &model.warnings { let (line, column) = warning .span .map(|span| model.document.source_index.line_col(span.start as usize)) .map(|(line, column)| (Some(line as u64), Some(column as u64))) .unwrap_or((None, None)); items.push(("warning", &warning.code, line, column, &warning.message)); } if items.is_empty() { return; } let has_error = items.iter().any(|item| item.0 == "error"); let open = if has_error { " open" } else { "" }; let _ = write!( html, "
\n{count} 条诊断(Core 与 View 来源已区分)\n
    \n", severity = if has_error { "error" } else { "warning" }, open = open, count = items.len() ); for (severity, code, line, column, message) in items { let _ = write!( html, "
  1. {code}{loc}{message}
  2. \n", severity = escape_attr(severity), code = escape_text(code), loc = match (line, column) { (Some(line), Some(column)) => format!( "第 {line} 行第 {column} 列" ), _ => String::new(), }, message = escape_text(message) ); } html.push_str("
\n
\n"); } fn render_functions(&self, html: &mut String, model: &PresentationModel) { if model.outline.is_empty() { return; } let functions: Vec<_> = model.functions().collect(); if functions.is_empty() { return; } let _ = write!( html, "
\n本文函数({count})\n
    \n", count = functions.len() ); for entry in functions { let _ = write!( html, "
  • {label}{detail}
  • \n", anchor = escape_attr(&entry.anchor), label = escape_text(&entry.label), detail = escape_text(&entry.detail) ); } html.push_str("
\n
\n"); } fn render_document(&self, html: &mut String, model: &PresentationModel, ctx: &RenderContext) { html.push_str("
\n"); let current = SafeRelativePath::parse(&model.document.identity.relative_path).ok(); match ¤t { Some(current) => { render_blocks( html, &model.document.blocks, model, ctx, current, self.assets, ); } None => { let _ = write!( html, "

相对路径无效,已进入纯文本阅读模式。

\n" ); } } html.push_str("
\n"); } fn render_source_pane( &self, html: &mut String, model: &PresentationModel, _ctx: &RenderContext, ) { let source = &model.document.source; html.push_str("
\n
    \n"); if source.is_empty() { html.push_str("
  1. (空文件)
  2. \n"); } let index = &model.document.source_index; for line in 1..=index.line_count() { let text = index.line_text(source, line).unwrap_or(""); let _ = write!( html, "
  3. {line}{text}
  4. \n", line = line, text = escape_text(text) ); } html.push_str("
\n
\n"); // Exact bytes for the copy action (never interpreted as markup). let _ = write!( html, "\n", escape_text(source) ); } fn render_footer(&self, html: &mut String, model: &PresentationModel) { let core = model .core_version .clone() .unwrap_or_else(|| "core unavailable".to_string()); let _ = write!( html, r##"
Marqdo · 静态阅读 Analysis v2 · Trace v2 · {core} 默认不执行 · 无自动运行
"##, core = escape_text(&core) ); } fn render_dock(&self, html: &mut String, ctx: &RenderContext) { let run_disabled = if ctx.run_available { "" } else { " data-disabled=\"true\"" }; let _ = write!( html, r##" "##, reload = icon("M20 7V3l-3 3a8 8 0 1 0 2 11M20 3h-5"), settings = icon("M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M5 19l2-2M17 7l2-2"), play = icon("m9 5 11 7-11 7z"), clear = icon("m14 3 4 2-4 8M5 12l8 2 2 6H3zM7 15l-1 4M10 16l-1 4"), more = icon("M5 12h.01M12 12h.01M19 12h.01"), run_disabled = run_disabled ); } fn render_toast(&self, html: &mut String) { html.push_str("\n"); } fn render_dialogs(&self, html: &mut String, model: &PresentationModel, ctx: &RenderContext) { let csrf = ctx .csrf_token .as_deref() .map(|token| { format!( "", escape_attr(token) ) }) .unwrap_or_default(); let _ = write!( html, r##"{csrf}

搜索当前文档

    阅读设置

    文件与更多

    {files}

    函数与知识单元

    当前版本不支持

    关于 Marqdo View

    版本 {view_version} · Tool Protocol v1 · Analysis v2 · Trace v2。

    冻结核心:{core}。

    本页面只渲染原始 Markdown 与已校验的静态语义;打开、刷新、搜索、导出都不会执行文档。运行需要用户显式确认。

    "##, csrf = csrf, files = self.render_file_list(model, ctx), view_version = env!("CARGO_PKG_VERSION"), core = escape_text(model.core_version.as_deref().unwrap_or("未检测到可用核心")), ); } fn render_file_list(&self, model: &PresentationModel, ctx: &RenderContext) -> String { if model.navigation.documents.len() <= 1 { return String::new(); } let Ok(current) = SafeRelativePath::parse(&model.document.identity.relative_path) else { return String::new(); }; let mut out = String::from( "
    项目内文档
      \n", ); for document in &model.navigation.documents { let href = ctx.links.document_href(¤t, document); let active = model .navigation .active .as_ref() .map(|active| active == document) .unwrap_or(false); let _ = write!( out, "
    • {name}
    • \n", if active { " aria-current=\"page\"" } else { "" }, href = escape_attr(&href), name = escape_text(document.as_str()) ); } out.push_str("
    \n"); out } } impl Default for ReaderRenderer { fn default() -> Self { Self::new() } } fn render_blocks( html: &mut String, blocks: &[DocBlock], model: &PresentationModel, ctx: &RenderContext, current: &SafeRelativePath, assets: &AssetBundle, ) { for block in blocks { render_block(html, block, model, ctx, current, assets); } } fn render_block( html: &mut String, block: &DocBlock, model: &PresentationModel, ctx: &RenderContext, current: &SafeRelativePath, assets: &AssetBundle, ) { match block { DocBlock::Heading { level, span, content, } => { let unit = resolve_heading_unit(model, *span, *level); let anchor = anchor_for_span(span.start, span.end); let (badge, cleaned) = display_heading_content(content, unit); let data_semantic = if let Some((_, data)) = badge { data } else if let Some(unit) = unit { match unit.kind { UnitKind::Function => "exec", UnitKind::Knowledge => "knowledge", _ => "document", } } else { "document" }; let _ = write!( html, "", level, escape_attr(&anchor), source_id_id(model, *span), data_semantic, ); if let Some(badge) = badge { let _ = write!( html, "{}", badge.1, badge.0 ); } render_inlines(html, &cleaned, model, ctx, current, assets); let _ = write!(html, "\n"); } DocBlock::Paragraph { content, .. } => { html.push_str("

    "); render_inlines(html, content, model, ctx, current, assets); html.push_str("

    \n"); } DocBlock::List { ordered, start, tight: _, items, .. } => { if *ordered { match start { Some(start) if *start != 1 => { let _ = write!(html, "
      \n"); } _ => html.push_str("
        \n"), } } else { html.push_str("
          \n"); } for item in items { if let DocBlock::ListItem { task, children, .. } = item { html.push_str("
        • "); if let Some(checked) = task { let _ = write!( html, "", checked = checked, label = if *checked { "已完成" } else { "未完成" } ); } if let Some(first) = children.first() { if let DocBlock::Paragraph { content, .. } = first { render_inlines(html, content, model, ctx, current, assets); for child in &children[1..] { render_block(html, child, model, ctx, current, assets); } } else { for child in children { render_block(html, child, model, ctx, current, assets); } } } html.push_str("
        • \n"); } } html.push_str(if *ordered { "
      \n" } else { "\n" }); } DocBlock::ListItem { children, .. } => { html.push_str("
    1. "); for child in children { render_block(html, child, model, ctx, current, assets); } html.push_str("
    2. \n"); } DocBlock::BlockQuote { children, .. } => { html.push_str("
      \n"); render_blocks(html, children, model, ctx, current, assets); html.push_str("
      \n"); } DocBlock::CodeBlock { span, info, literal, } => { let resource = model .semantic .as_ref() .and_then(|projection| projection.resource_for_span(*span)); let language = info.split_whitespace().next().unwrap_or(""); let _ = write!( html, "
      ", resource .map(|resource| format!( " data-source-id=\"{}\"", escape_attr(&source_id( &model.document.identity.module_id, resource.span, "resource-code" )) )) .unwrap_or_default() ); if !language.is_empty() { let _ = write!( html, "{}", escape_text(language) ); } let _ = write!( html, "
      {}
      \n", escape_text(literal) ); } DocBlock::Table { alignments, header, rows, .. } => { html.push_str("
      \n"); if !header.is_empty() { html.push_str(""); for (index, cell) in header.iter().enumerate() { let align = alignments.get(index).copied().unwrap_or(TableAlign::None); let _ = write!(html, "", align_attr(align)); render_inlines(html, cell, model, ctx, current, assets); html.push_str(""); } html.push_str("\n"); } if !rows.is_empty() { html.push_str("\n"); for row in rows { html.push_str(""); for (index, cell) in row.iter().enumerate() { let align = alignments.get(index).copied().unwrap_or(TableAlign::None); let _ = write!(html, "", align_attr(align)); render_inlines(html, cell, model, ctx, current, assets); html.push_str(""); } html.push_str("\n"); } html.push_str("\n"); } html.push_str("
      \n"); } DocBlock::MathBlock { span, literal } => { let _ = write!( html, "
      {}公式原文 · 未渲染数学
      \n", escape_attr(&source_id( &model.document.identity.module_id, *span, "resource-formula" )), escape_text(literal) ); } DocBlock::ThematicBreak { .. } => html.push_str("
      \n"), DocBlock::HtmlBlock { .. } => { html.push_str( "
      已忽略原始 HTML 内容(安全默认)。源码态可查看原文。
      \n", ); } DocBlock::Other { .. } => {} } } fn resolve_heading_unit( model: &PresentationModel, heading_span: SourceSpan, level: u8, ) -> Option<&crate::semantic::SemanticUnit> { let projection = model.semantic.as_ref()?; // A function heading maps to its function unit exactly; never borrow the // ancestor function for H3/H4 sections (that would duplicate DOM ids). if let Some(function) = projection .functions .iter() .find(|function| function.heading_span == heading_span) { if let Some(unit) = projection .units .iter() .find(|unit| unit.id == function.unit_id) { return Some(unit); } } projection .units .iter() .filter(|unit| unit.level == level && unit.span == heading_span) .min_by_key(|unit| unit.span.len()) .or_else(|| projection.unit_for_heading(heading_span, level)) } fn display_heading_content( content: &[Inline], unit: Option<&crate::semantic::SemanticUnit>, ) -> (Option<(&'static str, &'static str)>, Vec) { let Some(unit) = unit else { return (None, content.to_vec()); }; let plain: String = content.iter().map(Inline::plain_text).collect(); for (prefix, badge, data) in [ ("@exec ", "EXEC", "exec"), ("@knowledge ", "KNOWLEDGE", "knowledge"), ] { if let Some(rest) = plain.strip_prefix(prefix) { if normalize_heading_name(rest) == unit.name { return ( Some((badge, data)), strip_prefix_from_inlines(content, prefix), ); } } } (None, content.to_vec()) } fn normalize_heading_name(raw: &str) -> String { // Name comparison here is only a display heuristic; the Core already // decided the semantic name. Collapse whitespace and trim. raw.split_whitespace().collect::>().join(" ") } fn strip_prefix_from_inlines(content: &[Inline], prefix: &str) -> Vec { let mut remaining = prefix.len(); let mut out = Vec::new(); for inline in content { if remaining == 0 { out.push(inline.clone()); continue; } match inline { Inline::Text { span, literal } => { if remaining >= literal.len() { remaining -= literal.len(); } else { let cut = remaining; remaining = 0; let rest = &literal[cut..]; if !rest.is_empty() { out.push(Inline::Text { span: *span, literal: rest.to_string(), }); } } } other => { remaining = 0; out.push(other.clone()); } } } out } fn render_inlines( html: &mut String, inlines: &[Inline], model: &PresentationModel, ctx: &RenderContext, current: &SafeRelativePath, assets: &AssetBundle, ) { let _ = assets; for inline in inlines { render_inline(html, inline, model, ctx, current); } } fn render_inline( html: &mut String, inline: &Inline, model: &PresentationModel, ctx: &RenderContext, current: &SafeRelativePath, ) { let projection = model.semantic.as_ref(); match inline { Inline::Text { span, literal } => { // A text node can itself be the payload of an inline code carrier; // anchors are applied by the enclosing carrier branch below. let _ = span; html.push_str(&escape_text(literal)); } Inline::Code { span, literal, ticks: _, } => { let anchor = projection.and_then(|projection| projection.statement_for_inline(*span)); html.push_str("'); html.push_str(&escape_text(literal)); html.push_str(""); } Inline::Strong { span, children } => { let anchor = projection.and_then(|projection| projection.statement_for_inline(*span)); html.push_str("'); render_inlines(html, children, model, ctx, current, assets_placeholder()); html.push_str(""); } Inline::Emph { span, children } => { let anchor = projection.and_then(|projection| projection.statement_for_inline(*span)); html.push_str("'); render_inlines(html, children, model, ctx, current, assets_placeholder()); html.push_str(""); } Inline::Strikethrough { children, .. } => { html.push_str(""); render_inlines(html, children, model, ctx, current, assets_placeholder()); html.push_str(""); } Inline::Link { span, url, title, children, } => { let reference = projection.and_then(|projection| projection.reference_for_span(*span)); let state = reference.map(|reference| reference.state.as_str()); let target = resolve_link(url, current, &ctx.links); match target { Some(href) => { let _ = write!(html, "'); render_inlines(html, children, model, ctx, current, assets_placeholder()); html.push_str(""); } None => { html.push_str( "", ); render_inlines(html, children, model, ctx, current, assets_placeholder()); html.push_str(""); } } } Inline::Image { url, alt, title, .. } => { // Remote or unverified images are never loaded implicitly. let _ = (url, title); let _ = write!( html, "[图片已阻止自动加载:{}]", escape_text(if alt.is_empty() { "无替代文本" } else { alt }) ); } Inline::Math { span, literal, display, } => { let resource = projection.and_then(|projection| projection.resource_for_span(*span)); let _ = write!( html, "{}", resource .map(|resource| format!( " data-source-id=\"{}\"", escape_attr(&source_id( &model.document.identity.module_id, resource.span, "resource-formula" )) )) .unwrap_or_default(), escape_text(literal) ); let _ = display; } Inline::HtmlInline { .. } => { html.push_str("已忽略原始行内 HTML"); } Inline::SoftBreak { .. } => html.push(' '), Inline::LineBreak { .. } => html.push_str("
      "), Inline::Other { .. } => {} } } // The renderer is a struct method in the hot path; this helper keeps the // recursive inline signature small without a second renderer. fn assets_placeholder() -> &'static AssetBundle { AssetBundle::get() } fn align_attr(align: TableAlign) -> &'static str { match align { TableAlign::None => "", TableAlign::Left => " style=\"text-align:left\"", TableAlign::Center => " style=\"text-align:center\"", TableAlign::Right => " style=\"text-align:right\"", } } fn icon(path: &str) -> String { format!( "" ) } fn source_id_id(model: &PresentationModel, span: SourceSpan) -> String { escape_attr(&source_id( &model.document.identity.module_id, span, "heading", )) } fn escape_text(raw: &str) -> String { let mut out = String::with_capacity(raw.len() + 8); for ch in raw.chars() { match ch { '&' => out.push_str("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), '\'' => out.push_str("'"), _ => out.push(ch), } } out } fn escape_attr(raw: &str) -> String { escape_text(raw) } fn csp_policy() -> &'static str { "default-src 'none'; style-src 'self'; script-src 'self' file:; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; object-src 'none'" } fn percent_encode_path(raw: &str) -> String { let mut out = String::with_capacity(raw.len()); for byte in raw.as_bytes() { let unreserved = byte.is_ascii_alphanumeric() || matches!(*byte, b'-' | b'_' | b'.' | b'~' | b'/'); if unreserved { out.push(*byte as char); } else { use std::fmt::Write as _; let _ = write!(out, "%{byte:02X}"); } } out } /// Sanitize one Markdown link destination. Returns `None` for schemes the /// reader must never expose (`javascript:`, `data:`, `file:`, ...) and for /// console-control-looking payloads. fn resolve_link(raw: &str, current: &SafeRelativePath, policy: &LinkPolicy) -> Option { let url = raw.trim(); if url.is_empty() { return None; } if url.chars().any(|ch| ch.is_control() || ch == '\u{7f}') { return None; } // Explicit scheme: only http/https/mailto are navigable. A single-letter // prefix is a Windows drive, not a scheme. if let Some(colon) = url.find(':') { let scheme = &url[..colon]; if scheme.len() > 1 && scheme.chars().all(|ch| ch.is_ascii_alphabetic()) { return match scheme.to_ascii_lowercase().as_str() { "http" | "https" | "mailto" => Some(url.to_string()), _ => None, }; } } if url.starts_with("//") { return None; } if url.starts_with('#') { return Some(url.to_string()); } if url.starts_with('/') { return match policy { LinkPolicy::LocalServer => Some(url.to_string()), LinkPolicy::StaticRelative { .. } => None, }; } let path_part = url.split(['?', '#']).next().unwrap_or(url); if path_part.ends_with(".mq.md") { let joined = match current.parent() { Some(dir) => format!("{dir}/{path_part}"), None => path_part.to_string(), }; if let Ok(target) = SafeRelativePath::parse(&joined) { return Some(policy.document_href(current, &target)); } return None; } Some(url.to_string()) }