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.

190 lines
6.6KB

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