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.

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