feat: package the shared reader for offline embedding (#16)
This commit is contained in:
1 parent
84f7636627
commit
23fa0306d1
12 files changed
+430
-62
No files matched your search
@@ -32,3 +32,4 @@ steps:
|
||||
MARQDO_BIN="$(scripts/frozen-beta.sh fetch "$(mktemp -d)")"
|
||||
export MARQDO_BIN
|
||||
./scripts/test-browser.sh
|
||||
./scripts/test-export.sh
|
||||
@@ -142,6 +142,24 @@ marqdo view export examples/function-params.mq.md --out /tmp/view-result \
|
||||
标准输出、标准错误、参数值和完整事件流均不会写入此导出。终态没有记录结束时刻时,该字段为 `null`。
|
||||
错误运行 ID、已改动文稿、截断和未完成快照均拒绝导出。普通 `export --out DIR` 可继续用于无运行结果的文稿。
|
||||
|
||||
### 在宿主中嵌入只读正文
|
||||
|
||||
```bash
|
||||
source_sha="$(sha256sum article.mq.md | cut -d' ' -f1)"
|
||||
marqdo view export article.mq.md --out /tmp/view-reader --embed \
|
||||
--theme dark --anchor introduction --expect-source-sha256 "$source_sha"
|
||||
```
|
||||
|
||||
`--embed` 接受选定的 `.mq.md` 或普通 `.md` 文件。普通 Markdown 直接阅读,状态为 `markdown-only`。
|
||||
主题选择为 `light`(默认)或 `dark`。`manifest.json` 的 `entry.heading_ids` 列出可跳转的标题 ID。
|
||||
省略 `--anchor` 可从文稿开头读取。若调用方指定了不存在的标题或不匹配的源码摘要,命令会返回诊断并停止导出。
|
||||
|
||||
宿主从本地包加载 `manifest.entry.href`。请核对 `mode=embedded`、`requires`、`producers.view.binary_sha256`、
|
||||
`pages[0].source_sha256` 和包文件的摘要。保留 `index.html`、`assets/` 与 `media/` 的相对位置,
|
||||
在本地隔离浏览上下文中打开。使用 iframe 时可设置 `sandbox="allow-same-origin"` 而不开放脚本或顶层导航。
|
||||
正文使用独立 View 的同一主题、标题、公式、表格和媒体规则。只有本文稿内存在的标题链接可跳转,
|
||||
外部及跨文稿链接保留为文字。有效媒体限于项目内的已验证静态图片。宿主管理选中文稿、导航和运行授权。
|
||||
|
||||
## 开发与验收
|
||||
|
||||
```bash
|
||||
|
||||
@@ -242,6 +242,10 @@
|
||||
margin: 0 auto;
|
||||
padding: clamp(28px, 5vh, 56px) 0 calc(var(--mq-dock-h) + 72px);
|
||||
}
|
||||
.mq-reader[data-embedded="true"] .mq-main {
|
||||
--mq-gutter: clamp(12px, 4vw, 32px);
|
||||
padding: clamp(12px, 3vw, 28px) 0;
|
||||
}
|
||||
|
||||
.mq-docmeta {
|
||||
display: flex;
|
||||
|
||||
@@ -107,6 +107,66 @@ reject_import "$result_work/run.json" "$run_id" 'view.observation_stale'
|
||||
test ! -e "$result_work/project/out/view-sentinel.txt"
|
||||
echo 'Observation export: PASS (real CLI, selected run, stale/incomplete/truncated refusal, zero re-execution)'
|
||||
|
||||
# #16: embed both an analyzed document and ordinary Markdown through the same
|
||||
# release binary. No project sibling or blocked media should enter the package.
|
||||
embed_work="$result_work/embed"
|
||||
mkdir -p "$embed_work/project"
|
||||
python3 - "$embed_work" <<'PY'
|
||||
import pathlib
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
work = pathlib.Path(sys.argv[1])
|
||||
project = work / 'project'
|
||||
wide = 'long' * 100
|
||||
body = f'''\n阅读正文含有公式 $r^2$ 与 [跳到详情](#detail)。
|
||||
|
||||
  
|
||||
|
||||
[远程链接](https://example.invalid) [缺失锚点](#missing) [其他文稿](other.mq.md)
|
||||
|
||||
<script>window.embeddedAttackDetected = true</script>
|
||||
|
||||
| 文字 | 列 |
|
||||
| --- | --- |
|
||||
| {wide} | 示例 |
|
||||
|
||||
```text
|
||||
{wide}
|
||||
```
|
||||
|
||||
## Detail
|
||||
|
||||
> 一段引用。
|
||||
'''
|
||||
(project / 'index.mq.md').write_text('# @knowledge 阅读\n' + body)
|
||||
(project / 'plain.md').write_text('# 阅读\n' + body)
|
||||
(project / 'other.mq.md').write_text('# @knowledge 不应打包\n')
|
||||
def chunk(name, data):
|
||||
return struct.pack('>I', len(data)) + name + data + struct.pack('>I', zlib.crc32(name + data))
|
||||
image = (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 2, 0, 0, 0))
|
||||
+ chunk(b'IDAT', zlib.compress(b'\x00\xA0\x00\x50')) + chunk(b'IEND', b''))
|
||||
(project / 'image.png').write_bytes(image)
|
||||
(work / 'outside.png').write_bytes(image)
|
||||
(project / 'escape.png').symlink_to('../outside.png')
|
||||
PY
|
||||
for source in index.mq.md plain.md; do
|
||||
document="$embed_work/project/$source"
|
||||
document_sha="$(sha256sum "$document" | cut -d' ' -f1)"
|
||||
"${view[@]}" export "$document" --out "$embed_work/$source" --embed \
|
||||
--theme dark --anchor detail --expect-source-sha256 "$document_sha"
|
||||
done
|
||||
for option in --anchor --expect-source-sha256; do
|
||||
if "${view[@]}" export "$document" --out "$embed_work/invalid" --embed \
|
||||
"$option" missing > "$embed_work/rejection.log" 2>&1; then
|
||||
echo "error: embedded export accepted invalid $option" >&2
|
||||
exit 1
|
||||
fi
|
||||
rg -q 'view.export_(invalid|source_changed)' "$embed_work/rejection.log"
|
||||
test ! -e "$embed_work/invalid"
|
||||
done
|
||||
|
||||
# X-04: open the exported site from file:// in a real browser (offline).
|
||||
if [[ -d "$repo_root/tests/browser/node_modules/playwright" ]]; then
|
||||
PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$repo_root/tests/.cache/pw-browsers}" \
|
||||
@@ -144,6 +204,8 @@ const { chromium } = require(path.join(process.argv[2], "node_modules/playwright
|
||||
await browser.close();
|
||||
})().catch((error) => { console.error(error.message); process.exit(1); });
|
||||
JS
|
||||
PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$repo_root/tests/.cache/pw-browsers}" \
|
||||
node tests/browser/embedded.browser.cjs "$embed_work" "${view[@]}"
|
||||
else
|
||||
echo "note: Playwright not installed; skipped file:// browser check"
|
||||
fi
|
||||
|
||||
+22
-1
@@ -82,7 +82,12 @@ pub struct ExportArgs {
|
||||
pub no_annotations: bool,
|
||||
|
||||
/// Import a trusted, already completed CLI Observation snapshot.
|
||||
#[arg(long, value_name = "FILE", requires = "run_id")]
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "FILE",
|
||||
requires = "run_id",
|
||||
conflicts_with = "embed"
|
||||
)]
|
||||
pub observation: Option<PathBuf>,
|
||||
|
||||
/// Exact Observation run.id selected for export.
|
||||
@@ -92,6 +97,22 @@ pub struct ExportArgs {
|
||||
/// Include a potentially sensitive, non-scalar return value from the snapshot.
|
||||
#[arg(long, requires = "observation")]
|
||||
pub include_sensitive_result: bool,
|
||||
|
||||
/// Export one document as a script-free, embeddable reader package.
|
||||
#[arg(long)]
|
||||
pub embed: bool,
|
||||
|
||||
/// Select the embedded reader theme (default: light).
|
||||
#[arg(long, value_parser = ["light", "dark"], requires = "embed")]
|
||||
pub theme: Option<String>,
|
||||
|
||||
/// Publish an entry link to this exact heading ID in the embedded document.
|
||||
#[arg(long, value_name = "ID", requires = "embed")]
|
||||
pub anchor: Option<String>,
|
||||
|
||||
/// Require this raw, lowercase SHA-256 of the selected document's bytes.
|
||||
#[arg(long, value_name = "HEX", requires = "embed")]
|
||||
pub expect_source_sha256: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
|
||||
+92
-18
@@ -8,7 +8,7 @@ use crate::error::{ViewError, ViewResult};
|
||||
use crate::export_result::ObservationImport;
|
||||
use crate::reader::assemble::DocumentService;
|
||||
use crate::reader::assets::AssetBundle;
|
||||
use crate::reader::render::ReaderRenderer;
|
||||
use crate::reader::render::{fragment_href, ReaderRenderer};
|
||||
use crate::reader::snapshot::ExportResultOverlay;
|
||||
use crate::reader::source::sha256_hex;
|
||||
use crate::reader::source::SafeRelativePath;
|
||||
@@ -32,14 +32,21 @@ pub struct ExportSummary {
|
||||
pub manifest_sha256: String,
|
||||
}
|
||||
|
||||
pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult<ExportSummary> {
|
||||
export_with_observation(context, options, None)
|
||||
pub(crate) struct EmbedOptions<'a> {
|
||||
pub dark_theme: bool,
|
||||
pub anchor: Option<&'a str>,
|
||||
pub expected_sha256: Option<&'a str>,
|
||||
}
|
||||
|
||||
pub(crate) fn export_with_observation(
|
||||
pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult<ExportSummary> {
|
||||
write_export(context, options, None, None)
|
||||
}
|
||||
|
||||
pub(crate) fn write_export(
|
||||
context: &DocumentService,
|
||||
options: &ExportOptions,
|
||||
observation: Option<ObservationImport<'_>>,
|
||||
embed: Option<&EmbedOptions<'_>>,
|
||||
) -> ViewResult<ExportSummary> {
|
||||
let root = context.project().root().to_path_buf();
|
||||
let out = absolute_export_target(&options.out)?;
|
||||
@@ -55,13 +62,38 @@ pub(crate) fn export_with_observation(
|
||||
validate_existing_target(&out)?;
|
||||
|
||||
let entry = context.load(&context.project().entry().relative)?;
|
||||
if let Some(embed) = embed {
|
||||
if embed
|
||||
.expected_sha256
|
||||
.is_some_and(|expected| expected != sha256_hex(entry.document.source.as_bytes()))
|
||||
{
|
||||
return Err(ViewError::ExportSourceChanged {
|
||||
detail: "embedded document does not match --expect-source-sha256".into(),
|
||||
});
|
||||
}
|
||||
if embed
|
||||
.anchor
|
||||
.is_some_and(|anchor| !entry.has_heading_anchor(anchor))
|
||||
{
|
||||
return Err(ViewError::ExportInvalid {
|
||||
detail: "requested heading anchor does not exist in the embedded document".into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
let overlay = observation
|
||||
.map(|input| input.prepare(&entry))
|
||||
.transpose()?
|
||||
.map(Arc::new);
|
||||
let staging = staging_dir(&out)?;
|
||||
let result = (|| {
|
||||
let site = build_site(context, &entry, &staging, !options.no_annotations, overlay)?;
|
||||
let site = build_site(
|
||||
context,
|
||||
&entry,
|
||||
&staging,
|
||||
!options.no_annotations,
|
||||
overlay,
|
||||
embed,
|
||||
)?;
|
||||
publish(&staging, &out)?;
|
||||
Ok(ExportSummary {
|
||||
out,
|
||||
@@ -130,9 +162,14 @@ fn build_site(
|
||||
staging: &Path,
|
||||
annotations: bool,
|
||||
overlay: Option<Arc<ExportResultOverlay>>,
|
||||
embed: Option<&EmbedOptions<'_>>,
|
||||
) -> ViewResult<Site> {
|
||||
let documents = context.project().list_documents()?;
|
||||
let entry = SafeRelativePath::parse(&entry_model.document.identity.relative_path)?;
|
||||
let documents = if embed.is_some() {
|
||||
vec![entry.clone()]
|
||||
} else {
|
||||
context.project().list_documents()?
|
||||
};
|
||||
if !documents.contains(&entry) {
|
||||
return Err(ViewError::ExportFailed {
|
||||
detail: "entry document is missing".into(),
|
||||
@@ -147,7 +184,7 @@ fn build_site(
|
||||
let renderer = ReaderRenderer::new();
|
||||
let mut assets = Vec::new();
|
||||
for asset in bundle.all() {
|
||||
if overlay.is_some() && asset.extension == "js" {
|
||||
if (overlay.is_some() || embed.is_some()) && asset.extension == "js" {
|
||||
continue;
|
||||
}
|
||||
let (name, bytes) = if asset.name == "reader" && asset.extension == "css" {
|
||||
@@ -177,16 +214,26 @@ fn build_site(
|
||||
entry.insert(record);
|
||||
}
|
||||
}
|
||||
let depth = relative.as_str().split('/').count();
|
||||
let depth = if embed.is_some() {
|
||||
0
|
||||
} else {
|
||||
relative.as_str().split('/').count()
|
||||
};
|
||||
let mut settings = crate::reader::render::RenderContext::static_export(depth, annotations);
|
||||
settings.snapshot_package = overlay.is_some();
|
||||
settings.embedded = embed.is_some();
|
||||
settings.dark_theme = embed.is_some_and(|embed| embed.dark_theme);
|
||||
settings.overlay = if *relative == entry {
|
||||
overlay.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let page = renderer.render(model, &settings);
|
||||
let path = format!("pages/{}.html", relative.as_str());
|
||||
let path = if embed.is_some() {
|
||||
"index.html".to_string()
|
||||
} else {
|
||||
format!("pages/{}.html", relative.as_str())
|
||||
};
|
||||
let file = writer.write(&path, page.html.as_bytes())?;
|
||||
pages.push(serde_json::json!({
|
||||
"relative_path": relative.as_str(),
|
||||
@@ -200,15 +247,19 @@ fn build_site(
|
||||
}));
|
||||
files.push(file);
|
||||
}
|
||||
let index_sha = if embed.is_some() {
|
||||
pages[0]["sha256"].clone()
|
||||
} else {
|
||||
let mut index_context = crate::reader::render::RenderContext::static_export(0, annotations);
|
||||
index_context.snapshot_package = overlay.is_some();
|
||||
index_context.overlay = overlay.clone();
|
||||
let index_page = renderer.render(entry_model, &index_context);
|
||||
let index_file = writer.write("index.html", index_page.html.as_bytes())?;
|
||||
let sha = index_file["sha256"].clone();
|
||||
files.push(index_file);
|
||||
sha
|
||||
};
|
||||
files.extend(media_files.values().cloned());
|
||||
|
||||
let mut index_context = crate::reader::render::RenderContext::static_export(0, annotations);
|
||||
index_context.snapshot_package = overlay.is_some();
|
||||
index_context.overlay = overlay.clone();
|
||||
let index_page = renderer.render(entry_model, &index_context);
|
||||
let index_file = writer.write("index.html", index_page.html.as_bytes())?;
|
||||
let index_sha = index_file["sha256"].clone();
|
||||
files.push(index_file);
|
||||
files.sort_by(|a, b| a["path"].as_str().cmp(&b["path"].as_str()));
|
||||
let mut manifest = serde_json::json!({
|
||||
"schema": MANIFEST_SCHEMA,
|
||||
@@ -258,6 +309,22 @@ fn build_site(
|
||||
fields.remove("note");
|
||||
}
|
||||
}
|
||||
if let Some(embed) = embed {
|
||||
let mut anchors: Vec<_> = entry_model.heading_slugs.iter().collect();
|
||||
anchors.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
let href = match embed.anchor {
|
||||
Some(anchor) => format!("index.html{}", fragment_href(anchor)),
|
||||
None => "index.html".to_string(),
|
||||
};
|
||||
manifest["mode"] = serde_json::json!("embedded");
|
||||
manifest["theme"] = serde_json::json!(if embed.dark_theme { "dark" } else { "light" });
|
||||
manifest["entry"]["href"] = serde_json::json!(href);
|
||||
manifest["entry"]["anchor"] = serde_json::json!(embed.anchor);
|
||||
manifest["entry"]["heading_ids"] = serde_json::json!(anchors
|
||||
.into_iter()
|
||||
.map(|(_, slug)| slug)
|
||||
.collect::<Vec<_>>());
|
||||
}
|
||||
let manifest_bytes =
|
||||
serde_json::to_vec_pretty(&manifest).map_err(|err| ViewError::ExportFailed {
|
||||
detail: format!("serialize export manifest: {err}"),
|
||||
@@ -310,7 +377,14 @@ pub fn snapshot(
|
||||
let staging = scratch.file("site");
|
||||
std::fs::create_dir(&staging)
|
||||
.map_err(|err| ViewError::io("create private snapshot site", err))?;
|
||||
let site = build_site(context, model, &staging, true, Some(Arc::new(overlay)))?;
|
||||
let site = build_site(
|
||||
context,
|
||||
model,
|
||||
&staging,
|
||||
true,
|
||||
Some(Arc::new(overlay)),
|
||||
None,
|
||||
)?;
|
||||
let path = scratch.file("snapshot.zip");
|
||||
let archive =
|
||||
std::fs::File::create(&path).map_err(|err| ViewError::io("create snapshot ZIP", err))?;
|
||||
|
||||
+7
-1
@@ -69,13 +69,19 @@ fn export_command(opts: &RuntimeOpts, args: &ExportArgs) -> ViewResult<i32> {
|
||||
})
|
||||
}
|
||||
};
|
||||
let summary = export::export_with_observation(
|
||||
let embed = args.embed.then(|| export::EmbedOptions {
|
||||
dark_theme: args.theme.as_deref() == Some("dark"),
|
||||
anchor: args.anchor.as_deref(),
|
||||
expected_sha256: args.expect_source_sha256.as_deref(),
|
||||
});
|
||||
let summary = export::write_export(
|
||||
&service,
|
||||
&ExportOptions {
|
||||
out: args.out.clone(),
|
||||
no_annotations: args.no_annotations,
|
||||
},
|
||||
observation,
|
||||
embed.as_ref(),
|
||||
)?;
|
||||
println!(
|
||||
"marqdo view export: {} page(s), {} file(s) → {}",
|
||||
|
||||
@@ -226,7 +226,10 @@ impl DocumentService {
|
||||
let mut verified = None;
|
||||
let mut source = disk_source.clone();
|
||||
|
||||
if let Some(client) = &self.core {
|
||||
if relative.as_str().ends_with(".md") && !relative.as_str().ends_with(".mq.md") {
|
||||
status = SourceStatus::MarkdownOnly;
|
||||
status_note = None;
|
||||
} else if let Some(client) = &self.core {
|
||||
match client.check(
|
||||
&self.project,
|
||||
relative,
|
||||
|
||||
@@ -15,6 +15,8 @@ pub const PRESENTATION_VERSION: u32 = 1;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SourceStatus {
|
||||
/// Ordinary Markdown has no Marqdo semantic projection.
|
||||
MarkdownOnly,
|
||||
/// No usable `MARQDO_BIN`; prose only, semantics explicitly unverified.
|
||||
CoreUnavailable,
|
||||
/// `check` succeeded and Analysis v3 was verified.
|
||||
@@ -32,6 +34,7 @@ pub enum SourceStatus {
|
||||
impl SourceStatus {
|
||||
pub fn data_value(&self) -> &'static str {
|
||||
match self {
|
||||
SourceStatus::MarkdownOnly => "markdown-only",
|
||||
SourceStatus::CoreUnavailable => "core-unavailable",
|
||||
SourceStatus::StaticOk => "static-ok",
|
||||
SourceStatus::CoreError => "core-error",
|
||||
@@ -43,6 +46,7 @@ impl SourceStatus {
|
||||
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
SourceStatus::MarkdownOnly => "Markdown · 只读",
|
||||
SourceStatus::CoreUnavailable => "核心不可用 · 语义未验证",
|
||||
SourceStatus::StaticOk => "静态检查已通过 · 未运行",
|
||||
SourceStatus::CoreError => "Core 检查失败 · 语义不可用",
|
||||
@@ -125,6 +129,12 @@ pub enum OutlineKind {
|
||||
}
|
||||
|
||||
impl PresentationModel {
|
||||
pub(crate) fn has_heading_anchor(&self, id: &str) -> bool {
|
||||
self.heading_slugs
|
||||
.iter()
|
||||
.any(|(span, slug)| slug == id || anchor_for_span(span.start, span.end) == id)
|
||||
}
|
||||
|
||||
/// True when the entry module exposes a resolvable `main` (canonical or
|
||||
/// unique local name). The dock Run button never substitutes another
|
||||
/// function for a missing entry function (RFC-VIEW-0002 §2.4).
|
||||
|
||||
+76
-36
@@ -92,6 +92,8 @@ pub struct RenderContext {
|
||||
/// 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<std::sync::Arc<super::snapshot::ExportResultOverlay>>,
|
||||
}
|
||||
|
||||
@@ -106,6 +108,8 @@ impl RenderContext {
|
||||
run_timeout_secs: 30,
|
||||
core_available: false,
|
||||
snapshot_package: false,
|
||||
embedded: false,
|
||||
dark_theme: false,
|
||||
overlay: None,
|
||||
}
|
||||
}
|
||||
@@ -120,6 +124,8 @@ impl RenderContext {
|
||||
run_timeout_secs: 0,
|
||||
core_available: false,
|
||||
snapshot_package: false,
|
||||
embedded: false,
|
||||
dark_theme: false,
|
||||
overlay: None,
|
||||
}
|
||||
}
|
||||
@@ -159,7 +165,8 @@ impl ReaderRenderer {
|
||||
let logo_uri = self.assets.logo().data_uri();
|
||||
|
||||
let navigation = &model.navigation;
|
||||
let script = if ctx.snapshot_package {
|
||||
let scriptless = ctx.snapshot_package || ctx.embedded;
|
||||
let script = if scriptless {
|
||||
String::new()
|
||||
} else {
|
||||
format!(
|
||||
@@ -195,16 +202,18 @@ impl ReaderRenderer {
|
||||
<link rel="stylesheet" href="{css}"/>
|
||||
{script}
|
||||
</head>
|
||||
<body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-has-main="{has_main}" data-core-available="{core_available}" data-document="{document}" data-analysis-digest="{analysis_digest}" data-run-timeout="{run_timeout}" data-live="{live}">
|
||||
<body class="mq-reader" data-mode="document" data-theme="{theme}" data-embedded="{embedded}" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-has-main="{has_main}" data-core-available="{core_available}" data-document="{document}" data-analysis-digest="{analysis_digest}" data-run-timeout="{run_timeout}" data-live="{live}">
|
||||
<a class="mq-skip" href="#mq-main">跳到正文</a>
|
||||
"##,
|
||||
presentation_version = model.version,
|
||||
view_version = env!("CARGO_PKG_VERSION"),
|
||||
csp = csp_policy(ctx.snapshot_package),
|
||||
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" },
|
||||
@@ -216,14 +225,18 @@ impl ReaderRenderer {
|
||||
live = if ctx.live { "true" } else { "false" },
|
||||
);
|
||||
|
||||
self.render_topbar(&mut html, model, ctx, navigation);
|
||||
self.render_ornament(&mut html);
|
||||
if !ctx.embedded {
|
||||
self.render_topbar(&mut html, model, ctx, navigation);
|
||||
self.render_ornament(&mut html);
|
||||
}
|
||||
let _ = write!(html, "<main class=\"mq-main\" id=\"mq-main\">\n");
|
||||
|
||||
if navigation.welcome {
|
||||
if !ctx.embedded && navigation.welcome {
|
||||
self.render_welcome(&mut html, navigation);
|
||||
}
|
||||
self.render_document_meta(&mut html, model, ctx.overlay.is_some());
|
||||
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),
|
||||
@@ -231,25 +244,29 @@ impl ReaderRenderer {
|
||||
};
|
||||
let _ = write!(html, "<p class=\"mq-snapshot-notice\">此文档包含一次执行快照。来源摘要见 <a href=\"{prefix}manifest.json\">manifest.json</a>。</p>");
|
||||
}
|
||||
self.render_diagnostics(&mut html, model);
|
||||
self.render_functions(&mut html, model, ctx);
|
||||
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.live {
|
||||
self.render_live_run_shell(&mut html, ctx);
|
||||
} else {
|
||||
self.render_run_panel(&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, "<details class=\"mq-static-source\"><summary>原始源码</summary><pre>{}</pre></details>",
|
||||
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);
|
||||
}
|
||||
if ctx.snapshot_package {
|
||||
let _ = write!(html, "<details class=\"mq-static-source\"><summary>原始源码</summary><pre>{}</pre></details>",
|
||||
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, "</main>\n");
|
||||
|
||||
if !ctx.snapshot_package {
|
||||
if !scriptless {
|
||||
self.render_dock(&mut html, ctx);
|
||||
self.render_toast(&mut html);
|
||||
self.render_dialogs(&mut html, model, ctx);
|
||||
@@ -258,7 +275,7 @@ impl ReaderRenderer {
|
||||
|
||||
RenderedPage {
|
||||
html,
|
||||
assets_used: if ctx.snapshot_package {
|
||||
assets_used: if scriptless {
|
||||
vec![css_name]
|
||||
} else {
|
||||
vec![css_name, js_name]
|
||||
@@ -1046,7 +1063,7 @@ fn render_block(
|
||||
}
|
||||
let _ = write!(
|
||||
html,
|
||||
"<pre><code>{}</code></pre></div>\n",
|
||||
"<pre tabindex=\"0\" aria-label=\"代码\"><code>{}</code></pre></div>\n",
|
||||
escape_text(literal)
|
||||
);
|
||||
}
|
||||
@@ -1056,7 +1073,7 @@ fn render_block(
|
||||
rows,
|
||||
..
|
||||
} => {
|
||||
html.push_str("<div class=\"mq-table-wrap\"><table>\n");
|
||||
html.push_str("<div class=\"mq-table-wrap\" tabindex=\"0\" role=\"region\" aria-label=\"表格\"><table>\n");
|
||||
if !header.is_empty() {
|
||||
html.push_str("<thead><tr>");
|
||||
for (index, cell) in header.iter().enumerate() {
|
||||
@@ -1351,18 +1368,22 @@ fn render_inline(
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let target = 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)
|
||||
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),
|
||||
}
|
||||
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 {
|
||||
@@ -1605,6 +1626,25 @@ fn percent_encode_path(raw: &str) -> String {
|
||||
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<String> {
|
||||
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.
|
||||
|
||||
@@ -187,15 +187,11 @@ fn serve_page(
|
||||
};
|
||||
let (session, set_cookie) = state.security.page_session(&request);
|
||||
let ctx = RenderContext {
|
||||
links: crate::reader::render::LinkPolicy::LocalServer,
|
||||
live: true,
|
||||
csrf_token: Some(session.csrf),
|
||||
run_available: state.service.core().is_some() && model.can_offer_run(),
|
||||
annotations: true,
|
||||
run_timeout_secs: state.controller.config().run_timeout_secs(),
|
||||
core_available: state.service.core().is_some(),
|
||||
snapshot_package: false,
|
||||
overlay: None,
|
||||
..RenderContext::live()
|
||||
};
|
||||
let page = state.renderer.render(&model, &ctx);
|
||||
let mut headers = Vec::new();
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"use strict";
|
||||
|
||||
const assert = require("node:assert/strict");
|
||||
const { spawn } = require("node:child_process");
|
||||
const { createHash } = require("node:crypto");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { setTimeout: delay } = require("node:timers/promises");
|
||||
const { pathToFileURL } = require("node:url");
|
||||
const { chromium } = require("playwright");
|
||||
|
||||
const [work, executable, ...entryArgs] = process.argv.slice(2);
|
||||
const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
function startReader(source) {
|
||||
const child = spawn(executable, [...entryArgs, source, "--port", "0", "--no-open"]);
|
||||
const address = new Promise((resolve, reject) => {
|
||||
let output = "";
|
||||
const timer = setTimeout(() => reject(new Error("View did not print a loopback address")), 10000);
|
||||
function read(chunk) {
|
||||
output += chunk;
|
||||
const match = output.match(/http:\/\/127\.0\.0\.1:[0-9]+\//);
|
||||
if (match) {
|
||||
clearTimeout(timer);
|
||||
resolve(match[0]);
|
||||
}
|
||||
}
|
||||
child.stdout.on("data", read);
|
||||
child.stderr.on("data", read);
|
||||
child.on("error", (error) => { clearTimeout(timer); reject(error); });
|
||||
child.on("exit", (code) => { clearTimeout(timer); reject(new Error(`View quit (${code}): ${output}`)); });
|
||||
});
|
||||
return { child, address };
|
||||
}
|
||||
|
||||
async function compareReading(browser, name) {
|
||||
const source = path.join(work, "project", name);
|
||||
const bundle = path.join(work, name);
|
||||
const manifest = JSON.parse(await fs.readFile(path.join(bundle, "manifest.json")));
|
||||
assert.equal(manifest.mode, "embedded");
|
||||
assert.equal(manifest.theme, "dark");
|
||||
assert.equal(manifest.executed, false);
|
||||
assert.equal(manifest.requires.api_revision, 1);
|
||||
assert.equal(manifest.pages.length, 1);
|
||||
assert.equal(manifest.pages[0].source_sha256, digest(await fs.readFile(source)));
|
||||
assert.equal(manifest.pages[0].source_status, name === "plain.md" ? "markdown-only" : "static-ok");
|
||||
assert.equal(manifest.entry.href, "index.html#detail");
|
||||
assert.ok(manifest.entry.heading_ids.includes("detail"));
|
||||
assert.equal(manifest.files.filter((file) => file.mime === "image/png").length, 1);
|
||||
for (const file of [...manifest.files, ...manifest.assets]) {
|
||||
assert.equal(digest(await fs.readFile(path.join(bundle, file.path))), file.sha256);
|
||||
assert.ok(!file.path.endsWith(".js"));
|
||||
}
|
||||
|
||||
const standalone = await browser.newPage({ viewport: { width: 390, height: 600 } });
|
||||
const reader = startReader(source);
|
||||
let standaloneStyle;
|
||||
try {
|
||||
await standalone.goto(await reader.address);
|
||||
await standalone.locator('[data-action="settings"]').click();
|
||||
await standalone.locator('[data-action="theme"]').click();
|
||||
standaloneStyle = await style(standalone.locator(".mq-document"));
|
||||
assert.equal(await standalone.locator(".mq-document img").count(), 1);
|
||||
} finally {
|
||||
reader.child.kill();
|
||||
await standalone.close();
|
||||
}
|
||||
|
||||
const offline = await browser.newContext({ offline: true, viewport: { width: 390, height: 720 } });
|
||||
try {
|
||||
const page = await offline.newPage();
|
||||
const requests = [];
|
||||
const errors = [];
|
||||
page.on("request", (request) => requests.push(request.url()));
|
||||
page.on("pageerror", (error) => errors.push(String(error)));
|
||||
const host = path.join(work, "host.html");
|
||||
await fs.writeFile(host, `<iframe title="文稿" sandbox="allow-same-origin" src="${name}/${manifest.entry.href}" width="300" height="580"></iframe>`);
|
||||
await page.goto(pathToFileURL(host).href);
|
||||
const frame = page.frameLocator("iframe");
|
||||
const article = frame.locator(".mq-document");
|
||||
assert.deepEqual(await style(article), standaloneStyle);
|
||||
assert.equal(await article.locator("math").count(), 1);
|
||||
assert.equal(await article.locator("blockquote").count(), 1);
|
||||
assert.equal(await article.locator("img").count(), 1);
|
||||
assert.equal(await article.locator("img").evaluate((image) => image.naturalWidth), 1);
|
||||
assert.equal(await frame.locator("script,button,.mq-topbar,.mq-dock").count(), 0);
|
||||
assert.equal(await article.getByRole("link").count(), 1);
|
||||
assert.equal(await frame.locator(":target").getAttribute("id"), "detail");
|
||||
for (const selector of [".mq-table-wrap", ".mq-codeblock pre"]) {
|
||||
const scroller = article.locator(selector);
|
||||
assert.ok(await scroller.evaluate((node) => node.scrollWidth > node.clientWidth));
|
||||
await scroller.focus();
|
||||
await scroller.press("ArrowRight");
|
||||
let scrolled = false;
|
||||
for (let attempt = 0; attempt < 20 && !scrolled; attempt += 1) {
|
||||
await delay(25);
|
||||
scrolled = await scroller.evaluate((node) => node === document.activeElement && node.scrollLeft > 0);
|
||||
}
|
||||
assert.ok(scrolled, `${selector} did not scroll using the keyboard`);
|
||||
}
|
||||
assert.ok(requests.every((url) => url.startsWith("file:") || url.startsWith("data:")), requests);
|
||||
assert.deepEqual(errors, []);
|
||||
} finally {
|
||||
await offline.close();
|
||||
}
|
||||
}
|
||||
|
||||
function style(article) {
|
||||
return article.evaluate(async (element) => {
|
||||
await document.fonts.ready;
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
family: style.fontFamily,
|
||||
color: style.color,
|
||||
size: style.fontSize,
|
||||
scheme: style.colorScheme,
|
||||
mathFont: [...document.fonts].find((font) => font.family === "Noto Sans Math")?.status,
|
||||
stylesheet: document.querySelector('link[rel="stylesheet"]').href.split("/").pop(),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const browser = await chromium.launch();
|
||||
try {
|
||||
for (const name of ["index.mq.md", "plain.md"]) {
|
||||
await compareReading(browser, name);
|
||||
}
|
||||
console.log("Embedded reader: PASS (standalone and sandboxed offline frame, theme, font, anchor, media, keyboard)");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
})().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
Reference in new issue
Block a user