Consolidate layout: tests fixtures, public user docs, and view site.

Move gold samples under tests/, put executable user docs in public/, restyle view, and add catalog plus gh-pages publish workflow.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-04 14:49:44 +08:00
1 parent 29418e14f2
commit 96a7c6ce76
65 files changed
+1770 -432

No files matched your search

+312
View File
@@ -0,0 +1,312 @@
//! OKF-compatible catalog generation: `marqdo catalog` / `sync`.
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use crate::lex::{classify_source, LineKind};
use crate::parse::parse_source;
pub struct CatalogOptions {
pub path: PathBuf,
pub out_dir: PathBuf,
}
struct ModuleInfo {
id: String,
resource: String,
title: String,
imports: Vec<String>,
exports: Vec<String>,
}
pub fn write_catalog(opts: CatalogOptions) -> Result<()> {
let root = if opts.path.is_file() {
opts.path
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."))
} else {
opts.path.clone()
};
let root = root.canonicalize().unwrap_or(root);
let mut files = Vec::new();
if opts.path.is_file() {
files.push(opts.path.canonicalize().unwrap_or(opts.path.clone()));
} else {
collect_mq_md(&root, &root, &mut files)?;
files.sort();
}
fs::create_dir_all(opts.out_dir.join("modules"))
.with_context(|| format!("create {}", opts.out_dir.display()))?;
let version = env!("CARGO_PKG_VERSION");
let mut modules = Vec::new();
let mut had_err = false;
for abs in &files {
let rel = abs
.strip_prefix(&root)
.unwrap_or(abs)
.to_string_lossy()
.replace('\\', "/");
match inspect_file(abs, &rel) {
Ok(info) => modules.push(info),
Err(e) => {
eprintln!("catalog: skip {rel}: {e:#}");
had_err = true;
}
}
}
let catalog_yaml = render_catalog_yaml(&modules, version);
fs::write(opts.out_dir.join("catalog.yaml"), catalog_yaml)?;
let index_md = render_index_md(&modules, version);
fs::write(opts.out_dir.join("index.md"), index_md)?;
for m in &modules {
let stem = m.resource.replace('/', "__").replace('\\', "__");
let stem = stem.trim_end_matches(".mq.md");
let path = opts.out_dir.join("modules").join(format!("{stem}.md"));
fs::write(&path, render_module_md(m, version))?;
}
eprintln!(
"marqdo catalog: {} module(s) → {}",
modules.len(),
opts.out_dir.display()
);
if had_err {
anyhow::bail!("catalog completed with errors");
}
Ok(())
}
fn collect_mq_md(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let p = entry.path();
if p.is_dir() {
collect_mq_md(root, &p, out)?;
} else if p
.file_name()
.and_then(|s| s.to_str())
.map(|s| s.ends_with(".mq.md"))
.unwrap_or(false)
{
out.push(p);
}
}
Ok(())
}
fn inspect_file(abs: &Path, rel: &str) -> Result<ModuleInfo> {
let source = fs::read_to_string(abs)?;
let imports = extract_frontmatter_imports(&source);
let title = extract_frontmatter_title(&source)
.unwrap_or_else(|| rel.trim_end_matches(".mq.md").to_string());
let mut exports = Vec::new();
// Prefer parse for accurate top-level fn names
match parse_source(&source) {
Ok(module) => {
for f in &module.functions {
exports.push(f.name.clone());
}
}
Err(_) => {
for line in classify_source(&source) {
if line.kind != LineKind::Code {
continue;
}
let t = line.text.trim();
if let Some(rest) = t.strip_prefix("# ") {
if !rest.starts_with('#') {
exports.push(rest.to_string());
}
}
}
}
}
let id = rel.trim_end_matches(".mq.md").to_string();
Ok(ModuleInfo {
id,
resource: rel.to_string(),
title,
imports,
exports,
})
}
fn extract_frontmatter_imports(source: &str) -> Vec<String> {
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
let mut imports = Vec::new();
let lines: Vec<&str> = source.lines().collect();
if lines.first().map(|l| l.trim()) != Some("---") {
return imports;
}
for line in lines.iter().skip(1) {
let t = line.trim();
if t == "---" {
break;
}
if let Some(rest) = t.strip_prefix('>') {
let path = rest.trim();
if path.ends_with(".mq.md") {
imports.push(path.to_string());
}
}
}
imports
}
fn extract_frontmatter_title(source: &str) -> Option<String> {
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
let lines: Vec<&str> = source.lines().collect();
if lines.first().map(|l| l.trim()) != Some("---") {
return None;
}
for line in lines.iter().skip(1) {
let t = line.trim();
if t == "---" {
break;
}
if let Some(v) = t.strip_prefix("title:") {
return Some(v.trim().trim_matches('"').to_string());
}
}
None
}
fn yaml_escape(s: &str) -> String {
if s.is_empty()
|| s.contains(':')
|| s.contains('#')
|| s.contains('"')
|| s.contains('\'')
|| s.contains('\n')
|| s.starts_with(' ')
{
format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
} else {
s.to_string()
}
}
fn render_catalog_yaml(modules: &[ModuleInfo], version: &str) -> String {
let mut out = String::new();
out.push_str("# GENERATED by marqdo — do not edit by hand\n");
out.push_str("type: Marqdo Catalog\n");
out.push_str("title: marqdo-project\n");
out.push_str("generated:\n");
out.push_str(&format!(" by: marqdo/{version}\n"));
out.push_str("modules:\n");
for m in modules {
out.push_str(&format!(" - id: {}\n", yaml_escape(&m.id)));
out.push_str(&format!(" resource: {}\n", yaml_escape(&m.resource)));
out.push_str(&format!(" title: {}\n", yaml_escape(&m.title)));
if m.imports.is_empty() {
out.push_str(" imports: []\n");
} else {
out.push_str(" imports:\n");
for i in &m.imports {
out.push_str(&format!(" - {}\n", yaml_escape(i)));
}
}
if m.exports.is_empty() {
out.push_str(" exports: []\n");
} else {
out.push_str(" exports:\n");
for e in &m.exports {
out.push_str(&format!(" - name: {}\n", yaml_escape(e)));
out.push_str(" kind: fn\n");
}
}
}
out
}
fn render_index_md(modules: &[ModuleInfo], version: &str) -> String {
let mut out = String::new();
out.push_str("---\n");
out.push_str("type: Marqdo Catalog\n");
out.push_str("title: marqdo catalog\n");
out.push_str("generated:\n");
out.push_str(&format!(" by: marqdo/{version}\n"));
out.push_str("---\n\n");
out.push_str("# Catalog\n\n");
out.push_str("> Generated by Marqdo. Do not edit by hand.\n\n");
out.push_str("| Module | Resource | Imports |\n");
out.push_str("|--------|----------|--------|\n");
for m in modules {
let stem = m.resource.replace('/', "__");
let stem = stem.trim_end_matches(".mq.md");
out.push_str(&format!(
"| [{}](modules/{stem}.md) | `{}` | {} |\n",
m.title,
m.resource,
if m.imports.is_empty() {
"—".into()
} else {
m.imports.join(", ")
}
));
}
out
}
fn render_module_md(m: &ModuleInfo, version: &str) -> String {
let mut out = String::new();
out.push_str("---\n");
out.push_str("type: Marqdo Module\n");
out.push_str(&format!("title: {}\n", m.title));
out.push_str(&format!("resource: {}\n", m.resource));
if m.imports.is_empty() {
out.push_str("depends: []\n");
} else {
out.push_str("depends:\n");
for i in &m.imports {
out.push_str(&format!(" - {i}\n"));
}
}
if m.exports.is_empty() {
out.push_str("exports: []\n");
} else {
out.push_str("exports:\n");
for e in &m.exports {
out.push_str(&format!(" - {e}\n"));
}
}
out.push_str("generated:\n");
out.push_str(&format!(" by: marqdo/{version}\n"));
out.push_str("---\n\n");
out.push_str(&format!("# {}\n\n", m.title));
out.push_str(&format!(
"> Auto-generated from [`{}`](../../{}). Do not edit by hand.\n\n",
m.resource, m.resource
));
out.push_str("## Dependencies\n\n");
if m.imports.is_empty() {
out.push_str("_None_\n\n");
} else {
for i in &m.imports {
out.push_str(&format!("- `{i}`\n"));
}
out.push('\n');
}
out.push_str("## Exports\n\n");
if m.exports.is_empty() {
out.push_str("_None_\n");
} else {
out.push_str("| Symbol | Kind |\n|--------|------|\n");
for e in &m.exports {
out.push_str(&format!("| `{e}` | fn |\n"));
}
}
out
}
+51 -1
View File
@@ -23,6 +23,24 @@ impl fmt::Display for Span {
}
}
/// Format a path for user-facing diagnostics.
///
/// Strips the Windows extended-length prefix (`\\?\` / `\\?\UNC\`) that
/// `canonicalize` often adds, so messages stay readable.
pub fn display_path(path: &Path) -> String {
let raw = path.display().to_string();
if let Some(rest) = raw.strip_prefix(r"\\?\UNC\") {
format!(r"\\{rest}")
} else if let Some(rest) = raw.strip_prefix(r"\\?\") {
rest.to_string()
} else if let Some(rest) = raw.strip_prefix("//?/") {
// Some tools emit forward-slash forms
rest.to_string()
} else {
raw
}
}
/// Unified diagnostic: `path:line:col: message` (path omitted if unknown).
#[derive(Debug, Error, Clone)]
#[error("{}", self.format_message())]
@@ -47,7 +65,7 @@ impl Diagnostic {
pub fn format_message(&self) -> String {
match &self.path {
Some(p) => format!("{}:{}: {}", p.display(), self.span, self.message),
Some(p) => format!("{}:{}: {}", display_path(p), self.span, self.message),
None => format!("{}: {}", self.span, self.message),
}
}
@@ -57,3 +75,35 @@ impl Diagnostic {
pub fn bail_at(path: Option<&Path>, span: Span, message: impl Into<String>) -> anyhow::Error {
anyhow::Error::new(Diagnostic::new(path, span, message))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_windows_extended_prefix() {
let p = PathBuf::from(r"\\?\E:\marqdo\examples\errors\bad-arity.mq.md");
assert_eq!(
display_path(&p),
r"E:\marqdo\examples\errors\bad-arity.mq.md"
);
}
#[test]
fn strips_unc_extended_prefix() {
let p = PathBuf::from(r"\\?\UNC\server\share\file.mq.md");
assert_eq!(display_path(&p), r"\\server\share\file.mq.md");
}
#[test]
fn diagnostic_message_uses_clean_path() {
let d = Diagnostic::at(
Path::new(r"\\?\E:\marqdo\x.mq.md"),
Span::new(7, 1),
"missing argument for parameter `x`",
);
let msg = d.format_message();
assert!(!msg.contains(r"\\?\"));
assert!(msg.contains(r"E:\marqdo\x.mq.md:7:1:"));
}
}
+1 -1
View File
@@ -122,7 +122,7 @@ mod tests {
#[test]
fn classify_hello_fixture() {
let src = include_str!("../../examples/structure/hello.mq.md");
let src = include_str!("../../tests/structure/hello.mq.md");
let lines = classify_source(src);
assert!(lines.iter().any(|l| l.kind == LineKind::Code && l.text.contains("print")));
assert!(lines.iter().any(|l| l.kind == LineKind::Comment));
+1
View File
@@ -6,6 +6,7 @@
pub mod ast;
pub mod bytecode;
pub mod capture;
pub mod catalog;
pub mod debug;
pub mod diagnostics;
pub mod interp;
+73 -13
View File
@@ -4,11 +4,12 @@ use std::process::ExitCode;
use anyhow::Result;
use clap::{Parser, Subcommand, ValueEnum};
use marqdo::view::{serve, ViewOptions};
use marqdo::catalog::{write_catalog, CatalogOptions};
use marqdo::view::{serve, write_static, OutputOptions, ViewOptions};
use marqdo::{Backend, RunOptions};
#[derive(Parser, Debug)]
#[command(name = "marqdo", version, about = "Marqdo interpreter — run and view .mq.md programs")]
#[command(name = "marqdo", version, about = "Marqdo interpreter — run, view, and catalog .mq.md")]
struct Cli {
#[command(subcommand)]
command: Commands,
@@ -54,19 +55,54 @@ enum Commands {
#[arg(long)]
dump_all: bool,
},
/// Browse `.mq.md` structure + execution in a local webpage
/// Browse `.mq.md` structure + execution (live server or static output)
View {
#[command(subcommand)]
action: Option<ViewAction>,
/// Path when running the live server (default: `.`)
#[arg(value_name = "PATH", global = true)]
path: Option<PathBuf>,
#[arg(long, default_value = "127.0.0.1", global = true)]
host: String,
#[arg(long, default_value_t = 7429, global = true)]
port: u16,
#[arg(long, global = true)]
no_open: bool,
},
/// Generate OKF-compatible catalog YAML + module pages
Catalog {
#[arg(value_name = "PATH")]
path: Option<PathBuf>,
#[arg(long, default_value = "127.0.0.1")]
host: String,
#[arg(short = 'o', long = "out", default_value = ".marqdo")]
out: PathBuf,
},
/// Alias for `catalog`
Sync {
#[arg(value_name = "PATH")]
path: Option<PathBuf>,
#[arg(long, default_value_t = 7429)]
port: u16,
#[arg(short = 'o', long = "out", default_value = ".marqdo")]
out: PathBuf,
},
}
#[derive(Subcommand, Debug)]
enum ViewAction {
/// Write static HTML documentation site
Output {
#[arg(value_name = "PATH")]
path: Option<PathBuf>,
#[arg(short = 'o', long = "out", required = true)]
out: PathBuf,
#[arg(long)]
no_open: bool,
no_exec: bool,
},
}
@@ -115,16 +151,40 @@ fn try_main() -> Result<i32> {
Ok(0)
}
Commands::View {
action,
path,
host,
port,
no_open,
} => {
serve(ViewOptions {
} => match action {
Some(ViewAction::Output {
path: out_path,
out,
no_exec,
}) => {
write_static(OutputOptions {
path: out_path
.or(path)
.unwrap_or_else(|| PathBuf::from(".")),
out_dir: out,
no_exec,
})?;
Ok(0)
}
None => {
serve(ViewOptions {
path: path.unwrap_or_else(|| PathBuf::from(".")),
host,
port,
open_browser: !no_open,
})?;
Ok(0)
}
},
Commands::Catalog { path, out } | Commands::Sync { path, out } => {
write_catalog(CatalogOptions {
path: path.unwrap_or_else(|| PathBuf::from(".")),
host,
port,
open_browser: !no_open,
out_dir: out,
})?;
Ok(0)
}
+3 -3
View File
@@ -525,7 +525,7 @@ mod tests {
#[test]
fn parse_hello() {
let src = include_str!("../../examples/structure/hello.mq.md");
let src = include_str!("../../tests/structure/hello.mq.md");
let m = parse_source(src).unwrap();
assert_eq!(m.functions.len(), 1);
assert_eq!(m.functions[0].name, "Hello World");
@@ -535,7 +535,7 @@ mod tests {
#[test]
fn parse_index() {
let src = include_str!("../../examples/structure/nested-call.mq.md");
let src = include_str!("../../tests/structure/nested-call.mq.md");
let m = parse_source(src).unwrap();
assert!(m.imports.is_empty());
let main = m.functions.iter().find(|f| f.name == "main").unwrap();
@@ -546,7 +546,7 @@ mod tests {
#[test]
fn parse_branch() {
let src = include_str!("../../examples/structure/branch.mq.md");
let src = include_str!("../../tests/structure/branch.mq.md");
let m = parse_source(src).unwrap();
let main = &m.functions[0];
assert!(main.body.iter().any(|s| matches!(s, Stmt::Branch { .. })));
+426 -206
View File
@@ -1,6 +1,6 @@
//! HTML shell for `marqdo view`.
//! HTML shell for `marqdo view` — Apple-inspired monochrome, system fonts only.
use std::path::Path;
use std::path::{Component, Path, PathBuf};
use crate::view::render::FileViewModel;
@@ -17,6 +17,333 @@ pub fn escape(s: &str) -> String {
.collect()
}
/// How navigation hrefs are built.
#[derive(Debug, Clone)]
pub enum LinkMode {
/// Live server: `/file?path=…`
Live,
/// Static export: relative links under `pages/`.
/// `from` is the source rel path of the current page (`None` = index.html).
Static { from: Option<String> },
}
fn stylesheet() -> &'static str {
// Inspired by Apple HIG clarity + docs-site layouts (sticky sidebar, readable
// center column, system grays). Monochrome only; no remote fonts.
r#"
:root {
--bg: #f5f5f7;
--surface: #ffffff;
--ink: #1d1d1f;
--muted: #6e6e73;
--line: #d2d2d7;
--line-strong: #1d1d1f;
--fill: #f5f5f7;
--hover: #e8e8ed;
--focus: #0071e3;
--fail-bg: #fff5f5;
--ok-bg: #f5f5f7;
--radius: 12px;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
margin: 0;
min-height: 100vh;
font-family: var(--sans);
color: var(--ink);
background: var(--bg);
line-height: 1.47;
font-size: 17px;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
a { color: var(--ink); text-decoration: none; }
a:hover { opacity: 0.72; }
a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
#nav-toggle { position: absolute; opacity: 0; pointer-events: none; }
.topbar {
display: none;
align-items: center;
gap: 0.75rem;
padding: 0.7rem 1rem;
border-bottom: 1px solid var(--line);
background: rgba(255,255,255,0.86);
backdrop-filter: saturate(180%) blur(16px);
-webkit-backdrop-filter: saturate(180%) blur(16px);
position: sticky;
top: 0;
z-index: 20;
}
.topbar .brand { margin: 0; font-size: 1.05rem; font-weight: 600; letter-spacing: -0.022em; }
.nav-btn {
appearance: none;
border: 1px solid var(--line);
background: var(--surface);
color: var(--ink);
border-radius: 10px;
width: 2.35rem;
height: 2.35rem;
font-size: 1.05rem;
line-height: 1;
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.15s ease, border-color 0.15s ease;
}
.nav-btn:hover { background: var(--hover); }
.shell {
display: grid;
grid-template-columns: 280px minmax(0, 1fr);
min-height: 100vh;
max-width: 1400px;
margin: 0 auto;
}
.nav {
border-right: 1px solid var(--line);
padding: 1.75rem 1rem 2.5rem 1.15rem;
overflow: auto;
background: var(--bg);
position: sticky;
top: 0;
align-self: start;
height: 100vh;
}
.nav-brand { display: block; padding: 0 0.35rem; }
.brand {
font-size: 1.35rem;
font-weight: 700;
letter-spacing: -0.03em;
margin: 0 0 0.1rem;
}
.tagline {
color: var(--muted);
font-size: 0.78rem;
margin: 0 0 1.5rem;
font-weight: 500;
}
.nav h2 {
font-size: 0.68rem;
text-transform: uppercase;
letter-spacing: 0.09em;
color: var(--muted);
font-weight: 600;
margin: 1.15rem 0.35rem 0.45rem;
}
.nav ul { list-style: none; padding: 0; margin: 0; }
.nav li { margin: 0.08rem 0; }
.nav a.file {
display: block;
padding: 0.42rem 0.65rem;
border-radius: 8px;
border-bottom: none;
color: var(--ink);
font-family: var(--mono);
font-size: 0.78rem;
transition: background 0.12s ease, color 0.12s ease;
}
.nav a.file:hover { background: var(--hover); opacity: 1; }
.nav a.file.active {
background: var(--ink);
color: #fff;
opacity: 1;
font-weight: 500;
}
.folder {
color: var(--muted);
font-size: 0.72rem;
margin: 1rem 0.35rem 0.35rem;
font-weight: 600;
letter-spacing: 0.01em;
}
.panel-wrap {
min-width: 0;
overflow: auto;
background: var(--bg);
}
main.panel {
padding: 2.25rem 2.5rem 4rem;
margin: 0 auto;
width: 100%;
max-width: 58rem;
}
h1.page {
font-size: clamp(1.75rem, 2.4vw, 2.35rem);
font-weight: 700;
letter-spacing: -0.035em;
margin: 0 0 0.3rem;
line-height: 1.15;
}
.meta {
color: var(--muted);
font-size: 0.88rem;
margin: 0 0 1.75rem;
font-family: var(--mono);
}
.status-pill {
display: inline-block;
font-size: 0.68rem;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
padding: 0.18rem 0.5rem;
border-radius: 999px;
border: 1px solid var(--line);
margin-left: 0.5rem;
vertical-align: middle;
}
.status-pill.ok { background: var(--surface); color: var(--muted); }
.status-pill.fail { background: var(--ink); color: #fff; border-color: var(--ink); }
section.block { margin: 2rem 0; }
section.block > h2 {
font-size: 0.72rem;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--muted);
font-weight: 600;
margin: 0 0 0.85rem;
}
.structure {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 0.35rem 0.15rem;
box-shadow: 0 1px 0 rgba(0,0,0,0.02);
}
.card {
border: none;
border-bottom: 1px solid var(--line);
border-radius: 0;
padding: 0.85rem 1.1rem;
margin: 0;
background: transparent;
}
.card:last-child { border-bottom: none; }
.fun-card, .call-card, .branch-card, .loop-card, .ret-card {
border-left: 2px solid var(--line-strong);
padding-left: calc(1.1rem - 2px);
}
.comment-card {
border-left: 2px solid var(--line);
background: transparent;
padding-left: calc(1.1rem - 2px);
}
.badge {
display: inline-block;
font-family: var(--mono);
font-size: 0.66rem;
padding: 0.14rem 0.4rem;
border-radius: 6px;
border: 1px solid var(--line);
background: var(--fill);
color: var(--ink);
margin-right: 0.4rem;
font-weight: 600;
letter-spacing: 0.02em;
}
.params { margin: 0.35rem 0 0; }
.chip {
display: inline-block;
font-family: var(--mono);
font-size: 0.72rem;
padding: 0.14rem 0.45rem;
margin: 0.15rem 0.15rem 0 0;
border-radius: 6px;
background: var(--fill);
border: 1px solid transparent;
color: var(--ink);
}
.nested {
margin: 0.45rem 0 0.15rem 0.15rem;
padding-left: 0.85rem;
border-left: 1px solid var(--line);
}
.arm {
margin: 0.4rem 0;
padding: 0.55rem 0.7rem;
background: var(--fill);
border-radius: 10px;
border: 1px solid transparent;
}
.out, .source {
font-family: var(--mono);
font-size: 0.82rem;
white-space: pre-wrap;
background: var(--surface);
border-radius: var(--radius);
padding: 1rem 1.15rem;
border: 1px solid var(--line);
line-height: 1.55;
box-shadow: 0 1px 0 rgba(0,0,0,0.02);
}
.out.ok { background: var(--ok-bg); }
.out.fail {
background: var(--fail-bg);
border-color: #e4c1c1;
color: var(--ink);
font-weight: 500;
}
.comment-text { color: var(--muted); font-size: 0.92rem; }
code.expr {
font-family: var(--mono);
font-size: 0.84rem;
color: var(--ink);
}
.err { color: var(--ink); font-weight: 600; padding: 0.75rem 1rem; }
.welcome {
max-width: 40rem;
margin: 4rem auto;
text-align: center;
}
.welcome p { color: var(--muted); font-size: 1.05rem; }
.backdrop {
display: none;
position: fixed;
inset: 0;
background: rgba(0,0,0,0.28);
z-index: 25;
animation: fade-in 0.18s ease;
}
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
@media (max-width: 900px) {
.shell { grid-template-columns: 240px minmax(0, 1fr); }
main.panel { max-width: 48rem; padding: 1.75rem 1.5rem 3rem; }
}
@media (max-width: 800px) {
.topbar { display: flex; }
.nav-brand { display: none; }
.shell {
grid-template-columns: 1fr;
max-width: none;
min-height: calc(100vh - 3.25rem);
}
.nav {
position: fixed;
top: 0;
left: 0;
bottom: 0;
width: min(82vw, 300px);
height: 100vh;
z-index: 30;
transform: translateX(-105%);
transition: transform 0.22s cubic-bezier(0.2, 0.8, 0.2, 1);
border-right: 1px solid var(--line);
background: var(--surface);
box-shadow: 8px 0 32px rgba(0,0,0,0.08);
}
#nav-toggle:checked ~ .shell .nav { transform: translateX(0); }
#nav-toggle:checked ~ .backdrop { display: block; }
main.panel {
max-width: none;
padding: 1.4rem 1.15rem 3rem;
}
}
"#
}
pub fn layout(title: &str, nav: &str, main: &str) -> String {
format!(
r##"<!DOCTYPE html>
@@ -24,209 +351,41 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>{title} · marqdo view</title>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,600;9..144,700&family=IBM+Plex+Mono:wght@400;500&family=Sora:wght@400;600&display=swap" rel="stylesheet"/>
<style>
:root {{
--bg0: #0f1c1a;
--bg1: #162824;
--panel: #1c322d;
--ink: #e7f2ee;
--muted: #9bb5ac;
--accent: #3ecf8e;
--accent-dim: #2a9b6a;
--call: #5ec8ff;
--branch: #f0b429;
--loop: #ff7a59;
--ret: #c4a7ff;
--err: #ff6b6b;
--line: rgba(255,255,255,0.08);
}}
* {{ box-sizing: border-box; }}
body {{
margin: 0;
min-height: 100vh;
font-family: "Sora", system-ui, sans-serif;
color: var(--ink);
background:
radial-gradient(1200px 600px at 10% -10%, #1a3d34 0%, transparent 55%),
radial-gradient(900px 500px at 100% 0%, #243528 0%, transparent 50%),
linear-gradient(165deg, var(--bg0), var(--bg1));
}}
a {{ color: var(--accent); text-decoration: none; }}
a:hover {{ text-decoration: underline; }}
.shell {{
display: grid;
grid-template-columns: minmax(220px, 280px) 1fr;
min-height: 100vh;
}}
@media (max-width: 800px) {{
.shell {{ grid-template-columns: 1fr; }}
}}
.nav {{
border-right: 1px solid var(--line);
background: rgba(0,0,0,0.22);
padding: 1.25rem 1rem 2rem;
overflow: auto;
}}
.brand {{
font-family: "Fraunces", Georgia, serif;
font-size: 1.45rem;
font-weight: 700;
letter-spacing: -0.02em;
margin: 0 0 0.25rem;
}}
.brand span {{ color: var(--accent); }}
.tagline {{
color: var(--muted);
font-size: 0.8rem;
margin: 0 0 1.25rem;
}}
.nav h2 {{
font-size: 0.7rem;
text-transform: uppercase;
letter-spacing: 0.12em;
color: var(--muted);
margin: 1rem 0 0.4rem;
}}
.nav ul {{ list-style: none; padding: 0; margin: 0; }}
.nav li {{ margin: 0.15rem 0; }}
.nav a.file {{
display: block;
padding: 0.35rem 0.5rem;
border-radius: 6px;
color: var(--ink);
font-family: "IBM Plex Mono", monospace;
font-size: 0.78rem;
}}
.nav a.file:hover, .nav a.file.active {{
background: rgba(62, 207, 142, 0.12);
text-decoration: none;
}}
.folder {{ color: var(--muted); font-size: 0.75rem; margin-top: 0.75rem; }}
main.panel {{
padding: 1.5rem 1.75rem 3rem;
overflow: auto;
}}
h1.page {{
font-family: "Fraunces", Georgia, serif;
font-size: 1.75rem;
margin: 0 0 0.5rem;
}}
.meta {{ color: var(--muted); font-size: 0.85rem; margin-bottom: 1.5rem; }}
section.block {{
margin: 1.25rem 0 1.75rem;
}}
section.block > h2 {{
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.1em;
color: var(--muted);
margin: 0 0 0.65rem;
border-bottom: 1px solid var(--line);
padding-bottom: 0.35rem;
}}
.card {{
background: var(--panel);
border: 1px solid var(--line);
border-radius: 10px;
padding: 0.85rem 1rem;
margin: 0.55rem 0;
}}
.fun-card {{ border-left: 3px solid var(--accent); }}
.call-card {{ border-left: 3px solid var(--call); }}
.branch-card {{ border-left: 3px solid var(--branch); }}
.loop-card {{ border-left: 3px solid var(--loop); }}
.ret-card {{ border-left: 3px solid var(--ret); }}
.badge {{
display: inline-block;
font-family: "IBM Plex Mono", monospace;
font-size: 0.7rem;
padding: 0.1rem 0.4rem;
border-radius: 4px;
background: rgba(255,255,255,0.06);
margin-right: 0.35rem;
}}
.params {{ margin: 0.35rem 0; }}
.chip {{
display: inline-block;
font-family: "IBM Plex Mono", monospace;
font-size: 0.75rem;
padding: 0.15rem 0.45rem;
margin: 0.15rem;
border-radius: 999px;
background: rgba(62, 207, 142, 0.15);
color: var(--accent);
}}
.nested {{ margin-left: 0.85rem; padding-left: 0.75rem; border-left: 1px dashed var(--line); }}
.arm {{
margin: 0.4rem 0;
padding: 0.5rem 0.65rem;
background: rgba(0,0,0,0.2);
border-radius: 8px;
}}
.out {{
font-family: "IBM Plex Mono", monospace;
font-size: 0.85rem;
white-space: pre-wrap;
background: #0a1210;
border-radius: 8px;
padding: 0.85rem 1rem;
border: 1px solid var(--line);
}}
.out.ok {{ box-shadow: inset 3px 0 0 var(--accent-dim); }}
.out.fail {{ box-shadow: inset 3px 0 0 var(--err); color: #ffc9c9; }}
.source {{
font-family: "IBM Plex Mono", monospace;
font-size: 0.78rem;
white-space: pre-wrap;
background: #0a1210;
border-radius: 8px;
padding: 0.85rem 1rem;
border: 1px solid var(--line);
line-height: 1.45;
}}
.err {{ color: var(--err); }}
.comment-card {{
border-left: 3px solid var(--muted);
background: rgba(255,255,255,0.03);
}}
.comment-text {{
color: var(--muted);
font-size: 0.9rem;
line-height: 1.45;
}}
code.expr {{
font-family: "IBM Plex Mono", monospace;
font-size: 0.82rem;
color: var(--ink);
}}
.welcome {{ max-width: 36rem; }}
.welcome p {{ color: var(--muted); line-height: 1.55; }}
</style>
<title>{title} · marqdo</title>
<style>{css}</style>
</head>
<body>
<input type="checkbox" id="nav-toggle"/>
<label class="backdrop" for="nav-toggle" aria-hidden="true"></label>
<header class="topbar">
<label class="nav-btn" for="nav-toggle" aria-label="Menu">☰</label>
<p class="brand">marqdo</p>
</header>
<div class="shell">
<aside class="nav">
<p class="brand">marq<span>do</span> view</p>
<p class="tagline">Markup structure · live output</p>
<div class="nav-brand">
<p class="brand">marqdo</p>
<p class="tagline">view</p>
</div>
{nav}
</aside>
<div class="panel-wrap">
<main class="panel">
{main}
</main>
</div>
</div>
</body>
</html>
"##,
title = escape(title),
css = stylesheet(),
nav = nav,
main = main
)
}
pub fn nav_html(files: &[std::path::PathBuf], active: Option<&str>) -> String {
pub fn nav_html(files: &[PathBuf], active: Option<&str>, links: &LinkMode) -> String {
let mut out = String::from("<h2>Files</h2><ul>");
let mut last_folder = String::new();
for f in files {
@@ -253,16 +412,68 @@ pub fn nav_html(files: &[std::path::PathBuf], active: Option<&str>) -> String {
} else {
""
};
let href = format!("/file?path={}", urlencoding_encode(&rel));
let href = href_file(links, &rel);
out.push_str(&format!(
"<li><a class=\"file{active_cls}\" href=\"{href}\">{}</a></li>",
"<li><a class=\"file{active_cls}\" href=\"{}\">{}</a></li>",
escape(&href),
escape(name)
));
}
out.push_str("</ul>");
// index link for static pages
if matches!(links, LinkMode::Static { from: Some(_) }) {
let home = href_index(links);
out.insert_str(
0,
&format!(
"<p style=\"margin:0 0 0.75rem\"><a href=\"{}\">Index</a></p>",
escape(&home)
),
);
}
out
}
fn href_file(links: &LinkMode, target_rel: &str) -> String {
match links {
LinkMode::Live => format!("/file?path={}", urlencoding_encode(target_rel)),
LinkMode::Static { from: None } => format!("pages/{}.html", target_rel),
LinkMode::Static {
from: Some(from_rel),
} => relative_page_href(from_rel, target_rel),
}
}
fn href_index(links: &LinkMode) -> String {
match links {
LinkMode::Live => "/".into(),
LinkMode::Static { from: None } => "index.html".into(),
LinkMode::Static {
from: Some(from_rel),
} => {
let depth = Path::new(from_rel)
.parent()
.map(|p| p.components().filter(|c| matches!(c, Component::Normal(_))).count())
.unwrap_or(0);
// pages/<dirs...>/file.html → up (depth+1) to OUT_DIR
format!("{}index.html", "../".repeat(depth + 1))
}
}
}
/// From `pages/<from>.html` to `pages/<to>.html`.
fn relative_page_href(from_rel: &str, to_rel: &str) -> String {
let from_parent = Path::new(from_rel).parent().unwrap_or_else(|| Path::new(""));
let to_path = PathBuf::from(format!("{to_rel}.html"));
let mut ups = 0usize;
for c in from_parent.components() {
if matches!(c, Component::Normal(_)) {
ups += 1;
}
}
format!("{}{}", "../".repeat(ups), to_path.to_string_lossy().replace('\\', "/"))
}
fn urlencoding_encode(s: &str) -> String {
let mut out = String::new();
for b in s.bytes() {
@@ -276,43 +487,56 @@ fn urlencoding_encode(s: &str) -> String {
out
}
pub fn page_index(files: &[std::path::PathBuf], only: Option<&Path>) -> String {
let nav = nav_html(files, None);
pub fn page_index(files: &[PathBuf], only: Option<&Path>, links: &LinkMode) -> String {
let nav = nav_html(files, None, links);
let main = if let Some(p) = only {
let rel = p.to_string_lossy().replace('\\', "/");
format!(
"<div class=\"welcome\"><h1 class=\"page\">Single file</h1><p class=\"meta\">Open <a href=\"/file?path={}\">{}</a></p></div>",
urlencoding_encode(&rel),
"<div class=\"welcome\"><h1 class=\"page\">marqdo</h1><p class=\"meta\">Open <a href=\"{}\">{}</a></p></div>",
escape(&href_file(links, &rel)),
escape(&rel)
)
} else if files.is_empty() {
"<div class=\"welcome\"><h1 class=\"page\">marqdo</h1><p>No <code>.mq.md</code> files found in this path.</p></div>".into()
} else {
// Prefer callers to render the first file at `/` / index.html; this is a fallback.
let first = files[0].to_string_lossy().replace('\\', "/");
format!(
"<div class=\"welcome\"><h1 class=\"page\">Browse</h1><p>Select a <code>.mq.md</code> file in the index. Structure is rendered from the AST; output comes from the same pipeline as <code>marqdo run</code>.</p><p class=\"meta\">{} file(s)</p></div>",
files.len()
"<div class=\"welcome\"><h1 class=\"page\">marqdo</h1><p>Opening <a href=\"{}\">{}</a>…</p></div>",
escape(&href_file(links, &first)),
escape(&first)
)
};
layout("index", &nav, &main)
}
pub fn page_file(files: &[std::path::PathBuf], rel: &str, vm: &FileViewModel) -> String {
let nav = nav_html(files, Some(rel));
pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkMode) -> String {
let nav = nav_html(files, Some(rel), links);
let status = if vm.ok { "ok" } else { "fail" };
let status_label = if vm.ok { "ok" } else { "fail" };
let out_text = if vm.ok {
if vm.stdout.is_empty() {
"(no stdout)".to_string()
"(no stdout)".into()
} else {
escape(&vm.stdout)
}
} else if vm.stderr.is_empty() {
"(skipped)".into()
} else {
escape(&vm.stderr)
};
let title = Path::new(rel)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(rel)
.trim_end_matches(".mq.md");
let main = format!(
r#"
<h1 class="page">{title}</h1>
<h1 class="page">{title}<span class="status-pill {status}">{status_label}</span></h1>
<p class="meta">{rel}</p>
<section class="block">
<h2>Structure</h2>
{structure}
<div class="structure">{structure}</div>
</section>
<section class="block">
<h2>Execution</h2>
@@ -323,15 +547,11 @@ pub fn page_file(files: &[std::path::PathBuf], rel: &str, vm: &FileViewModel) ->
<pre class="source">{source}</pre>
</section>
"#,
title = escape(
Path::new(rel)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or(rel)
),
title = escape(title),
status = status,
status_label = status_label,
rel = escape(rel),
structure = vm.structure_html,
status = status,
out = out_text,
source = escape(&vm.source),
);
+52 -14
View File
@@ -1,8 +1,11 @@
//! `marqdo view` — local HTML browser for `.mq.md` structure + output.
mod html;
mod output;
mod render;
pub use output::{write_static, OutputOptions};
use std::fs;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
@@ -11,7 +14,7 @@ use std::process::Command;
use anyhow::{bail, Context, Result};
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
use crate::view::html::{escape, page_file, page_index};
use crate::view::html::{escape, page_file, page_index, LinkMode};
use crate::view::render::{render_module_structure, FileViewModel};
use crate::{run_file_capture, RunOptions};
@@ -22,12 +25,10 @@ pub struct ViewOptions {
pub open_browser: bool,
}
struct ViewRoot {
/// Directory that paths are resolved against.
root: PathBuf,
/// If Some, only this relative file is in scope (single-file mode).
only_file: Option<PathBuf>,
files: Vec<PathBuf>,
pub(crate) struct ViewRoot {
pub root: PathBuf,
pub only_file: Option<PathBuf>,
pub files: Vec<PathBuf>,
}
/// Block serving until Ctrl+C (process kill).
@@ -54,7 +55,7 @@ pub fn serve(opts: ViewOptions) -> Result<()> {
Ok(())
}
fn build_root(path: &Path) -> Result<ViewRoot> {
pub(crate) fn build_root(path: &Path) -> Result<ViewRoot> {
let path = if path.exists() {
path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
} else {
@@ -124,14 +125,23 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> {
let (path_part, query) = split_url(&url);
match path_part {
"/" | "/index.html" => {
let body = page_index(&root.files, root.only_file.as_deref());
respond_html(request, body)
// Default: open the first file in the folder (sorted), no welcome pick screen.
if let Some(first) = root.files.first() {
let rel = first.to_string_lossy().replace('\\', "/");
let resolved = resolve_rel(root, &rel)?;
let vm = build_file_view(&resolved, &rel)?;
let body = page_file(&root.files, &rel, &vm, &LinkMode::Live);
respond_html(request, body)
} else {
let body = page_index(&root.files, None, &LinkMode::Live);
respond_html(request, body)
}
}
"/file" => {
let rel = query_param(query, "path").unwrap_or_default();
let resolved = resolve_rel(root, &rel)?;
let vm = build_file_view(&resolved, &rel)?;
let body = page_file(&root.files, &rel, &vm);
let body = page_file(&root.files, &rel, &vm, &LinkMode::Live);
respond_html(request, body)
}
"/api/tree" => {
@@ -146,18 +156,22 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> {
}
}
fn build_file_view(abs: &Path, rel: &str) -> Result<FileViewModel> {
pub(crate) fn build_file_view(abs: &Path, rel: &str) -> Result<FileViewModel> {
let source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?;
let structure = match crate::load::load_module(abs) {
Ok(module) => render_module_structure(&module, &source),
Err(e) => format!(
"<div class=\"err\">parse/load error: {}</div>",
escape(&format!("{e:#}"))
escape(&tidy_user_error(&format!("{e:#}"), abs, rel))
),
};
let (stdout, stderr, ok) = match run_file_capture(abs, &RunOptions::default()) {
Ok(cap) => (cap.stdout, String::new(), true),
Err(e) => (String::new(), format!("{e:#}"), false),
Err(e) => (
String::new(),
tidy_user_error(&format!("{e:#}"), abs, rel),
false,
),
};
Ok(FileViewModel {
rel_path: rel.to_string(),
@@ -169,6 +183,30 @@ fn build_file_view(abs: &Path, rel: &str) -> Result<FileViewModel> {
})
}
/// Prefer view-relative paths and strip Windows `\\?\` noise in error text.
fn tidy_user_error(msg: &str, abs: &Path, rel: &str) -> String {
use crate::diagnostics::display_path;
let mut s = msg.to_string();
let abs_disp = abs.display().to_string();
let abs_clean = display_path(abs);
for candidate in [
abs_disp.as_str(),
abs_clean.as_str(),
&abs_disp.replace('/', "\\"),
&abs_clean.replace('/', "\\"),
&abs_disp.replace('\\', "/"),
&abs_clean.replace('\\', "/"),
] {
if !candidate.is_empty() {
s = s.replace(candidate, rel);
}
}
// Leftover extended prefixes anywhere in the message
s = s.replace(r"\\?\", "");
s = s.replace("//?/", "");
s
}
fn resolve_rel(root: &ViewRoot, rel: &str) -> Result<PathBuf> {
if rel.is_empty() {
bail!("missing path");
+73
View File
@@ -0,0 +1,73 @@
//! Static HTML export: `marqdo view output`.
use std::fs;
use std::path::PathBuf;
use anyhow::{Context, Result};
use crate::view::html::{page_file, page_index, LinkMode};
use crate::view::{build_file_view, build_root, ViewRoot};
pub struct OutputOptions {
pub path: PathBuf,
pub out_dir: PathBuf,
pub no_exec: bool,
}
pub fn write_static(opts: OutputOptions) -> Result<()> {
let root = build_root(&opts.path)?;
fs::create_dir_all(&opts.out_dir)
.with_context(|| format!("create {}", opts.out_dir.display()))?;
let pages_root = opts.out_dir.join("pages");
let mut first_page_html: Option<String> = None;
for rel_pb in &root.files {
let rel = rel_pb.to_string_lossy().replace('\\', "/");
let abs = resolve_abs(&root, &rel)?;
let mut vm = build_file_view(&abs, &rel)?;
if opts.no_exec {
vm.stdout.clear();
vm.stderr = "execution skipped (--no-exec)".into();
vm.ok = true;
}
let links = LinkMode::Static {
from: Some(rel.clone()),
};
let html = page_file(&root.files, &rel, &vm, &links);
let out_file = pages_root.join(format!("{rel}.html"));
if let Some(parent) = out_file.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&out_file, html).with_context(|| format!("write {}", out_file.display()))?;
if first_page_html.is_none() {
// index.html = first file (same content, links rooted at OUT_DIR)
first_page_html = Some(page_file(
&root.files,
&rel,
&vm,
&LinkMode::Static { from: None },
));
}
}
let index_html = first_page_html.unwrap_or_else(|| {
page_index(&root.files, root.only_file.as_deref(), &LinkMode::Static { from: None })
});
let index_path = opts.out_dir.join("index.html");
fs::write(&index_path, index_html)
.with_context(|| format!("write {}", index_path.display()))?;
eprintln!(
"marqdo view output: {} page(s) → {}",
root.files.len(),
opts.out_dir.display()
);
Ok(())
}
fn resolve_abs(root: &ViewRoot, rel: &str) -> Result<PathBuf> {
let abs = root.root.join(rel);
Ok(abs.canonicalize().unwrap_or(abs))
}
+1 -1
View File
@@ -413,7 +413,7 @@ mod tests {
#[test]
fn structure_keeps_comments_and_surface_expr() {
let src = include_str!("../../examples/structure/nested-call.mq.md");
let src = include_str!("../../tests/structure/nested-call.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&module, src);
assert!(html.contains("comment-card"));