// 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::protocol::analysis_v3::{source_id, UnitKind}; use crate::reader::assets::AssetBundle; use crate::reader::markdown::{DocBlock, Inline, TableAlign}; use crate::reader::model::{anchor_for_span, PresentationModel}; use crate::reader::result_value::render_result_value; use crate::reader::source::SafeRelativePath; use crate::reader::source::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", percent_encode_path(target.as_str()) ) } } } fn media_href(&self, media: &super::media::Media) -> String { match self { LinkPolicy::LocalServer => format!( "/media/{}?path={}", media.filename(), percent_encode_path(media.path.as_str()) ), LinkPolicy::StaticRelative { page_depth } => { format!("{}media/{}", "../".repeat(*page_depth), media.filename()) } } } 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(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, /// Static exports may hide semantic/run annotations without changing prose. pub annotations: bool, /// View wall-clock limit shown in the explicit run form (seconds). pub run_timeout_secs: u64, /// Whether a frozen Core was negotiated (an explicit run form can exist). pub core_available: bool, pub snapshot_package: bool, pub embedded: bool, pub dark_theme: bool, pub overlay: Option>, } impl RenderContext { pub fn live() -> Self { Self { links: LinkPolicy::LocalServer, live: true, csrf_token: None, run_available: false, annotations: true, run_timeout_secs: 30, core_available: false, snapshot_package: false, embedded: false, dark_theme: false, overlay: None, } } pub fn static_site(page_depth: usize) -> Self { Self { links: LinkPolicy::StaticRelative { page_depth }, live: false, csrf_token: None, run_available: false, annotations: true, run_timeout_secs: 0, core_available: false, snapshot_package: false, embedded: false, dark_theme: false, overlay: None, } } /// Static export with annotations optionally disabled. pub fn static_export(page_depth: usize, annotations: bool) -> Self { let mut context = Self::static_site(page_depth); context.annotations = annotations; context } } 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 scriptless = ctx.snapshot_package || ctx.embedded; let script = if scriptless { String::new() } else { format!( "", escape_attr(&format!("{asset_prefix}{js_name}")) ) }; let mut html = String::with_capacity(16 * 1024 + model.document.source.len()); let relative_path = model.document.identity.relative_path.clone(); let analysis_digest = model .semantic .as_ref() .map(|semantic| semantic.analysis_digest.clone()) .unwrap_or_default(); let entry_main = model .semantic .as_ref() .and_then(|analysis| analysis.entry_main()); let page_title = if navigation.site_title.is_empty() { model.title.clone() } else { format!("{} · {}", model.title, navigation.site_title) }; let _ = write!( html, r##" {title} {script} 跳到正文 "##, presentation_version = model.version, view_version = env!("CARGO_PKG_VERSION"), csp = csp_policy(scriptless), title = escape_text(&page_title), logo = escape_attr(&logo_uri), css = escape_attr(&format!("{asset_prefix}{css_name}")), status = model.source_status.data_value(), theme = if ctx.dark_theme { "dark" } else { "light" }, embedded = ctx.embedded, annotations = if ctx.annotations { "on" } else { "off" }, run_state = model.run_state().data_value(), run_available = if ctx.run_available { "true" } else { "false" }, has_main = entry_main.is_some(), entry_function = escape_attr( entry_main .map(|function| function.id.as_str()) .unwrap_or_default() ), entry_needs_parameters = entry_main.is_some_and(|function| function .signature .params .iter() .any(|param| param.required)), core_available = if ctx.core_available { "true" } else { "false" }, document = escape_attr(&relative_path), analysis_digest = escape_attr(&analysis_digest), run_timeout = ctx.run_timeout_secs, live = if ctx.live { "true" } else { "false" }, ); if !ctx.embedded { self.render_topbar(&mut html, model, ctx, navigation); self.render_ornament(&mut html); } let _ = write!(html, "
\n"); if !ctx.embedded && navigation.welcome { self.render_welcome(&mut html, navigation); } if !ctx.embedded { self.render_document_meta(&mut html, model, ctx.overlay.is_some()); } if ctx.overlay.is_some() { let prefix = match ctx.links { LinkPolicy::StaticRelative { page_depth } => "../".repeat(page_depth), LinkPolicy::LocalServer => String::new(), }; let _ = write!(html, "

