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.

272 lines
9.3KB

  1. #[macro_use]
  2. extern crate serde_derive;
  3. extern crate tera;
  4. extern crate errors;
  5. extern crate config;
  6. extern crate content;
  7. extern crate utils;
  8. #[cfg(test)]
  9. extern crate front_matter;
  10. use std::collections::HashMap;
  11. use tera::{Tera, Context, to_value, Value};
  12. use errors::{Result, ResultExt};
  13. use config::Config;
  14. use content::{Page, Section};
  15. use utils::templates::render_template;
  16. /// A list of all the pages in the paginator with their index and links
  17. #[derive(Clone, Debug, PartialEq, Serialize)]
  18. pub struct Pager<'a> {
  19. /// The page number in the paginator (1-indexed)
  20. index: usize,
  21. /// Permalink to that page
  22. permalink: String,
  23. /// Path to that page
  24. path: String,
  25. /// All pages for the pager
  26. pages: Vec<&'a Page>
  27. }
  28. impl<'a> Pager<'a> {
  29. fn new(index: usize, pages: Vec<&'a Page>, permalink: String, path: String) -> Pager<'a> {
  30. Pager {
  31. index,
  32. permalink,
  33. path,
  34. pages,
  35. }
  36. }
  37. /// Returns a manually cloned Pager with the pages removed
  38. /// for use as template context
  39. fn clone_without_pages(&self) -> Pager<'a> {
  40. Pager {
  41. index: self.index,
  42. permalink: self.permalink.clone(),
  43. path: self.path.clone(),
  44. pages: vec![],
  45. }
  46. }
  47. }
  48. #[derive(Clone, Debug, PartialEq)]
  49. pub struct Paginator<'a> {
  50. /// All pages in the section
  51. all_pages: &'a [Page],
  52. /// Pages split in chunks of `paginate_by`
  53. pub pagers: Vec<Pager<'a>>,
  54. /// How many content pages on a paginated page at max
  55. paginate_by: usize,
  56. /// The section struct we're building the paginator for
  57. section: &'a Section,
  58. }
  59. impl<'a> Paginator<'a> {
  60. /// Create a new paginator
  61. /// It will always at least create one pager (the first) even if there are no pages to paginate
  62. pub fn new(all_pages: &'a [Page], section: &'a Section) -> Paginator<'a> {
  63. let paginate_by = section.meta.paginate_by.unwrap();
  64. let mut pages = vec![];
  65. let mut current_page = vec![];
  66. for page in all_pages {
  67. current_page.push(page);
  68. if current_page.len() == paginate_by {
  69. pages.push(current_page);
  70. current_page = vec![];
  71. }
  72. }
  73. if !current_page.is_empty() {
  74. pages.push(current_page);
  75. }
  76. let mut pagers = vec![];
  77. for (index, page) in pages.iter().enumerate() {
  78. // First page has no pagination path
  79. if index == 0 {
  80. pagers.push(Pager::new(1, page.clone(), section.permalink.clone(), section.path.clone()));
  81. continue;
  82. }
  83. let page_path = format!("{}/{}/", section.meta.paginate_path, index + 1);
  84. let permalink = format!("{}{}", section.permalink, page_path);
  85. let pager_path = if section.is_index() {
  86. page_path
  87. } else {
  88. format!("{}{}", section.path, page_path)
  89. };
  90. pagers.push(Pager::new(
  91. index + 1,
  92. page.clone(),
  93. permalink,
  94. pager_path,
  95. ));
  96. }
  97. // We always have the index one at least
  98. if pagers.is_empty() {
  99. pagers.push(Pager::new(1, vec![], section.permalink.clone(), section.path.clone()));
  100. }
  101. Paginator {
  102. all_pages,
  103. pagers,
  104. paginate_by,
  105. section,
  106. }
  107. }
  108. pub fn build_paginator_context(&self, current_pager: &Pager) -> HashMap<&str, Value> {
  109. let mut paginator = HashMap::new();
  110. // the pager index is 1-indexed so we want a 0-indexed one for indexing there
  111. let pager_index = current_pager.index - 1;
  112. // Global variables
  113. paginator.insert("paginate_by", to_value(self.paginate_by).unwrap());
  114. paginator.insert("first", to_value(&self.section.permalink).unwrap());
  115. let last_pager = &self.pagers[self.pagers.len() - 1];
  116. paginator.insert("last", to_value(&last_pager.permalink).unwrap());
  117. paginator.insert(
  118. "pagers",
  119. to_value(
  120. &self.pagers.iter().map(|p| p.clone_without_pages()).collect::<Vec<_>>()
  121. ).unwrap()
  122. );
  123. // Variables for this specific page
  124. if pager_index > 0 {
  125. let prev_pager = &self.pagers[pager_index - 1];
  126. paginator.insert("previous", to_value(&prev_pager.permalink).unwrap());
  127. } else {
  128. paginator.insert("previous", to_value::<Option<()>>(None).unwrap());
  129. }
  130. if pager_index < self.pagers.len() - 1 {
  131. let next_pager = &self.pagers[pager_index + 1];
  132. paginator.insert("next", to_value(&next_pager.permalink).unwrap());
  133. } else {
  134. paginator.insert("next", to_value::<Option<()>>(None).unwrap());
  135. }
  136. paginator.insert("pages", to_value(&current_pager.pages).unwrap());
  137. paginator.insert("current_index", to_value(current_pager.index).unwrap());
  138. paginator
  139. }
  140. pub fn render_pager(&self, pager: &Pager, config: &Config, tera: &Tera) -> Result<String> {
  141. let mut context = Context::new();
  142. context.add("config", &config);
  143. context.add("section", self.section);
  144. context.add("current_url", &pager.permalink);
  145. context.add("current_path", &pager.path);
  146. context.add("paginator", &self.build_paginator_context(pager));
  147. render_template(&self.section.get_template_name(), tera, &context, config.theme.clone())
  148. .chain_err(|| format!("Failed to render pager {} of section '{}'", pager.index, self.section.file.path.display()))
  149. }
  150. }
  151. #[cfg(test)]
  152. mod tests {
  153. use tera::to_value;
  154. use front_matter::SectionFrontMatter;
  155. use content::{Page, Section};
  156. use super::Paginator;
  157. fn create_section(is_index: bool) -> Section {
  158. let mut f = SectionFrontMatter::default();
  159. f.paginate_by = Some(2);
  160. f.paginate_path = "page".to_string();
  161. let mut s = Section::new("content/_index.md", f);
  162. if !is_index {
  163. s.path = "posts/".to_string();
  164. s.permalink = "https://vincent.is/posts/".to_string();
  165. s.file.components = vec!["posts".to_string()];
  166. } else {
  167. s.permalink = "https://vincent.is/".to_string();
  168. }
  169. s
  170. }
  171. #[test]
  172. fn test_can_create_paginator() {
  173. let pages = vec![
  174. Page::default(),
  175. Page::default(),
  176. Page::default(),
  177. ];
  178. let section = create_section(false);
  179. let paginator = Paginator::new(pages.as_slice(), &section);
  180. assert_eq!(paginator.pagers.len(), 2);
  181. assert_eq!(paginator.pagers[0].index, 1);
  182. assert_eq!(paginator.pagers[0].pages.len(), 2);
  183. assert_eq!(paginator.pagers[0].permalink, "https://vincent.is/posts/");
  184. assert_eq!(paginator.pagers[0].path, "posts/");
  185. assert_eq!(paginator.pagers[1].index, 2);
  186. assert_eq!(paginator.pagers[1].pages.len(), 1);
  187. assert_eq!(paginator.pagers[1].permalink, "https://vincent.is/posts/page/2/");
  188. assert_eq!(paginator.pagers[1].path, "posts/page/2/");
  189. }
  190. #[test]
  191. fn test_can_create_paginator_for_index() {
  192. let pages = vec![
  193. Page::default(),
  194. Page::default(),
  195. Page::default(),
  196. ];
  197. let section = create_section(true);
  198. let paginator = Paginator::new(pages.as_slice(), &section);
  199. assert_eq!(paginator.pagers.len(), 2);
  200. assert_eq!(paginator.pagers[0].index, 1);
  201. assert_eq!(paginator.pagers[0].pages.len(), 2);
  202. assert_eq!(paginator.pagers[0].permalink, "https://vincent.is/");
  203. assert_eq!(paginator.pagers[0].path, "");
  204. assert_eq!(paginator.pagers[1].index, 2);
  205. assert_eq!(paginator.pagers[1].pages.len(), 1);
  206. assert_eq!(paginator.pagers[1].permalink, "https://vincent.is/page/2/");
  207. assert_eq!(paginator.pagers[1].path, "page/2/");
  208. }
  209. #[test]
  210. fn test_can_build_paginator_context() {
  211. let pages = vec![
  212. Page::default(),
  213. Page::default(),
  214. Page::default(),
  215. ];
  216. let section = create_section(false);
  217. let paginator = Paginator::new(pages.as_slice(), &section);
  218. assert_eq!(paginator.pagers.len(), 2);
  219. let context = paginator.build_paginator_context(&paginator.pagers[0]);
  220. assert_eq!(context["paginate_by"], to_value(2).unwrap());
  221. assert_eq!(context["first"], to_value("https://vincent.is/posts/").unwrap());
  222. assert_eq!(context["last"], to_value("https://vincent.is/posts/page/2/").unwrap());
  223. assert_eq!(context["previous"], to_value::<Option<()>>(None).unwrap());
  224. assert_eq!(context["next"], to_value("https://vincent.is/posts/page/2/").unwrap());
  225. assert_eq!(context["current_index"], to_value(1).unwrap());
  226. let context = paginator.build_paginator_context(&paginator.pagers[1]);
  227. assert_eq!(context["paginate_by"], to_value(2).unwrap());
  228. assert_eq!(context["first"], to_value("https://vincent.is/posts/").unwrap());
  229. assert_eq!(context["last"], to_value("https://vincent.is/posts/page/2/").unwrap());
  230. assert_eq!(context["next"], to_value::<Option<()>>(None).unwrap());
  231. assert_eq!(context["previous"], to_value("https://vincent.is/posts/").unwrap());
  232. assert_eq!(context["current_index"], to_value(2).unwrap());
  233. }
  234. }