diff --git a/README.md b/README.md index d1cf2bb..de6d9a1 100644 --- a/README.md +++ b/README.md @@ -42,9 +42,7 @@ site = "smol" HTTP and Spartan route by the hostname the request carries, falling back to `default_site`; Nex and Gopher carry none, so their listener names one site outright. Every format a listener serves must be compiled in, which `--check` reports. A `.itsybitsy.toml` in a content directory sets rendering options for that directory — `[defaults]` for all its Markdown files, `[page."name.md"]` for one — with no inheritance from parent directories. Editing it re-renders on the next request. -A site can set `mews_profile = true` to render its `xhtmlmp` and `html` output as [Mews Profile](https://mews.page/spec/) pages: the XML declaration, the XHTML-MP 1.2 doctype, the conformance marker, the viewport tag and the default stylesheet link, with raw HTML and off-site or `data:` images dropped rather than passed through. The declaration stays in the `text/html` form too, unlike an ordinary page's, because section 3.1 requires it and a validator reads whichever bytes it was served; a browser logs a warning for it and renders the page the same. The stylesheet itself is served from an embedded copy, at whatever path the link's `href` resolves to, so there is nothing to place in the content root. Sites sharing one root must agree on this setting, since they share one render cache. - -A site may also set `feed` to the URL of its Atom feed, which is then declared in the head of every `xhtmlmp` and `html` page so a client can subscribe without reading the body (Mews Profile 6.2). Give it absolute: a capsule rarely carries the feed its web site publishes, so a root-relative path would point at a document this server has no file for. Sites sharing one root must agree on it too. +A site can set `mews_profile = true` to render its `xhtmlmp` and `html` output as [Mews Profile](https://mews.page/spec/) pages: the XHTML-MP 1.2 doctype, the conformance marker, the viewport tag and the default stylesheet link, with raw HTML and off-site or `data:` images dropped rather than passed through. Sites sharing one root must agree on this setting, since they share one render cache. ### Formats and protocols diff --git a/bin/src/proto/gemini.rs b/bin/src/proto/gemini.rs index 0dcd1cb..cb11680 100644 --- a/bin/src/proto/gemini.rs +++ b/bin/src/proto/gemini.rs @@ -68,9 +68,6 @@ pub fn serve(listener: &Listener, mut stream: TcpStream) -> Result<()> { std::io::copy(&mut file, &mut stream)?; Ok(()) } - Ok(Resolution::Found(Resource::Embedded { bytes, media_type })) => { - body_response(&mut stream, media_type, bytes) - } Ok(Resolution::Redirect(location)) => header(&mut stream, 31, &location), Ok(Resolution::NotFound) => header(&mut stream, 51, "Not found"), Err(err) => { diff --git a/bin/src/proto/gopher.rs b/bin/src/proto/gopher.rs index e727def..6c5b380 100644 --- a/bin/src/proto/gopher.rs +++ b/bin/src/proto/gopher.rs @@ -55,10 +55,6 @@ pub fn serve(listener: &Listener, mut stream: TcpStream) -> Result<()> { std::io::copy(&mut file, &mut stream)?; Ok(()) } - Ok(Resolution::Found(Resource::Embedded { bytes, .. })) => { - stream.write_all(bytes)?; - Ok(()) - } // resolve_flat follows redirects and sub-documents to real content. Ok(_) => text(&mut stream, b"Not found\n"), Err(err) => { diff --git a/bin/src/proto/http.rs b/bin/src/proto/http.rs index d75d150..bc63d47 100644 --- a/bin/src/proto/http.rs +++ b/bin/src/proto/http.rs @@ -175,9 +175,6 @@ pub fn serve(listener: &Listener, mut stream: TcpStream) -> Result<()> { } Ok(()) } - Ok(Resolution::Found(Resource::Embedded { bytes, media_type })) => { - respond(&mut stream, 200, "OK", media_type, bytes, &[], head_only) - } Ok(Resolution::Redirect(location)) => respond( &mut stream, 301, diff --git a/bin/src/proto/nex.rs b/bin/src/proto/nex.rs index 46cbe2d..346cdb5 100644 --- a/bin/src/proto/nex.rs +++ b/bin/src/proto/nex.rs @@ -45,9 +45,6 @@ pub fn serve(listener: &Listener, mut stream: TcpStream) -> Result<()> { let mut file = std::fs::File::open(&path)?; std::io::copy(&mut file, &mut stream)?; } - Ok(Resolution::Found(Resource::Embedded { bytes, .. })) => { - stream.write_all(bytes)?; - } // resolve_flat follows redirects and sub-documents to real content, so // neither reaches here; they are matched for completeness. Ok(_) => stream.write_all(b"Not found\n")?, diff --git a/bin/src/proto/spartan.rs b/bin/src/proto/spartan.rs index f1e5de8..348c736 100644 --- a/bin/src/proto/spartan.rs +++ b/bin/src/proto/spartan.rs @@ -73,9 +73,6 @@ pub fn serve(listener: &Listener, mut stream: TcpStream) -> Result<()> { std::io::copy(&mut file, &mut stream)?; Ok(()) } - Ok(Resolution::Found(Resource::Embedded { bytes, media_type })) => { - status(&mut stream, 2, media_type, bytes) - } Ok(Resolution::Redirect(location)) => status(&mut stream, 3, &location, b""), Ok(Resolution::NotFound) => status(&mut stream, 4, "Not found", b""), Err(err) => { diff --git a/core/assets/mews-0.1.css b/core/assets/mews-0.1.css deleted file mode 100644 index fc0d8ed..0000000 --- a/core/assets/mews-0.1.css +++ /dev/null @@ -1,106 +0,0 @@ -/* Mews Profile default stylesheet 0.1 */ - -/* Base: light theme */ -body { - background-color: #faf8f3; - color: #1f1f1f; - font-family: "Atkinson Hyperlegible", Verdana, Tahoma, system-ui, sans-serif; - font-size: 106%; - line-height: 1.5; - margin: 0 auto; - padding: 1em; - max-width: 40em; -} - -h1, h2, h3, h4, h5, h6 { - font-weight: bold; - line-height: 1.25; - margin: 1.6em 0 0.5em 0; -} -h1 { font-size: 1.6em; margin-top: 0.5em; } -h2 { font-size: 1.3em; } -h3 { font-size: 1.1em; } -h4, h5, h6 { font-size: 1em; } - -p, ul, ol, dl, blockquote, pre, table, address { - margin: 0 0 1em 0; -} -ul, ol { padding-left: 1.5em; } -li { margin-bottom: 0.25em; } -dt { font-weight: bold; } -dd { margin: 0 0 0.5em 1.5em; } - -a { color: #1a4f9c; text-decoration: underline; } -a:visited { color: #5b2a86; } -a:focus, a:active { outline: 2px solid #1a4f9c; } - -blockquote { - margin-left: 0; - padding-left: 1em; - border-left: 3px solid #c9c4b8; -} - -pre, code, kbd, samp { - font-family: "Source Code Pro", Consolas, Menlo, "DejaVu Sans Mono", monospace; - font-size: 0.9em; -} -pre { - background-color: #efece4; - padding: 0.75em; - overflow: auto; -} - -hr { - border: 0; - border-top: 1px solid #c9c4b8; - margin: 2em 0; -} - -table { border-collapse: collapse; } -th, td { - border: 1px solid #c9c4b8; - padding: 0.3em 0.6em; - text-align: left; - vertical-align: top; -} -caption { font-weight: bold; text-align: left; } - -img { - display: block; - max-width: 100%; - height: auto; - border: 0; -} - -input, select, textarea { font-size: 1em; font-family: inherit; } - -/* Body variants: light */ -body.mews-warm { background-color: #fbf4e8; color: #2a2420; } -body.mews-warm a { color: #8a3d14; } -body.mews-cool { background-color: #f3f6fa; color: #1c2430; } -body.mews-cool a { color: #1a4f9c; } -body.mews-green { background-color: #f2f6ef; color: #1f2a1f; } -body.mews-green a { color: #24502a; } -body.mews-mono { background-color: #e8ebe1; color: #1e2219; } -body.mews-mono a { color: #1e2219; } - -/* Dark theme: follows the system setting */ -@media (prefers-color-scheme: dark) { - body { background-color: #18191b; color: #e3e1dc; } - a { color: #8fb8f5; } - a:visited { color: #c9a3f2; } - a:focus, a:active { outline-color: #8fb8f5; } - blockquote, hr, th, td { border-color: #45464a; } - pre { background-color: #222326; } - - body.mews-warm { background-color: #1d1916; color: #e8dfd3; } - body.mews-warm a { color: #f0b48a; } - body.mews-cool { background-color: #161a20; color: #dde4ee; } - body.mews-cool a { color: #8fb8f5; } - body.mews-green { background-color: #161b16; color: #dbe6d8; } - body.mews-green a { color: #9fd39a; } - body.mews-mono { background-color: #1b1d18; color: #c8d0b8; } - body.mews-mono a { color: #c8d0b8; } -} - -html { color-scheme: light dark; } \ No newline at end of file diff --git a/core/src/config.rs b/core/src/config.rs index d9cec90..fd3a320 100644 --- a/core/src/config.rs +++ b/core/src/config.rs @@ -55,13 +55,6 @@ pub struct SiteSpec { /// profile's permitted-element list cannot otherwise be guaranteed. #[serde(default)] pub mews_profile: bool, - /// The site's Atom feed, declared in the head of its `xhtmlmp`/`html` - /// pages (mews.page/spec 6.2) so a client can subscribe without reading - /// the body. Absolute: a capsule rarely carries the feed its web site - /// publishes, so a root-relative path would point at a document this - /// server has no file for. - #[serde(default)] - pub feed: Option, } #[derive(Debug, Deserialize)] @@ -184,32 +177,21 @@ impl ServerConfig { let hosts = self.build_host_map()?; let formats = self.validate_listeners(available_formats)?; let shared_roots = group_shared_roots(&roots); - self.validate_shared_markup(&shared_roots)?; + self.validate_shared_mews_profile(&shared_roots)?; Ok(Checked { hosts, roots: roots.clone(), shared_roots, formats }) } /// Sites sharing a root share one [`crate::site::Site`] and so one render /// cache; a page rendered once there cannot differ by which name served the - /// request, so every setting that changes its markup must agree within a - /// group. - fn validate_shared_markup(&self, shared_roots: &[Vec]) -> Result<(), Error> { - self.validate_shared(shared_roots, "mews_profile", |spec| spec.mews_profile)?; - self.validate_shared(shared_roots, "feed", |spec| spec.feed.clone()) - } - - fn validate_shared( - &self, - shared_roots: &[Vec], - key: &str, - of: impl Fn(&SiteSpec) -> T, - ) -> Result<(), Error> { + /// request, so `mews_profile` must agree within a group. + fn validate_shared_mews_profile(&self, shared_roots: &[Vec]) -> Result<(), Error> { for group in shared_roots { - let mut settings = group.iter().map(|name| of(&self.site[name])); - let Some(first) = settings.next() else { continue }; + let mut settings = group.iter().map(|name| self.site[name].mews_profile); + let first = settings.next().unwrap_or(false); if settings.any(|value| value != first) { return Err(Error::config(format!( - "sites {} share one root, so {key} must agree between them", + "sites {} share one root, so mews_profile must agree between them", group.join(", ") ))); } diff --git a/core/src/render.rs b/core/src/render.rs index eaa859a..3915cb8 100644 --- a/core/src/render.rs +++ b/core/src/render.rs @@ -39,18 +39,6 @@ pub trait Renderer: Send + Sync { fn render(&self, doc: &Doc, ctx: &RenderCtx<'_>) -> Result; } -/// What a Mews Profile page needs beyond the document itself (mews.page/spec). -/// Present when the site has opted in, absent otherwise, so one `Option` says -/// both whether the profile applies and what it applies with. -#[derive(Debug, Clone, Copy)] -pub struct Mews<'a> { - /// The site's own hostnames, for judging an image `src` as same-site (4.2). - pub hosts: &'a [String], - /// The site's Atom feed, declared in the head (6.2). Absolute, since a - /// capsule need not host the feed its web site publishes. - pub feed: Option<&'a str>, -} - pub struct RenderCtx<'a> { /// Canonical root-relative URL of this document: `/`, `/about`, `/dir/`. A /// format that addresses sub-documents builds their URLs from this. @@ -60,10 +48,11 @@ pub struct RenderCtx<'a> { pub title: &'a str, pub settings: &'a PageSettings, pub width: Option, - /// Mews Profile settings, present when the site has opted in. Threaded - /// through so a renderer that cares can switch its markup without reaching - /// into site configuration itself. - pub mews: Option>, + /// The site's own hostnames, present when it has opted into Mews Profile + /// compliance (mews.page/spec) and absent otherwise. Threaded through so a + /// renderer that cares can switch its markup and judge an image `src` as + /// same-site, without reaching into site configuration itself. + pub mews_hosts: Option<&'a [String]>, } pub struct Rendered { @@ -128,7 +117,7 @@ impl Registry { url: &str, settings: &PageSettings, fallback_title: &str, - mews: Option>, + mews_hosts: Option<&[String]>, ) -> Result { let title = settings .title @@ -153,7 +142,7 @@ impl Registry { title: &page.title, settings, width: renderer.default_width(), - mews, + mews_hosts, }; // Format gates are resolved here, so no renderer meets one and a // gated run costs nothing extra in the cache: bodies are already @@ -233,7 +222,7 @@ mod tests { // after gates — is visible in the body. format!( "{} {} {:?} {} {:?} {:?}", - self.id, ctx.url, ctx.width, ctx.title, doc.blocks, ctx.mews + self.id, ctx.url, ctx.width, ctx.title, doc.blocks, ctx.mews_hosts ) .into_bytes(), )) @@ -280,16 +269,13 @@ mod tests { } #[test] - fn mews_settings_reach_the_renderer_when_the_site_opted_in() { + fn mews_hosts_reaches_the_renderer_when_the_site_opted_in() { let formats = vec!["one".to_string()]; let hosts = vec!["example.test".to_string()]; - let mews = Mews { hosts: &hosts, feed: Some("https://example.test/feed.xml") }; let page = registry() - .page(&formats, &doc(None), "/x", &PageSettings::default(), "x", Some(mews)) + .page(&formats, &doc(None), "/x", &PageSettings::default(), "x", Some(&hosts)) .unwrap(); - let body = String::from_utf8_lossy(page.body("one").unwrap()).to_string(); - assert!(body.contains("example.test"), "{body}"); - assert!(body.contains("feed.xml"), "{body}"); + assert!(String::from_utf8_lossy(page.body("one").unwrap()).contains("example.test")); let unset = registry() .page(&formats, &doc(None), "/x", &PageSettings::default(), "x", None) diff --git a/core/src/site.rs b/core/src/site.rs index 43de368..3eda4ab 100644 --- a/core/src/site.rs +++ b/core/src/site.rs @@ -16,23 +16,13 @@ use crate::error::Error; use crate::mime; use crate::parse; use crate::path::{clean_path, url_for}; -use crate::render::{Mews, Page, Registry, title_from_stem}; +use crate::render::{Page, Registry, title_from_stem}; /// How deep a chain of server-side redirects `resolve_flat` will follow. Every /// redirect currently points at a directly resolvable document, so one hop is /// always enough; the cap is there so a future rule cannot loop. const MAX_FLAT_HOPS: usize = 5; -/// Name a Mews page's stylesheet `` carries (`wap::xhtmlmp::MEWS_HEAD_EXTRA`). -const MEWS_STYLESHEET_NAME: &str = "mews-0.1.css"; - -/// The stylesheet itself, byte for byte as published at mews.page/spec (5.1). -/// Served from here rather than from a file an operator must place in every -/// site's root: the link's name and content are pinned to the spec version a -/// site opts into, not something a site chooses, so there is nothing for a -/// copy on disk to add and every way for it to go stale or go missing. -const MEWS_STYLESHEET: &[u8] = include_bytes!("../assets/mews-0.1.css"); - /// What a request path resolved to. #[derive(Debug)] pub enum Resolution { @@ -48,9 +38,6 @@ pub enum Resource { Document { url: String, page: Arc }, /// A file served byte for byte, streamed rather than buffered. Raw { path: PathBuf, media_type: &'static str }, - /// A byte slice built into the binary, served like `Raw` but with no file - /// to open: currently only the Mews Profile stylesheet. - Embedded { bytes: &'static [u8], media_type: &'static str }, /// A sub-document of a page, addressed under the page's own URL. /// /// Only a paginating format produces these, so whether this slug exists @@ -82,10 +69,6 @@ pub struct Site { /// differing host lists keeps only that one's, which is an accepted /// simplification rather than a union of them all. hosts: Vec, - /// This site's Atom feed (`SiteSpec::feed`), declared in the head of a - /// Mews page. Validation requires every site sharing this root to agree, - /// since the declaration is part of the cached markup. - feed: Option, } impl Site { @@ -97,7 +80,6 @@ impl Site { formats: Vec, mews_profile: bool, hosts: Vec, - feed: Option, ) -> Result { let root = root.canonicalize().map_err(|cause| Error::Io { path: root.to_path_buf(), cause })?; @@ -113,7 +95,6 @@ impl Site { formats, mews_profile, hosts, - feed, }) } @@ -129,20 +110,8 @@ impl Site { /// | `/foo` | `foo.md`, else `foo/index.md` | /// | `/foo.md` | redirects to `/foo` | /// | `/img.png` | the file itself, by media type | - /// | `/mews-0.1.css` | the embedded stylesheet, when `mews_profile` is set | pub fn resolve(&self, url_path: &str) -> Result { let Some(clean) = clean_path(url_path) else { return Ok(Resolution::NotFound) }; - - // Checked by name only, so the link resolves the same at any depth: a - // page under `/foo/bar` carries the same relative `href` as one at the - // root, and both must land here rather than on a per-directory copy. - if self.mews_profile && clean.rsplit('/').next() == Some(MEWS_STYLESHEET_NAME) { - return Ok(Resolution::Found(Resource::Embedded { - bytes: MEWS_STYLESHEET, - media_type: mime::media_type(Path::new(MEWS_STYLESHEET_NAME)), - })); - } - let Some(source) = self.file_for(&clean) else { return self.part_for(&clean) }; // `/foo.md` always redirects to its extensionless form, so one @@ -262,10 +231,15 @@ impl Site { let settings = self.dir_config(dir)?.settings_for(name)?; let doc = parse::document(source, &self.root)?; let stem = source.file_stem().and_then(|s| s.to_str()).unwrap_or_default(); - let mews = self - .mews_profile - .then_some(Mews { hosts: self.hosts.as_slice(), feed: self.feed.as_deref() }); - self.registry.page(&self.formats, &doc, url, &settings, &title_from_stem(stem), mews) + let mews_hosts = self.mews_profile.then_some(self.hosts.as_slice()); + self.registry.page( + &self.formats, + &doc, + url, + &settings, + &title_from_stem(stem), + mews_hosts, + ) }) } @@ -301,7 +275,7 @@ mod tests { } fn render(&self, doc: &Doc, ctx: &RenderCtx<'_>) -> Result { - let mut body = format!("title={}\nmews={:?}\n", ctx.title, ctx.mews); + let mut body = format!("title={}\nmews_hosts={:?}\n", ctx.title, ctx.mews_hosts); for block in &doc.blocks { body.push_str(&format!("{block:?}\n")); } @@ -316,7 +290,7 @@ mod tests { } fn open(root: &Path) -> Site { - Site::new(root, registry(), vec!["stub".to_string()], false, Vec::new(), None).unwrap() + Site::new(root, registry(), vec!["stub".to_string()], false, Vec::new()).unwrap() } /// One of each kind of thing a request can land on, shared by the resolution @@ -499,29 +473,6 @@ mod tests { assert_not_found(&site, "/nope"); } - #[test] - fn the_mews_stylesheet_is_served_embedded_when_the_profile_is_on() { - let (dir, _site) = fixture(); - let mews_site = - Site::new(dir.path(), registry(), vec!["stub".to_string()], true, Vec::new(), None) - .unwrap(); - for path in ["/mews-0.1.css", "/dir/mews-0.1.css"] { - match mews_site.resolve(path).unwrap() { - Resolution::Found(Resource::Embedded { bytes, media_type }) => { - assert_eq!(media_type, "text/css; charset=utf-8"); - assert_eq!(bytes, MEWS_STYLESHEET, "{path}"); - } - other => panic!("expected the embedded stylesheet at {path}, got {other:?}"), - } - } - } - - #[test] - fn the_mews_stylesheet_name_is_an_ordinary_missing_file_when_the_profile_is_off() { - let (_dir, site) = fixture(); - assert_not_found(&site, "/mews-0.1.css"); - } - #[test] fn a_bare_unresolvable_segment_resolves_to_nothing() { // The obvious implementation splits on the last `/`, where a bare @@ -630,10 +581,10 @@ mod tests { let (dir, _site) = fixture(); let hosts = vec!["example.test".to_string()]; let mews_site = - Site::new(dir.path(), registry(), vec!["stub".to_string()], true, hosts, None).unwrap(); + Site::new(dir.path(), registry(), vec!["stub".to_string()], true, hosts).unwrap(); let (_, page) = document(&mews_site, "/about"); let body = String::from_utf8(page.body("stub").unwrap().to_vec()).unwrap(); - assert!(body.contains("hosts: [\"example.test\"]"), "{body}"); + assert!(body.contains("mews_hosts=Some([\"example.test\"])"), "{body}"); } #[test] @@ -641,7 +592,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let absent = dir.path().join("absent"); assert!(matches!( - Site::new(&absent, registry(), vec![], false, Vec::new(), None), + Site::new(&absent, registry(), vec![], false, Vec::new()), Err(Error::Io { .. }) )); } @@ -652,7 +603,7 @@ mod tests { let file = dir.path().join("not-a-dir"); fs::write(&file, "x").unwrap(); assert!(matches!( - Site::new(&file, registry(), vec![], false, Vec::new(), None), + Site::new(&file, registry(), vec![], false, Vec::new()), Err(Error::Config { .. }) )); } @@ -714,15 +665,9 @@ mod part_tests { let mut registry = Registry::new(); registry.insert(Arc::new(Paginating)).unwrap(); - let site = Site::new( - root, - Arc::new(registry), - vec!["paginating".to_string()], - false, - Vec::new(), - None, - ) - .unwrap(); + let site = + Site::new(root, Arc::new(registry), vec!["paginating".to_string()], false, Vec::new()) + .unwrap(); (dir, site) } diff --git a/core/src/siteset.rs b/core/src/siteset.rs index 387e501..986b799 100644 --- a/core/src/siteset.rs +++ b/core/src/siteset.rs @@ -39,14 +39,8 @@ impl SiteSet { for (name, spec) in &config.site { let hosts = spec.hosts.iter().filter_map(|host| normalize_host(host)).collect(); - let site = Site::new( - &spec.root, - registry.clone(), - formats.clone(), - spec.mews_profile, - hosts, - spec.feed.clone(), - )?; + let site = + Site::new(&spec.root, registry.clone(), formats.clone(), spec.mews_profile, hosts)?; // One `Site` per distinct root, so sites sharing a folder share its // caches rather than each building their own. let index = match set.sites.iter().position(|open| open.root() == site.root()) { diff --git a/gemtext/src/lib.rs b/gemtext/src/lib.rs index d7fbde9..7d1fa3c 100644 --- a/gemtext/src/lib.rs +++ b/gemtext/src/lib.rs @@ -113,7 +113,7 @@ impl Writer { // number in the text to keep the sequence readable. if *ordered { self.line(&format!("* {}. {text}", start + index as u64)); - } else if !is_only_links_item(item) { + } else { self.line(&format!("* {text}")); } for block in item { @@ -201,16 +201,6 @@ impl Writer { } } -/// Whether a list item holds links and nothing else worth printing, in which -/// case the `=>` lines are the whole item and a marker line above them would -/// list every entry twice -- the same reading [`is_only_links`] gives a -/// paragraph. Markup other than one paragraph keeps its marker, since the -/// shape is then doing something a link catalogue alone would not carry; so -/// does an ordered item, whose number would go with it. -fn is_only_links_item(item: &[Block]) -> bool { - matches!(item, [Block::Paragraph(inline)] if is_only_links(inline)) -} - /// Whether a paragraph holds links and nothing else worth printing. fn is_only_links(inline: &[Inline]) -> bool { let mut saw_link = false; @@ -305,7 +295,8 @@ mod tests_support { pub fn render(markdown: &str) -> String { let doc = parse::markdown(markdown).unwrap(); let settings = PageSettings::default(); - let ctx = RenderCtx { url: "/x", title: "T", settings: &settings, width: None, mews: None }; + let ctx = + RenderCtx { url: "/x", title: "T", settings: &settings, width: None, mews_hosts: None }; let out = Gemtext.render(&doc, &ctx).unwrap(); String::from_utf8(out.body).unwrap() } @@ -380,19 +371,6 @@ mod tests { assert_eq!(render("- see [x](/x)\n"), "* see x\n=> /x x\n"); } - #[test] - fn a_list_of_bare_links_is_a_run_of_link_lines() { - // The shape a generator wants for a dated index: a real list, so the - // markup formats can give it
  • , without gemtext printing both - // the marker line and the link line for every entry. - assert_eq!(render("- [a](/a)\n- [b](/b)\n"), "=> /a a\n=> /b b\n"); - } - - #[test] - fn an_ordered_list_of_bare_links_keeps_its_numbers() { - assert_eq!(render("1. [a](/a)\n"), "* 1. a\n=> /a a\n"); - } - #[test] fn code_blocks_become_fences_carrying_their_info_string() { assert_eq!(render("```rust\nlet x = 1;\n```\n"), "```rust\nlet x = 1;\n```\n"); @@ -421,7 +399,8 @@ mod tests { // Pagination is a WML concern; a Gemini client scrolls one document. let doc = parse::markdown("a\n\nb\n").unwrap(); let settings = PageSettings::default(); - let ctx = RenderCtx { url: "/x", title: "T", settings: &settings, width: None, mews: None }; + let ctx = + RenderCtx { url: "/x", title: "T", settings: &settings, width: None, mews_hosts: None }; let plain = String::from_utf8(Gemtext.render(&doc, &ctx).unwrap().body).unwrap(); assert_eq!(plain, "a\n\nb\n"); } diff --git a/text/src/lib.rs b/text/src/lib.rs index 8aabf6b..e6951af 100644 --- a/text/src/lib.rs +++ b/text/src/lib.rs @@ -58,7 +58,8 @@ mod tests { /// assertions read as the content itself. fn render_with(settings: &PageSettings, width: u16, markdown: &str) -> String { let doc = parse::markdown(markdown).unwrap(); - let ctx = RenderCtx { url: "/x", title: "T", settings, width: Some(width), mews: None }; + let ctx = + RenderCtx { url: "/x", title: "T", settings, width: Some(width), mews_hosts: None }; String::from_utf8(Text.render(&doc, &ctx).unwrap().body).unwrap() } @@ -213,7 +214,8 @@ mod tests { /// `parse::document`, which needs a file, so the unit tests build them. fn render_blocks(settings: &PageSettings, width: u16, blocks: Vec) -> String { let doc = Doc { blocks, first_h1: None }; - let ctx = RenderCtx { url: "/x", title: "T", settings, width: Some(width), mews: None }; + let ctx = + RenderCtx { url: "/x", title: "T", settings, width: Some(width), mews_hosts: None }; String::from_utf8(Text.render(&doc, &ctx).unwrap().body).unwrap() } @@ -267,8 +269,13 @@ mod separation_tests { fn render(markdown: &str) -> String { let doc = parse::markdown(markdown).unwrap(); let settings = PageSettings { margin_left: 0, margin_right: 0, ..Default::default() }; - let ctx = - RenderCtx { url: "/x", title: "T", settings: &settings, width: Some(40), mews: None }; + let ctx = RenderCtx { + url: "/x", + title: "T", + settings: &settings, + width: Some(40), + mews_hosts: None, + }; String::from_utf8(Text.render(&doc, &ctx).unwrap().body).unwrap() } @@ -300,7 +307,8 @@ mod optional_feature_tests { fn render_with(settings: &PageSettings, width: u16, markdown: &str) -> String { let doc = parse::markdown(markdown).unwrap(); - let ctx = RenderCtx { url: "/x", title: "T", settings, width: Some(width), mews: None }; + let ctx = + RenderCtx { url: "/x", title: "T", settings, width: Some(width), mews_hosts: None }; String::from_utf8(Text.render(&doc, &ctx).unwrap().body).unwrap() } diff --git a/wap/src/lib.rs b/wap/src/lib.rs index 162551f..78e53a6 100644 --- a/wap/src/lib.rs +++ b/wap/src/lib.rs @@ -1,9 +1,9 @@ //! The WAP family: XHTML Mobile Profile, and the `text/html` body derived from it. //! //! One crate rather than one per format, because the HTML form is the XHTML-MP -//! bytes, less the XML declaration on a page that is not a Mews page, and because -//! WML's deck configuration is shared with nothing outside this family. Splitting -//! them would duplicate the escaper and the markup builder. +//! bytes with the XML declaration removed, and because WML's deck configuration +//! is shared with nothing outside this family. Splitting them would duplicate the +//! escaper and the markup builder. #[cfg(feature = "wml")] mod deck; @@ -29,7 +29,7 @@ impl Renderer for XhtmlMp { } fn render(&self, doc: &Doc, ctx: &RenderCtx<'_>) -> Result { - Ok(Rendered::body(xhtmlmp::document(doc, ctx.title, true, ctx.mews).into_bytes())) + Ok(Rendered::body(xhtmlmp::document(doc, ctx.title, true, ctx.mews_hosts).into_bytes())) } } @@ -46,7 +46,7 @@ impl Renderer for Html { } fn render(&self, doc: &Doc, ctx: &RenderCtx<'_>) -> Result { - Ok(Rendered::body(xhtmlmp::document(doc, ctx.title, false, ctx.mews).into_bytes())) + Ok(Rendered::body(xhtmlmp::document(doc, ctx.title, false, ctx.mews_hosts).into_bytes())) } } @@ -87,7 +87,7 @@ mod tests { title: "The Title", settings: &settings, width: None, - mews: None, + mews_hosts: None, }; String::from_utf8(renderer.render(&doc, &ctx).unwrap().body).unwrap() } @@ -184,7 +184,8 @@ mod tests { first_h1: None, }; let settings = PageSettings::default(); - let ctx = RenderCtx { url: "/x", title: "T", settings: &settings, width: None, mews: None }; + let ctx = + RenderCtx { url: "/x", title: "T", settings: &settings, width: None, mews_hosts: None }; let out = String::from_utf8(Html.render(&doc, &ctx).unwrap().body).unwrap(); assert!(out.contains("
    /\\
    "), "{out}"); } @@ -201,7 +202,8 @@ mod tests { first_h1: None, }; let settings = PageSettings::default(); - let ctx = RenderCtx { url: "/x", title: "T", settings: &settings, width: None, mews: None }; + let ctx = + RenderCtx { url: "/x", title: "T", settings: &settings, width: None, mews_hosts: None }; let out = String::from_utf8(Html.render(&doc, &ctx).unwrap().body).unwrap(); assert!(out.contains("\n"), "{out}"); } @@ -224,7 +226,8 @@ mod deck_tests { // Card dividers are comment directives, so the IR is built by hand here // the way `parse::document` would produce it. let doc = with_card_breaks(markdown); - let ctx = RenderCtx { url: "/trail", title: "Trail", settings, width: None, mews: None }; + let ctx = + RenderCtx { url: "/trail", title: "Trail", settings, width: None, mews_hosts: None }; Wml.render(&doc, &ctx).unwrap() } @@ -485,7 +488,7 @@ mod oracle_dump { title: "Trail", settings: &settings, width: None, - mews: None, + mews_hosts: None, }; let out = Wml.render(&doc, &ctx).unwrap(); std::fs::write(format!("/tmp/mine-{name}.wml"), out.body).unwrap(); diff --git a/wap/src/xhtmlmp.rs b/wap/src/xhtmlmp.rs index 5b4d430..cdafcb0 100644 --- a/wap/src/xhtmlmp.rs +++ b/wap/src/xhtmlmp.rs @@ -3,18 +3,15 @@ //! One document serves both: a WAP 2.0 client needs well-formed XML with the //! prolog and the Mobile Profile doctype, while a browser parsing the same bytes //! as `text/html` tolerates the leading `` as a bogus comment but -//! logs a warning for it. So an ordinary page's HTML form is the same markup -//! with that one line removed. A Mews page keeps it in both forms: see -//! [`document`]. +//! logs a warning for it. So the HTML form is the same markup with that one line +//! removed. use itsybitsy_core::config::normalize_host; use itsybitsy_core::ir::{Block, Doc, Inline}; -use itsybitsy_core::render::Mews; use crate::escape; -/// The XML declaration, which every form of a Mews page carries and only the -/// XHTML-MP form of an ordinary one does. +/// The XML declaration, which only the XHTML-MP form carries. const PROLOG: &str = "\n"; /// The ordinary doctype, used whenever a site has not opted into Mews Profile @@ -35,55 +32,44 @@ const MEWS_HEAD_EXTRA: &str = "\n\ \n"; /// Build the whole document. `prolog` distinguishes the two media types. -/// `mews` is `Some` when the site has opted into Mews Profile compliance, and -/// `None` otherwise. -pub fn document(doc: &Doc, title: &str, prolog: bool, mews: Option>) -> String { +/// `mews_hosts` is `Some` with the site's own hostnames when it has opted into +/// Mews Profile compliance, and `None` otherwise. +pub fn document(doc: &Doc, title: &str, prolog: bool, mews_hosts: Option<&[String]>) -> String { let mut out = String::new(); - // A Mews page carries the declaration whatever its media type: 3.1 requires - // it, and a validator or directory checker judges the bytes it was handed, - // which for anything fetching the way a browser does is the `text/html` - // form. The cost is the console warning an HTML parser logs for a comment - // it did not expect; it reads the line as a comment before the doctype, so - // nothing about how the page renders changes. - if prolog || mews.is_some() { + if prolog { out.push_str(PROLOG); } - out.push_str(if mews.is_some() { DOCTYPE_1_2 } else { DOCTYPE_1_0 }); + out.push_str(if mews_hosts.is_some() { DOCTYPE_1_2 } else { DOCTYPE_1_0 }); out.push_str("\n"); - out.push_str(&format!("\n{}\n", escape::text(title))); - if mews.is_some() { - out.push_str(MEWS_HEAD_EXTRA); - } - // The feed is declared here rather than linked from a page body, which is - // the only place a client reading the head can find it (6.2). The label is - // the spec example's, since the attribute names the feed rather than - // whichever page happens to carry the declaration. - if let Some(feed) = mews.and_then(|mews| mews.feed) { + if mews_hosts.is_some() { out.push_str(&format!( - "\n", - escape::attr(feed) + "\n{}\n{MEWS_HEAD_EXTRA}\n", + escape::text(title) )); + } else { + out.push_str(&format!("{}\n", escape::text(title))); } - out.push_str("\n"); out.push_str("\n"); - blocks(&doc.blocks, mews, &mut out); + blocks(&doc.blocks, mews_hosts, &mut out); out.push_str("\n\n"); out } -fn blocks(blocks: &[Block], mews: Option>, out: &mut String) { +fn blocks(blocks: &[Block], mews_hosts: Option<&[String]>, out: &mut String) { for block in blocks { - self_block(block, mews, out); + self_block(block, mews_hosts, out); } } -fn self_block(block: &Block, mews: Option>, out: &mut String) { +fn self_block(block: &Block, mews_hosts: Option<&[String]>, out: &mut String) { match block { Block::Heading { level, inline } => { let level = (*level).clamp(1, 6); - out.push_str(&format!("{}\n", inlines(inline, mews))); + out.push_str(&format!("{}\n", inlines(inline, mews_hosts))); + } + Block::Paragraph(inline) => { + out.push_str(&format!("

    {}

    \n", inlines(inline, mews_hosts))) } - Block::Paragraph(inline) => out.push_str(&format!("

    {}

    \n", inlines(inline, mews))), Block::CodeBlock { lines, .. } => { out.push_str("
    ");
                 out.push_str(&escape::text(&lines.join("\n")));
    @@ -98,7 +84,7 @@ fn self_block(block: &Block, mews: Option>, out: &mut String) {
             }
             Block::BlockQuote(inner) => {
                 out.push_str("
    \n"); - blocks(inner, mews, out); + blocks(inner, mews_hosts, out); out.push_str("
    \n"); } Block::List { ordered, start, items } => { @@ -114,10 +100,10 @@ fn self_block(block: &Block, mews: Option>, out: &mut String) { out.push_str("
  • "); // A single paragraph needs no block wrapper inside the item. match item.as_slice() { - [Block::Paragraph(inline)] => out.push_str(&inlines(inline, mews)), + [Block::Paragraph(inline)] => out.push_str(&inlines(inline, mews_hosts)), blocks_in_item => { out.push('\n'); - blocks(blocks_in_item, mews, out); + blocks(blocks_in_item, mews_hosts, out); } } out.push_str("
  • \n"); @@ -129,14 +115,14 @@ fn self_block(block: &Block, mews: Option>, out: &mut String) { if !head.is_empty() { out.push_str(""); for cell in head { - out.push_str(&format!("{}", inlines(cell, mews))); + out.push_str(&format!("{}", inlines(cell, mews_hosts))); } out.push_str("\n"); } for row in rows { out.push_str(""); for cell in row { - out.push_str(&format!("{}", inlines(cell, mews))); + out.push_str(&format!("{}", inlines(cell, mews_hosts))); } out.push_str("\n"); } @@ -148,34 +134,36 @@ fn self_block(block: &Block, mews: Option>, out: &mut String) { // cannot make that guarantee — the markup might use an element or // attribute the profile excludes — so it is dropped instead. Block::Html(html) => { - if mews.is_none() { + if mews_hosts.is_none() { out.push_str(html.trim_end()); out.push('\n'); } } // Alignment reaches only the fixed-width text formats. Pagination is a // WML concern; a browser scrolls one document. - Block::Aligned { block, .. } => self_block(block, mews, out), + Block::Aligned { block, .. } => self_block(block, mews_hosts, out), // Gates are filtered out before rendering; keeping the content is the // harmless reading if one ever arrives here. - Block::Gated { block, .. } => self_block(block, mews, out), + Block::Gated { block, .. } => self_block(block, mews_hosts, out), Block::CardBreak { .. } => {} } } -fn inlines(inline: &[Inline], mews: Option>) -> String { +fn inlines(inline: &[Inline], mews_hosts: Option<&[String]>) -> String { let mut out = String::new(); for item in inline { match item { Inline::Text(text) => out.push_str(&escape::text(text)), Inline::Code(code) => out.push_str(&format!("{}", escape::text(code))), - Inline::Emph(inner) => out.push_str(&format!("{}", inlines(inner, mews))), + Inline::Emph(inner) => { + out.push_str(&format!("{}", inlines(inner, mews_hosts))) + } Inline::Strong(inner) => { - out.push_str(&format!("{}", inlines(inner, mews))) + out.push_str(&format!("{}", inlines(inner, mews_hosts))) } // XHTML-MP 1.0 has no , and is not in the profile, so // the text survives without its markup rather than being dropped. - Inline::Strike(inner) => out.push_str(&inlines(inner, mews)), + Inline::Strike(inner) => out.push_str(&inlines(inner, mews_hosts)), Inline::Link { href, title, label } => { let title = title .as_deref() @@ -184,14 +172,14 @@ fn inlines(inline: &[Inline], mews: Option>) -> String { out.push_str(&format!( "{}", escape::attr(href), - inlines(label, mews) + inlines(label, mews_hosts) )); } Inline::Image { src, title, alt } => { // A Mews page's image must point at the same site and never be // a `data:` URI (SPEC.md 4.2); one that does not is dropped to // its alt text rather than rendered non-conformant. - if mews.is_some_and(|mews| !same_site_image(src, mews.hosts)) { + if mews_hosts.is_some_and(|hosts| !same_site_image(src, hosts)) { out.push_str(&escape::text(&Doc::plain_text(alt))); continue; } @@ -209,7 +197,7 @@ fn inlines(inline: &[Inline], mews: Option>) -> String { Inline::HardBreak => out.push_str("
    \n"), // See the Block::Html arm above: unverifiable in a Mews page. Inline::Html(html) => { - if mews.is_none() { + if mews_hosts.is_none() { out.push_str(html); } } @@ -254,50 +242,13 @@ mod tests { Doc { blocks: Vec::new(), first_h1: None } } - /// A site that has opted into the profile and declares no feed. - fn mews(hosts: &[String]) -> Mews<'_> { - Mews { hosts, feed: None } - } - #[test] - fn an_ordinary_page_carries_the_prolog_only_when_asked_for() { + fn the_prolog_is_present_only_when_asked_for() { let doc = empty(); assert!(document(&doc, "T", true, None).starts_with(""), "{out}"); - } - } - - #[test] - fn the_feed_is_declared_in_the_head_when_the_site_names_one() { - let hosts = vec!["example.test".to_string()]; - let feed = Mews { hosts: &hosts, feed: Some("https://example.test/feed.xml") }; - let out = document(&empty(), "T", false, Some(feed)); - assert!( - out.contains( - "" - ), - "{out}" - ); - assert!( - out.split("").next().is_some_and(|head| head.contains("alternate")), - "{out}" - ); - - let none = document(&empty(), "T", false, Some(mews(&hosts))); - assert!(!none.contains("alternate"), "{none}"); - } - #[test] fn a_plain_page_keeps_the_1_0_doctype_and_no_mews_head() { let out = document(&empty(), "T", false, None); @@ -308,7 +259,7 @@ mod tests { #[test] fn a_mews_page_carries_the_1_2_doctype_and_the_conformance_marker() { let hosts = vec!["example.test".to_string()]; - let out = document(&empty(), "T", false, Some(mews(&hosts))); + let out = document(&empty(), "T", false, Some(&hosts)); assert!(out.contains("XHTML Mobile 1.2"), "{out}"); assert!(out.contains(""), "{out}"); assert!(out.contains(""), "{out}"); @@ -322,7 +273,7 @@ mod tests { fn a_mews_page_drops_raw_html_it_cannot_vouch_for() { let hosts = vec!["example.test".to_string()]; let doc = Doc { blocks: vec![Block::Html("
    x
    ".into())], first_h1: None }; - let out = document(&doc, "T", false, Some(mews(&hosts))); + let out = document(&doc, "T", false, Some(&hosts)); assert!(!out.contains("
    "), "{out}"); let plain = document(&doc, "T", false, None); @@ -344,7 +295,7 @@ mod tests { fn a_mews_page_keeps_a_relative_or_same_site_image() { let hosts = vec!["example.test".to_string()]; for src in ["/i.png", "i.png", "https://example.test/i.png", "//img.example.test/i.png"] { - let out = document(&image_doc(src), "T", false, Some(mews(&hosts))); + let out = document(&image_doc(src), "T", false, Some(&hosts)); assert!(out.contains(&format!("src=\"{src}\"")), "{src}: {out}"); } } @@ -353,7 +304,7 @@ mod tests { fn a_mews_page_drops_an_off_site_or_data_image_to_its_alt_text() { let hosts = vec!["example.test".to_string()]; for src in ["https://elsewhere.test/i.png", "data:image/png;base64,AAAA"] { - let out = document(&image_doc(src), "T", false, Some(mews(&hosts))); + let out = document(&image_doc(src), "T", false, Some(&hosts)); assert!(!out.contains("