You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

170 lines
5.9KB

  1. use std::collections::HashMap;
  2. use std::path::{Path, PathBuf};
  3. use std::result::Result as StdResult;
  4. use tera::{Tera, Context as TeraContext};
  5. use serde::ser::{SerializeStruct, self};
  6. use config::Config;
  7. use front_matter::{SectionFrontMatter, split_section_content};
  8. use errors::{Result, ResultExt};
  9. use fs::{read_file};
  10. use rendering::markdown::markdown_to_html;
  11. use rendering::context::Context;
  12. use content::Page;
  13. use content::file_info::FileInfo;
  14. use content::Header;
  15. #[derive(Clone, Debug, PartialEq)]
  16. pub struct Section {
  17. /// All info about the actual file
  18. pub file: FileInfo,
  19. /// The front matter meta-data
  20. pub meta: SectionFrontMatter,
  21. /// The URL path of the page
  22. pub path: String,
  23. /// The full URL for that page
  24. pub permalink: String,
  25. /// The actual content of the page, in markdown
  26. pub raw_content: String,
  27. /// The HTML rendered of the page
  28. pub content: String,
  29. /// All direct pages of that section
  30. pub pages: Vec<Page>,
  31. /// All pages that cannot be sorted in this section
  32. pub ignored_pages: Vec<Page>,
  33. /// All direct subsections
  34. pub subsections: Vec<Section>,
  35. /// Toc made from the headers of the markdown file
  36. pub toc: Vec<Header>,
  37. }
  38. impl Section {
  39. pub fn new<P: AsRef<Path>>(file_path: P, meta: SectionFrontMatter) -> Section {
  40. let file_path = file_path.as_ref();
  41. Section {
  42. file: FileInfo::new_section(file_path),
  43. meta: meta,
  44. path: "".to_string(),
  45. permalink: "".to_string(),
  46. raw_content: "".to_string(),
  47. content: "".to_string(),
  48. pages: vec![],
  49. ignored_pages: vec![],
  50. subsections: vec![],
  51. toc: vec![],
  52. }
  53. }
  54. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Section> {
  55. let (meta, content) = split_section_content(file_path, content)?;
  56. let mut section = Section::new(file_path, meta);
  57. section.raw_content = content.clone();
  58. section.path = format!("{}/", section.file.components.join("/"));
  59. section.permalink = config.make_permalink(&section.path);
  60. Ok(section)
  61. }
  62. /// Read and parse a .md file into a Page struct
  63. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Section> {
  64. let path = path.as_ref();
  65. let content = read_file(path)?;
  66. Section::parse(path, &content, config)
  67. }
  68. pub fn get_template_name(&self) -> String {
  69. match self.meta.template {
  70. Some(ref l) => l.to_string(),
  71. None => {
  72. if self.is_index() {
  73. return "index.html".to_string();
  74. }
  75. "section.html".to_string()
  76. },
  77. }
  78. }
  79. /// We need access to all pages url to render links relative to content
  80. /// so that can't happen at the same time as parsing
  81. pub fn render_markdown(&mut self, permalinks: &HashMap<String, String>, tera: &Tera, config: &Config) -> Result<()> {
  82. let context = Context::new(tera, config, &self.permalink, permalinks, self.meta.insert_anchor.unwrap());
  83. let res = markdown_to_html(&self.raw_content, &context)?;
  84. self.content = res.0;
  85. self.toc = res.1;
  86. Ok(())
  87. }
  88. /// Renders the page using the default layout, unless specified in front-matter
  89. pub fn render_html(&self, sections: HashMap<String, Section>, tera: &Tera, config: &Config) -> Result<String> {
  90. let tpl_name = self.get_template_name();
  91. let mut context = TeraContext::new();
  92. context.add("config", config);
  93. context.add("section", self);
  94. context.add("current_url", &self.permalink);
  95. context.add("current_path", &self.path);
  96. if self.is_index() {
  97. context.add("sections", &sections);
  98. }
  99. tera.render(&tpl_name, &context)
  100. .chain_err(|| format!("Failed to render section '{}'", self.file.path.display()))
  101. }
  102. /// Is this the index section?
  103. pub fn is_index(&self) -> bool {
  104. self.file.components.is_empty()
  105. }
  106. /// Returns all the paths of the pages belonging to that section
  107. pub fn all_pages_path(&self) -> Vec<PathBuf> {
  108. let mut paths = vec![];
  109. paths.extend(self.pages.iter().map(|p| p.file.path.clone()));
  110. paths.extend(self.ignored_pages.iter().map(|p| p.file.path.clone()));
  111. paths
  112. }
  113. /// Whether the page given belongs to that section
  114. pub fn is_child_page(&self, path: &PathBuf) -> bool {
  115. self.all_pages_path().contains(path)
  116. }
  117. }
  118. impl ser::Serialize for Section {
  119. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  120. let mut state = serializer.serialize_struct("section", 10)?;
  121. state.serialize_field("content", &self.content)?;
  122. state.serialize_field("permalink", &self.permalink)?;
  123. state.serialize_field("title", &self.meta.title)?;
  124. state.serialize_field("description", &self.meta.description)?;
  125. state.serialize_field("extra", &self.meta.extra)?;
  126. state.serialize_field("path", &format!("/{}", self.path))?;
  127. state.serialize_field("permalink", &self.permalink)?;
  128. state.serialize_field("pages", &self.pages)?;
  129. state.serialize_field("subsections", &self.subsections)?;
  130. state.serialize_field("toc", &self.toc)?;
  131. state.end()
  132. }
  133. }
  134. /// Used to create a default index section if there is no _index.md in the root content directory
  135. impl Default for Section {
  136. fn default() -> Section {
  137. Section {
  138. file: FileInfo::default(),
  139. meta: SectionFrontMatter::default(),
  140. path: "".to_string(),
  141. permalink: "".to_string(),
  142. raw_content: "".to_string(),
  143. content: "".to_string(),
  144. pages: vec![],
  145. ignored_pages: vec![],
  146. subsections: vec![],
  147. toc: vec![],
  148. }
  149. }
  150. }