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.

178 lines
6.1KB

  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::{Context, Header, markdown_to_html};
  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 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(
  83. tera,
  84. config.highlight_code.unwrap(),
  85. config.highlight_theme.clone().unwrap(),
  86. &self.permalink,
  87. permalinks,
  88. self.meta.insert_anchor_links.unwrap()
  89. );
  90. let res = markdown_to_html(&self.raw_content, &context)?;
  91. self.content = res.0;
  92. self.toc = res.1;
  93. Ok(())
  94. }
  95. /// Renders the page using the default layout, unless specified in front-matter
  96. pub fn render_html(&self, tera: &Tera, config: &Config) -> Result<String> {
  97. let tpl_name = self.get_template_name();
  98. let mut context = TeraContext::new();
  99. context.add("config", config);
  100. context.add("section", self);
  101. context.add("current_url", &self.permalink);
  102. context.add("current_path", &self.path);
  103. render_template(&tpl_name, tera, &context, config.theme.clone())
  104. .chain_err(|| format!("Failed to render section '{}'", self.file.path.display()))
  105. }
  106. /// Is this the index section?
  107. pub fn is_index(&self) -> bool {
  108. self.file.components.is_empty()
  109. }
  110. /// Returns all the paths of the pages belonging to that section
  111. pub fn all_pages_path(&self) -> Vec<PathBuf> {
  112. let mut paths = vec![];
  113. paths.extend(self.pages.iter().map(|p| p.file.path.clone()));
  114. paths.extend(self.ignored_pages.iter().map(|p| p.file.path.clone()));
  115. paths
  116. }
  117. /// Whether the page given belongs to that section
  118. pub fn is_child_page(&self, path: &PathBuf) -> bool {
  119. self.all_pages_path().contains(path)
  120. }
  121. }
  122. impl ser::Serialize for Section {
  123. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  124. let mut state = serializer.serialize_struct("section", 12)?;
  125. state.serialize_field("content", &self.content)?;
  126. state.serialize_field("permalink", &self.permalink)?;
  127. state.serialize_field("title", &self.meta.title)?;
  128. state.serialize_field("description", &self.meta.description)?;
  129. state.serialize_field("extra", &self.meta.extra)?;
  130. state.serialize_field("path", &self.path)?;
  131. state.serialize_field("permalink", &self.permalink)?;
  132. state.serialize_field("pages", &self.pages)?;
  133. state.serialize_field("subsections", &self.subsections)?;
  134. let (word_count, reading_time) = get_reading_analytics(&self.raw_content);
  135. state.serialize_field("word_count", &word_count)?;
  136. state.serialize_field("reading_time", &reading_time)?;
  137. state.serialize_field("toc", &self.toc)?;
  138. state.end()
  139. }
  140. }
  141. /// Used to create a default index section if there is no _index.md in the root content directory
  142. impl Default for Section {
  143. fn default() -> Section {
  144. Section {
  145. file: FileInfo::default(),
  146. meta: SectionFrontMatter::default(),
  147. path: "".to_string(),
  148. permalink: "".to_string(),
  149. raw_content: "".to_string(),
  150. content: "".to_string(),
  151. pages: vec![],
  152. ignored_pages: vec![],
  153. subsections: vec![],
  154. toc: vec![],
  155. }
  156. }
  157. }