use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use crate::document::{Document, Kind};
use crate::folder::Folder;
use crate::html;
use crate::widgets::{Modules, Widgets};
use super::frame::chapter_names;
use super::markdown::markdown;
pub struct Rendered {
file: PathBuf,
source: String,
expanded: String,
html: String,
links: Vec<Link>,
embeds: Vec<String>,
tags: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Link {
pub file: PathBuf,
pub line: Option<usize>,
pub target: String,
}
impl Rendered {
pub fn file(&self) -> &Path {
&self.file
}
pub fn source(&self) -> &str {
&self.source
}
pub fn expanded(&self) -> &str {
&self.expanded
}
pub fn html(&self) -> &str {
&self.html
}
pub fn ids(&self) -> BTreeSet<String> {
html::values(&self.html, "id").into_iter().collect()
}
pub fn heading_ids(&self) -> Vec<String> {
super::markdown::heading_ids(&self.html)
}
pub fn links(&self) -> &[Link] {
&self.links
}
pub fn embeds(&self) -> &[String] {
&self.embeds
}
pub(crate) fn tag_problems(&self) -> &[String] {
&self.tags
}
}
pub fn content(widgets: &Widgets, file: &Path, source: String) -> Rendered {
let _render = tracing::info_span!("render").entered();
let mut tags = Vec::new();
let extensions: Vec<_> = widgets.extensions.iter().map(|b| b.snapshot()).collect();
let mut augmented = source.clone();
for binding in &extensions {
match binding.transform(file, &augmented) {
Ok(text) => augmented = text,
Err(error) => tags.push(format!("Extension: {error:#}")),
}
}
let expanded = crate::widgets::expand_with(&augmented, widgets.names(), &mut tags, &|name| {
widgets.written(file, name)
});
let grammars: Vec<_> = extensions.iter().filter_map(|b| b.grammar()).collect();
let mut extension_embeds = Vec::new();
let mut html = crate::highlight::with_grammars(&grammars, || markdown(&expanded));
for (identity, target) in crate::html::values(&html, "src").into_iter().enumerate() {
let path = target.split('#').next().unwrap_or(&target);
if let Some(binding) = extensions.iter().find(|b| b.owns(Path::new(path))) {
extension_embeds.push(target.clone());
match binding.embed(file, &target, "", identity) {
Ok(embed) => {
let needle = format!("src=\"{}\"", crate::html::escape(&target));
while let Some(at) = html.find(&needle) {
let Some(start) = html[..at].rfind("<img ") else {
break;
};
let Some(end) = html[at..].find('>') else {
break;
};
html.replace_range(start..at + end + 1, &embed);
}
}
Err(error) => tags.push(format!("Extension embed: {error:#}")),
}
}
}
let mut targets = html::values(&html, "href");
let mut embeds = html::values(&html, "src");
embeds.extend(extension_embeds);
targets.extend(embeds.iter().cloned());
for design in embedded_designs(&source) {
if !embeds.contains(&design) {
embeds.push(design.clone());
}
if !targets.contains(&design) {
targets.push(design);
}
}
let links = targets
.into_iter()
.map(|target| Link {
file: file.to_path_buf(),
line: source
.find(&target)
.map(|at| source[..at].lines().count().max(1)),
target,
})
.collect();
Rendered {
file: file.to_path_buf(),
source,
expanded,
html,
links,
embeds,
tags,
}
}
pub fn read(widgets: &Widgets, file: &Path) -> Rendered {
content(
widgets,
file,
std::fs::read_to_string(file).unwrap_or_default(),
)
}
pub fn shown_in(file: &Path, folder: &Folder) -> Option<Document> {
Document::load(&shown_by(file, folder), folder.served()).ok()
}
pub fn shown_by(file: &Path, folder: &Folder) -> PathBuf {
folder.site(file).unwrap_or_else(|| file.to_path_buf())
}
pub fn ids(file: &Path, folder: &Folder, modules: &Modules) -> BTreeSet<String> {
if file.extension().is_some_and(|ext| ext == "md") {
return shown_in(file, folder)
.map(|document| read(&Widgets::of(&document, modules), file).ids())
.unwrap_or_default();
}
let served = folder.served();
let Ok(document) = Document::load(file, served) else {
return BTreeSet::new();
};
let Kind::Doc { chapters, .. } = &document.kind else {
return BTreeSet::new();
};
let widgets = Widgets::of(&document, modules);
let own_ids = |chapter: &Path| read(&widgets, chapter).ids();
if chapters.len() == 1 {
return own_ids(&chapters[0]);
}
let names = chapter_names(chapters, served);
let mut ids = BTreeSet::new();
for (chapter, (_, name)) in chapters.iter().zip(&names) {
ids.extend(
own_ids(chapter)
.into_iter()
.map(|id| format!("{name}--{id}")),
);
ids.insert(name.clone());
}
ids
}
fn embedded_designs(source: &str) -> Vec<String> {
use comrak::nodes::NodeValue;
let arena = comrak::Arena::new();
let root = comrak::parse_document(&arena, source, &comrak::Options::default());
root.descendants()
.filter_map(|node| match &node.data.borrow().value {
NodeValue::Image(link) | NodeValue::Link(link) => Some(link.url.clone()),
_ => None,
})
.filter(|url| {
url.split('#')
.next()
.is_some_and(|path| path.ends_with(".design"))
})
.collect()
}