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.

351 lines
12KB

  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. extern crate taxonomies;
  9. #[cfg(test)]
  10. extern crate front_matter;
  11. use std::collections::HashMap;
  12. use tera::{Tera, Context, to_value, Value};
  13. use errors::{Result, ResultExt};
  14. use config::Config;
  15. use content::{Page, Section};
  16. use utils::templates::render_template;
  17. use taxonomies::{Taxonomy, TaxonomyItem};
  18. #[derive(Clone, Debug, PartialEq)]
  19. enum PaginationRoot<'a> {
  20. Section(&'a Section),
  21. Taxonomy(&'a Taxonomy),
  22. }
  23. /// A list of all the pages in the paginator with their index and links
  24. #[derive(Clone, Debug, PartialEq, Serialize)]
  25. pub struct Pager<'a> {
  26. /// The page number in the paginator (1-indexed)
  27. pub index: usize,
  28. /// Permalink to that page
  29. permalink: String,
  30. /// Path to that page
  31. path: String,
  32. /// All pages for the pager
  33. pages: Vec<&'a Page>,
  34. }
  35. impl<'a> Pager<'a> {
  36. fn new(index: usize, pages: Vec<&'a Page>, permalink: String, path: String) -> Pager<'a> {
  37. Pager {
  38. index,
  39. permalink,
  40. path,
  41. pages,
  42. }
  43. }
  44. }
  45. #[derive(Clone, Debug, PartialEq)]
  46. pub struct Paginator<'a> {
  47. /// All pages in the section
  48. all_pages: &'a [Page],
  49. /// Pages split in chunks of `paginate_by`
  50. pub pagers: Vec<Pager<'a>>,
  51. /// How many content pages on a paginated page at max
  52. paginate_by: usize,
  53. /// The thing we are creating the paginator for: section or taxonomy
  54. root: PaginationRoot<'a>,
  55. // Those below can be obtained from the root but it would make the code more complex than needed
  56. pub permalink: String,
  57. path: String,
  58. pub paginate_path: String,
  59. is_index: bool,
  60. }
  61. impl<'a> Paginator<'a> {
  62. /// Create a new paginator from a section
  63. /// It will always at least create one pager (the first) even if there are no pages to paginate
  64. pub fn from_section(all_pages: &'a [Page], section: &'a Section) -> Paginator<'a> {
  65. let paginate_by = section.meta.paginate_by.unwrap();
  66. let mut paginator = Paginator {
  67. all_pages,
  68. pagers: vec![],
  69. paginate_by,
  70. root: PaginationRoot::Section(section),
  71. permalink: section.permalink.clone(),
  72. path: section.path.clone(),
  73. paginate_path: section.meta.paginate_path.clone(),
  74. is_index: section.is_index(),
  75. };
  76. paginator.fill_pagers();
  77. paginator
  78. }
  79. /// Create a new paginator from a taxonomy
  80. /// It will always at least create one pager (the first) even if there are no pages to paginate
  81. pub fn from_taxonomy(taxonomy: &'a Taxonomy, item: &'a TaxonomyItem) -> Paginator<'a> {
  82. let paginate_by = taxonomy.kind.paginate_by.unwrap();
  83. let mut paginator = Paginator {
  84. all_pages: &item.pages,
  85. pagers: vec![],
  86. paginate_by,
  87. root: PaginationRoot::Taxonomy(taxonomy),
  88. permalink: item.permalink.clone(),
  89. path: format!("{}/{}", taxonomy.kind.name, item.slug),
  90. paginate_path: taxonomy.kind.paginate_path.clone().unwrap_or_else(|| "pages".to_string()),
  91. is_index: false,
  92. };
  93. paginator.fill_pagers();
  94. paginator
  95. }
  96. fn fill_pagers(&mut self) {
  97. let mut pages = vec![];
  98. let mut current_page = vec![];
  99. for page in self.all_pages {
  100. current_page.push(page);
  101. if current_page.len() == self.paginate_by {
  102. pages.push(current_page);
  103. current_page = vec![];
  104. }
  105. }
  106. if !current_page.is_empty() {
  107. pages.push(current_page);
  108. }
  109. let mut pagers = vec![];
  110. for (index, page) in pages.iter().enumerate() {
  111. // First page has no pagination path
  112. if index == 0 {
  113. pagers.push(Pager::new(1, page.clone(), self.permalink.clone(), self.path.clone()));
  114. continue;
  115. }
  116. let page_path = format!("{}/{}/", self.paginate_path, index + 1);
  117. let permalink = format!("{}{}", self.permalink, page_path);
  118. let pager_path = if self.is_index {
  119. page_path
  120. } else {
  121. if self.path.ends_with("/") {
  122. format!("{}{}", self.path, page_path)
  123. } else {
  124. format!("{}/{}", self.path, page_path)
  125. }
  126. };
  127. pagers.push(Pager::new(
  128. index + 1,
  129. page.clone(),
  130. permalink,
  131. pager_path,
  132. ));
  133. }
  134. // We always have the index one at least
  135. if pagers.is_empty() {
  136. pagers.push(Pager::new(1, vec![], self.permalink.clone(), self.path.clone()));
  137. }
  138. self.pagers = pagers;
  139. }
  140. pub fn build_paginator_context(&self, current_pager: &Pager) -> HashMap<&str, Value> {
  141. let mut paginator = HashMap::new();
  142. // the pager index is 1-indexed so we want a 0-indexed one for indexing there
  143. let pager_index = current_pager.index - 1;
  144. // Global variables
  145. paginator.insert("paginate_by", to_value(self.paginate_by).unwrap());
  146. paginator.insert("first", to_value(&self.permalink).unwrap());
  147. let last_pager = &self.pagers[self.pagers.len() - 1];
  148. paginator.insert("last", to_value(&last_pager.permalink).unwrap());
  149. // Variables for this specific page
  150. if pager_index > 0 {
  151. let prev_pager = &self.pagers[pager_index - 1];
  152. paginator.insert("previous", to_value(&prev_pager.permalink).unwrap());
  153. } else {
  154. paginator.insert("previous", Value::Null);
  155. }
  156. if pager_index < self.pagers.len() - 1 {
  157. let next_pager = &self.pagers[pager_index + 1];
  158. paginator.insert("next", to_value(&next_pager.permalink).unwrap());
  159. } else {
  160. paginator.insert("next", Value::Null);
  161. }
  162. paginator.insert("number_pagers", to_value(&self.pagers.len()).unwrap());
  163. paginator.insert("base_url", to_value(&format!("{}{}/", self.permalink, self.paginate_path)).unwrap());
  164. paginator.insert("pages", to_value(&current_pager.pages).unwrap());
  165. paginator.insert("current_index", to_value(current_pager.index).unwrap());
  166. paginator
  167. }
  168. pub fn render_pager(&self, pager: &Pager, config: &Config, tera: &Tera) -> Result<String> {
  169. let mut context = Context::new();
  170. context.insert("config", &config);
  171. let template_name = match self.root {
  172. PaginationRoot::Section(s) => {
  173. context.insert("section", &s.clone_without_pages());
  174. s.get_template_name()
  175. }
  176. PaginationRoot::Taxonomy(t) => {
  177. context.insert("taxonomy", &t.kind);
  178. format!("{}/single.html", t.kind.name)
  179. }
  180. };
  181. context.insert("current_url", &pager.permalink);
  182. context.insert("current_path", &pager.path);
  183. context.insert("paginator", &self.build_paginator_context(pager));
  184. render_template(&template_name, tera, &context, &config.theme)
  185. .chain_err(|| format!("Failed to render pager {}", pager.index))
  186. }
  187. }
  188. #[cfg(test)]
  189. mod tests {
  190. use tera::to_value;
  191. use front_matter::SectionFrontMatter;
  192. use content::{Page, Section};
  193. use config::Taxonomy as TaxonomyConfig;
  194. use taxonomies::{Taxonomy, TaxonomyItem};
  195. use super::Paginator;
  196. fn create_section(is_index: bool) -> Section {
  197. let mut f = SectionFrontMatter::default();
  198. f.paginate_by = Some(2);
  199. f.paginate_path = "page".to_string();
  200. let mut s = Section::new("content/_index.md", f);
  201. if !is_index {
  202. s.path = "posts/".to_string();
  203. s.permalink = "https://vincent.is/posts/".to_string();
  204. s.file.components = vec!["posts".to_string()];
  205. } else {
  206. s.permalink = "https://vincent.is/".to_string();
  207. }
  208. s
  209. }
  210. #[test]
  211. fn test_can_create_paginator() {
  212. let pages = vec![
  213. Page::default(),
  214. Page::default(),
  215. Page::default(),
  216. ];
  217. let section = create_section(false);
  218. let paginator = Paginator::from_section(pages.as_slice(), &section);
  219. assert_eq!(paginator.pagers.len(), 2);
  220. assert_eq!(paginator.pagers[0].index, 1);
  221. assert_eq!(paginator.pagers[0].pages.len(), 2);
  222. assert_eq!(paginator.pagers[0].permalink, "https://vincent.is/posts/");
  223. assert_eq!(paginator.pagers[0].path, "posts/");
  224. assert_eq!(paginator.pagers[1].index, 2);
  225. assert_eq!(paginator.pagers[1].pages.len(), 1);
  226. assert_eq!(paginator.pagers[1].permalink, "https://vincent.is/posts/page/2/");
  227. assert_eq!(paginator.pagers[1].path, "posts/page/2/");
  228. }
  229. #[test]
  230. fn test_can_create_paginator_for_index() {
  231. let pages = vec![
  232. Page::default(),
  233. Page::default(),
  234. Page::default(),
  235. ];
  236. let section = create_section(true);
  237. let paginator = Paginator::from_section(pages.as_slice(), &section);
  238. assert_eq!(paginator.pagers.len(), 2);
  239. assert_eq!(paginator.pagers[0].index, 1);
  240. assert_eq!(paginator.pagers[0].pages.len(), 2);
  241. assert_eq!(paginator.pagers[0].permalink, "https://vincent.is/");
  242. assert_eq!(paginator.pagers[0].path, "");
  243. assert_eq!(paginator.pagers[1].index, 2);
  244. assert_eq!(paginator.pagers[1].pages.len(), 1);
  245. assert_eq!(paginator.pagers[1].permalink, "https://vincent.is/page/2/");
  246. assert_eq!(paginator.pagers[1].path, "page/2/");
  247. }
  248. #[test]
  249. fn test_can_build_paginator_context() {
  250. let pages = vec![
  251. Page::default(),
  252. Page::default(),
  253. Page::default(),
  254. ];
  255. let section = create_section(false);
  256. let paginator = Paginator::from_section(pages.as_slice(), &section);
  257. assert_eq!(paginator.pagers.len(), 2);
  258. let context = paginator.build_paginator_context(&paginator.pagers[0]);
  259. assert_eq!(context["paginate_by"], to_value(2).unwrap());
  260. assert_eq!(context["first"], to_value("https://vincent.is/posts/").unwrap());
  261. assert_eq!(context["last"], to_value("https://vincent.is/posts/page/2/").unwrap());
  262. assert_eq!(context["previous"], to_value::<Option<()>>(None).unwrap());
  263. assert_eq!(context["next"], to_value("https://vincent.is/posts/page/2/").unwrap());
  264. assert_eq!(context["current_index"], to_value(1).unwrap());
  265. let context = paginator.build_paginator_context(&paginator.pagers[1]);
  266. assert_eq!(context["paginate_by"], to_value(2).unwrap());
  267. assert_eq!(context["first"], to_value("https://vincent.is/posts/").unwrap());
  268. assert_eq!(context["last"], to_value("https://vincent.is/posts/page/2/").unwrap());
  269. assert_eq!(context["next"], to_value::<Option<()>>(None).unwrap());
  270. assert_eq!(context["previous"], to_value("https://vincent.is/posts/").unwrap());
  271. assert_eq!(context["current_index"], to_value(2).unwrap());
  272. }
  273. #[test]
  274. fn test_can_create_paginator_for_taxonomy() {
  275. let pages = vec![
  276. Page::default(),
  277. Page::default(),
  278. Page::default(),
  279. ];
  280. let taxonomy_def = TaxonomyConfig {
  281. name: "tags".to_string(),
  282. paginate_by: Some(2),
  283. ..TaxonomyConfig::default()
  284. };
  285. let taxonomy_item = TaxonomyItem {
  286. name: "Something".to_string(),
  287. slug: "something".to_string(),
  288. permalink: "https://vincent.is/tags/something/".to_string(),
  289. pages,
  290. };
  291. let taxonomy = Taxonomy { kind: taxonomy_def, items: vec![taxonomy_item.clone()] };
  292. let paginator = Paginator::from_taxonomy(&taxonomy, &taxonomy_item);
  293. assert_eq!(paginator.pagers.len(), 2);
  294. assert_eq!(paginator.pagers[0].index, 1);
  295. assert_eq!(paginator.pagers[0].pages.len(), 2);
  296. assert_eq!(paginator.pagers[0].permalink, "https://vincent.is/tags/something/");
  297. assert_eq!(paginator.pagers[0].path, "tags/something");
  298. assert_eq!(paginator.pagers[1].index, 2);
  299. assert_eq!(paginator.pagers[1].pages.len(), 1);
  300. assert_eq!(paginator.pagers[1].permalink, "https://vincent.is/tags/something/pages/2/");
  301. assert_eq!(paginator.pagers[1].path, "tags/something/pages/2/");
  302. }
  303. }