此文档包含一次执行快照。来源摘要见 manifest.json。

"); } if !ctx.embedded { self.render_diagnostics(&mut html, model); self.render_functions(&mut html, model, ctx); } self.render_document(&mut html, model, ctx); if !ctx.embedded { if ctx.live { self.render_live_run_shell(&mut html, ctx); } else { self.render_run_panel(&mut html, model, ctx); } if ctx.snapshot_package { let _ = write!(html, "
原始源码
{}
", escape_text(&model.document.source)); html.push_str(&self.render_file_list(model, ctx)); } else { self.render_source_pane(&mut html, model, ctx); } self.render_footer(&mut html, model); } let _ = write!(html, "
\n"); if !scriptless { 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: if scriptless { vec![css_name] } else { vec![css_name, js_name] }, } } fn render_topbar( &self, html: &mut String, model: &PresentationModel, ctx: &RenderContext, navigation: &crate::reader::model::Navigation, ) { if ctx.snapshot_package { let _ = write!(html, "
\"\"{}
", escape_attr(&self.assets.logo().data_uri()), escape_text(&navigation.site_title)); return; } let active = model .navigation .active .as_ref() .map(|path| path.as_str()) .unwrap_or(""); let files_count = navigation.documents.len(); let run_tab = if ctx.live { "".to_string() } else { String::new() }; 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"), ); let _ = (files_count, active); } fn render_ornament(&self, html: &mut String) { html.push_str( "
\n", ); } fn render_welcome(&self, html: &mut String, navigation: &crate::reader::model::Navigation) { let _ = write!( html, r##"

WELCOME TO

{title}

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

"##, title = escape_text(&navigation.site_title) ); } fn render_document_meta( &self, html: &mut String, model: &PresentationModel, has_snapshot: bool, ) { 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 = if has_snapshot { "静态文档 · 含执行快照".into() } else { escape_text(status.label()) }, ); if let Some(run) = &model.run { let _ = write!( html, "本次:{}\n", run.state.data_value(), escape_text(run.state_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, ctx: &RenderContext) { 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 function = model.semantic.as_ref().and_then(|semantic| { semantic.functions.iter().find(|function| { anchor_for_span(function.heading_span.start, function.heading_span.end) == entry.anchor }) }); let call_button = if ctx.live && ctx.core_available { function .map(|function| function_call_button(function, &function.local_name)) .unwrap_or_default() } else { String::new() }; let _ = write!( html, "
  • {label}{detail}{call_button}
  • \n", anchor = escape_attr(&entry.anchor), label = escape_text(&entry.label), detail = escape_text(&entry.detail), call_button = call_button ); } 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) => { let mut section = None; let place_result = |html: &mut String, function: &crate::protocol::analysis_v3::SemanticFunction| { if ctx.live { let _ = write!(html, "
", escape_attr(&function.id)); } if let Some(overlay) = ctx.overlay.as_deref().filter(|overlay| overlay.execution.target == function.id) { render_snapshot(html, overlay); } }; for block in &model.document.blocks { if let DocBlock::Heading { level: 1 | 2, span, .. } = block { if let Some(function) = section.take() { place_result(html, function); } section = function_at(model, *span); } render_block(html, block, model, ctx, current, self.assets); } if let Some(function) = section { place_result(html, function); } } 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 v3 · Observation v1 · {core} 默认不执行 · 无自动运行
"##, core = escape_text(&core) ); } /// Empty, accessible run panel that the single reader script fills from /// SSE events. It is never populated by the server for a live page: no run /// exists until the user explicitly submits one (RFC-VIEW-0002 §7.1). fn render_live_run_shell(&self, html: &mut String, _ctx: &RenderContext) { html.push_str( r##" "##, ); } fn render_dock(&self, html: &mut String, ctx: &RenderContext) { let 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"); let more = icon("M5 12h.01M12 12h.01M19 12h.01"); if ctx.live { let run_disabled = if ctx.core_available { "" } else { " data-disabled=\"true\"" }; let _ = write!( html, r##" "##, reload = icon("M20 7V3l-3 3a8 8 0 1 0 2 11M20 3h-5"), settings = settings, 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 = more, run_disabled = run_disabled ); } else { // Static export has no execution controls (RFC-VIEW-0002 §7.2). let _ = write!( html, r##" "##, settings = settings, more = more ); } } 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}

    函数与知识单元

    当前版本不支持

    {run_dialog} {export_dialog}

    关于 Marqdo View

    版本 {view_version} · CLI Tool API revision 1 · Analysis v3 · Observation v1。

    冻结核心:{core}。

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

    "##, csrf = csrf, export_dialog = if ctx.live && ctx.core_available { EXPORT_DIALOG } else { "" }, files = self.render_file_list(model, ctx), run_dialog = if ctx.core_available { render_run_form_dialog(model, ctx) } else { String::new() }, view_version = env!("CARGO_PKG_VERSION"), core = escape_text(model.core_version.as_deref().unwrap_or("未检测到可用核心")), ); } fn render_run_panel(&self, html: &mut String, model: &PresentationModel, _ctx: &RenderContext) { let Some(run) = &model.run else { return; }; let counts = &run.counts; let _ = write!( html, r##"

    本次运行 · {label}

    入口 {entry} · 观察级别 {capture} · 退出码 {exit_code} · 事件 {total}(本文 {entry_count} / 其他模块 {other_count})

    "##, state = run.state.data_value(), run_id = escape_attr(&run.run_id), label = escape_text(run.state_label()), entry = escape_text(run.entry.as_deref().unwrap_or("(未知入口)")), exit_code = run.exit_code, total = counts.total(), entry_count = run.entry_event_count, other_count = run.other_event_count, capture = escape_text(if run.capture_level.is_empty() { "(未知)" } else { &run.capture_level }), ); if let Some(truncated) = &run.truncated { let _ = write!( html, "

    Observation 已截断:{}

    \n", escape_text(&truncated.label()) ); } if let Some(code) = &run.error_code { let _ = write!( html, "

    Core 错误码:{}

    \n", escape_text(code) ); } for warning in &run.warnings { let _ = write!( html, "

    {}

    \n", escape_text(warning) ); } if let Some(value) = &run.result_value { html.push_str(render_result_value(value).as_html()); } if !run.stdout.is_empty() { let _ = write!( html, "
    {}
    \n", escape_text(&run.stdout) ); } if !run.stderr.is_empty() { let _ = write!( html, "
    {}
    \n", escape_text(&run.stderr) ); } if !run.events.is_empty() { html.push_str("
    真实 Observation v1 事件\n
      \n"); for event in run.events.iter().take(200) { let location = match event.span { Some(span) => { let (line, column) = model.document.source_index.line_col(span.start as usize); format!("第 {line} 行第 {column} 列") } None => { let module = event .module_id .as_deref() .and_then(|module| module.rsplit("::").next()) .unwrap_or("(无模块)"); module.to_string() } }; let detail = event.detail.as_deref().unwrap_or(""); let operation = event .operation .as_deref() .map(|operation| format!(" · {operation}")) .unwrap_or_default(); let _ = write!( html, "
    1. {kind}{location} {detail}{operation}
    2. \n", seq = event.seq, kind = escape_text(event.kind_label()), location = escape_text(&location), detail = escape_text(detail), operation = escape_text(&operation) ); } html.push_str("
    \n"); if run.events.len() > 200 { let _ = write!( html, "

    仅显示前 200 条(共 {} 条);完整数据保留在本地会话缓存中。

    \n", run.events.len() ); } html.push_str("
    \n"); } html.push_str("
    \n
    \n"); } 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 slug = model .heading_slugs .get(span) .map(String::as_str) .unwrap_or(&anchor); if slug != anchor { let _ = write!( html, "", escape_attr(&anchor) ); } let (badge, cleaned) = display_heading_content(content, unit); let section_span = unit .and_then(|unit| unit.span.start.checked_sub(0).map(|_| unit.span)) .map(|span| { format!( " data-section-start=\"{}\" data-section-end=\"{}\"", span.start, span.end ) }) .unwrap_or_default(); 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(slug), source_id_id(model, *span), data_semantic, span.start, span.end, ); let _ = section_span; if let Some(badge) = badge { let _ = write!( html, "{}", badge.1, badge.0 ); } render_inlines(html, &cleaned, model, ctx, current, assets); let interaction = if ctx.live && ctx.core_available { model.semantic.as_ref().and_then(|analysis| { analysis .function_by_heading(*span) .map(|function| (analysis, function)) }) } else { None }; if let Some((_, function)) = interaction { html.push_str(&function_call_button(function, &function.local_name)); } let _ = write!(html, "\n"); if let Some((analysis, function)) = interaction { render_function_interaction(html, model, analysis, function); } } 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" )), render_math(literal, true) ); } 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::protocol::analysis_v3::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.heading_span == Some(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::protocol::analysis_v3::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 = if ctx.annotations { projection.and_then(|projection| projection.statement_for_inline(*span)) } else { None }; html.push_str("'); html.push_str(&escape_text(literal)); html.push_str(""); if let Some((_, statement)) = anchor { render_run_chips(html, model, statement.span); } } Inline::Strong { span, children } => { let anchor = if ctx.annotations { projection.and_then(|projection| projection.statement_for_inline(*span)) } else { None }; html.push_str("'); render_inlines(html, children, model, ctx, current, assets_placeholder()); html.push_str(""); if let Some((_, statement)) = anchor { render_run_chips(html, model, statement.span); } } Inline::Emph { span, children } => { let anchor = if ctx.annotations { projection.and_then(|projection| projection.statement_for_inline(*span)) } else { None }; html.push_str("'); render_inlines(html, children, model, ctx, current, assets_placeholder()); html.push_str(""); if let Some((_, statement)) = anchor { render_run_chips(html, model, statement.span); } } 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 reference_state = reference.map(|reference| reference.state); let reference_href = reference.and_then(|reference| match reference.state { crate::protocol::analysis_v3::ReferenceState::Resolved => { // A resolved module target is linked through the project // document map; the fragment is preserved as written. reference.candidate_path.as_deref().and_then(|candidate| { crate::reader::source::SafeRelativePath::parse(candidate) .ok() .map(|target| { let mut href = ctx.links.document_href(current, &target); if let Some(fragment) = &reference.fragment { if !fragment.is_empty() { href.push('#'); href.push_str(&percent_encode_path( &super::links::content_anchor(fragment), )); } } href }) }) } crate::protocol::analysis_v3::ReferenceState::External => { resolve_link(url, current, model, &ctx.links) } _ => None, }); let target = if ctx.embedded { resolve_embedded_link(url, current, model) } else { match reference { // A local target the loaded catalog did not cover is shown as // unverified, never as a broken link: keep the navigation href // only when the document is known to the project. Some(_reference) if reference_state == Some(crate::protocol::analysis_v3::ReferenceState::NotLoaded) => { resolve_link(url, current, model, &ctx.links) } Some(_) => reference_href, None => resolve_link(url, current, model, &ctx.links), } }; let state = reference_state.map(|state| state.data_value()); let state_title = match reference_state { Some(crate::protocol::analysis_v3::ReferenceState::NotLoaded) => { "未核验:当前加载目录未覆盖该本地目标" } Some(crate::protocol::analysis_v3::ReferenceState::Missing) => "引用目标缺失", Some(crate::protocol::analysis_v3::ReferenceState::Ambiguous) => { "引用目标不唯一,请检查候选" } Some(crate::protocol::analysis_v3::ReferenceState::OutsideScope) => { "引用目标越出项目范围,已拒绝读取" } Some(crate::protocol::analysis_v3::ReferenceState::Invalid) => "引用地址无效", _ => "", }; let unverified = matches!( reference_state, Some(crate::protocol::analysis_v3::ReferenceState::NotLoaded) ); match target { Some(href) => { let _ = write!(html, "'); render_inlines(html, children, model, ctx, current, assets_placeholder()); html.push_str(""); } None => { let class = if state.is_some() { "mq-link-blocked mq-link-error" } else { "mq-link-blocked" }; let _ = write!(html, "'); render_inlines(html, children, model, ctx, current, assets_placeholder()); html.push_str(""); } } } Inline::Image { url, alt, title, .. } => { if let Some(media) = model.media.get(url) { let _ = write!(html, "\"{}\"", escape_attr(&ctx.links.media_href(media)), escape_attr(alt), media.width, media.height, escape_attr(title)); } else { let _ = write!(html, "[图片已阻止自动加载:{}]", escape_attr(url), 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(), render_math(literal, *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", )) } pub(super) 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(snapshot_package: bool) -> &'static str { if snapshot_package { "default-src 'none'; style-src 'self' file:; img-src 'self' file: data:; font-src 'self' file:; base-uri 'none'; form-action 'none'; object-src 'none'" } else { "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'; object-src 'none'" } } fn render_snapshot(html: &mut String, overlay: &super::snapshot::ExportResultOverlay) { let execution = &overlay.execution; let status = if execution.status == "succeeded" { "成功" } else { "失败 · 部分观察" }; let _ = write!(html, "
      本次执行快照 · {} · {status}

      Core {} · {} · 运行 {}", escape_attr(execution.status), escape_text(&overlay.label), escape_text(&execution.core_version), escape_text(&execution.mode), escape_text(&execution.core_run_id)); if let Some(terminal_at) = &execution.terminal_at { let _ = write!( html, " · ", escape_attr(terminal_at), escape_text(terminal_at) ); } html.push_str("

      "); if let Some(value) = &overlay.value { html.push_str(value.as_html()); } for (label, value) in [("stdout", &overlay.stdout), ("stderr", &overlay.stderr)] { if let Some(value) = value { let _ = write!( html, "

      {label}

      {}
      ", escape_text(value) ); } } if let Some(arguments) = &overlay.arguments { html.push_str("

      提交的参数表达式

      "); for (name, expression) in arguments { let _ = write!( html, "
      {}
      {}
      ", escape_text(name), escape_text(expression) ); } html.push_str("
      "); } else { html.push_str("

      参数未包含

      "); } let observation_status = match execution.observation_status.as_str() { "verified" => "已验证", "truncated" => "已验证,观察截断", "invalid" => "无效", "stale" => "已过期", _ => "不可用", }; let _ = write!( html, "

      Observation v1 {observation_status} · 捕获级别 {capture_level}

      ", capture_level = escape_text(&execution.capture_level), ); if let Some(counts) = &overlay.observation_counts { html.push_str("
      "); for (kind, count) in counts { let _ = write!(html, "
      {}
      {count}
      ", escape_text(kind)); } html.push_str("
      "); } if !execution.output_complete || !execution.result_complete || execution.observation_truncated { html.push_str( "

      部分结果、输出或事件超过显示上限,或未完成。

      ", ); } html.push_str("
      "); } 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 } pub(crate) fn fragment_href(anchor: &str) -> String { format!("#{}", percent_encode_path(anchor)) } fn resolve_embedded_link( raw: &str, current: &SafeRelativePath, model: &PresentationModel, ) -> Option { let (path, fragment) = raw.trim().split_once('#')?; if !path.is_empty() && super::links::relative_url(current, path).as_ref() != Some(current) { return None; } let fragment = super::links::decode(fragment)?; model .has_heading_anchor(&fragment) .then(|| fragment_href(&fragment)) } /// 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, model: &PresentationModel, policy: &LinkPolicy, ) -> Option { let url = raw.trim(); if url.is_empty() || url.chars().any(char::is_control) || url.contains('\\') || url.starts_with('/') { return None; } let (path_with_query, fragment) = url .split_once('#') .map_or((url, None), |(path, fragment)| (path, Some(fragment))); let path = path_with_query.split('?').next()?; if let Some((scheme, _)) = path.split_once(':') { return matches!( scheme.to_ascii_lowercase().as_str(), "http" | "https" | "mailto" ) .then(|| url.to_string()); } let fragment = fragment .map(super::links::decode) .unwrap_or_else(|| Some(String::new()))?; let suffix = if fragment.is_empty() { String::new() } else { format!("#{}", percent_encode_path(&fragment)) }; if path.is_empty() { return Some(suffix); } let target = super::links::relative_url(current, path)?; if target.as_str().ends_with(".mq.md") { if !model.navigation.documents.contains(&target) { return None; } return Some(format!( "{}{suffix}", policy.document_href(current, &target) )); } Some(url.to_string()) } fn render_math(literal: &str, display: bool) -> String { super::math::render(literal, display).unwrap_or_else(|| { format!( "{}", escape_text(literal) ) }) } fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span: SourceSpan) { let Some(run) = &model.run else { return; }; let Some(summary) = run.anchor_summary(statement_span) else { return; }; let suffix = if summary.count > 1 { format!(" ×{}", summary.count) } else { String::new() }; let _ = write!( html, "{detail}{suffix}", seq = summary.last_seq, kinds = escape_attr(&summary.kinds.join(",")), count = summary.count, detail = escape_text(&summary.detail), suffix = escape_text(&suffix) ); } fn function_at( model: &PresentationModel, span: SourceSpan, ) -> Option<&crate::protocol::analysis_v3::SemanticFunction> { model.semantic.as_ref()?.function_by_heading(span) } fn function_call_button( function: &crate::protocol::analysis_v3::SemanticFunction, label: &str, ) -> String { format!( "", id = escape_attr(&function.id), label = escape_attr(label), anchor = anchor_for_span(function.heading_span.start, function.heading_span.end), ) } fn render_function_interaction( html: &mut String, model: &PresentationModel, analysis: &crate::protocol::analysis_v3::SemanticProjection, function: &crate::protocol::analysis_v3::SemanticFunction, ) { let anchor = anchor_for_span(function.heading_span.start, function.heading_span.end); let (line, _) = model .document .source_index .line_col(function.heading_span.start as usize); let _ = write!( html, r#" "#, label = escape_attr(analysis.canonical_function_name(function)), id = escape_attr(&function.id), name = escape_attr(analysis.call_name(function)), params = escape_attr(&function_params_json(function)), effects = escape_attr(&function.effects.join(", ")), ); } fn function_params_json(function: &crate::protocol::analysis_v3::SemanticFunction) -> String { serde_json::json!(function .signature .params .iter() .map(|param| serde_json::json!({ "name": param.name, "type": param.ty, "required": param.required, "default": param.default, })) .collect::>()) .to_string() } const EXPORT_DIALOG: &str = r##"

      导出文档(含本次结果)

      导出内容

      输出和参数可能包含令牌、路径或个人信息。请检查所选内容。

      "##; fn render_run_form_dialog(model: &PresentationModel, ctx: &RenderContext) -> String { let path = &model.document.identity.relative_path; format!( r##"

      显式运行

      入口 main · pure

      执行模式

      以下是即将提交的参数列表,仅用于审阅。点击“确认执行”后才会运行。

      
        

      墙钟上限 {timeout} 秒;结果通过 SSE 推送,不轮询。打开/刷新/导出不会执行。

      "##, path = escape_attr(path), timeout = ctx.run_timeout_secs ) }