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.

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