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.

section.rs 6.5KB

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