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.

158 lines
4.7KB

  1. #[macro_use]
  2. extern crate serde_derive;
  3. extern crate tera;
  4. extern crate slug;
  5. extern crate errors;
  6. extern crate config;
  7. extern crate content;
  8. extern crate front_matter;
  9. use std::collections::HashMap;
  10. use slug::slugify;
  11. use tera::{Context, Tera};
  12. use config::Config;
  13. use errors::{Result, ResultExt};
  14. use content::{Page, sort_pages};
  15. use front_matter::SortBy;
  16. #[derive(Debug, Copy, Clone, PartialEq)]
  17. pub enum TaxonomyKind {
  18. Tags,
  19. Categories,
  20. }
  21. /// A tag or category
  22. #[derive(Debug, Clone, Serialize, PartialEq)]
  23. pub struct TaxonomyItem {
  24. pub name: String,
  25. pub slug: String,
  26. pub pages: Vec<Page>,
  27. }
  28. impl TaxonomyItem {
  29. pub fn new(name: &str, pages: Vec<Page>) -> TaxonomyItem {
  30. // We shouldn't have any pages without dates there
  31. let (sorted_pages, _) = sort_pages(pages, SortBy::Date);
  32. TaxonomyItem {
  33. name: name.to_string(),
  34. slug: slugify(name),
  35. pages: sorted_pages,
  36. }
  37. }
  38. }
  39. /// All the tags or categories
  40. #[derive(Debug, Clone, PartialEq)]
  41. pub struct Taxonomy {
  42. pub kind: TaxonomyKind,
  43. // this vec is sorted by the count of item
  44. pub items: Vec<TaxonomyItem>,
  45. }
  46. impl Taxonomy {
  47. // TODO: take a Vec<&'a Page> if it makes a difference in terms of perf for actual sites
  48. pub fn find_tags_and_categories(all_pages: &[Page]) -> (Taxonomy, Taxonomy) {
  49. let mut tags = HashMap::new();
  50. let mut categories = HashMap::new();
  51. // Find all the tags/categories first
  52. for page in all_pages {
  53. // Don't consider pages without pages for tags/categories as that's the only thing
  54. // we can sort pages with across sections
  55. // If anyone sees that comment and wonder wtf, please open an issue as I can't think of
  56. // usecases other than blog posts for built-in taxonomies
  57. if page.meta.date.is_none() {
  58. continue;
  59. }
  60. if let Some(ref category) = page.meta.category {
  61. categories
  62. .entry(category.to_string())
  63. .or_insert_with(|| vec![])
  64. .push(page.clone());
  65. }
  66. if let Some(ref t) = page.meta.tags {
  67. for tag in t {
  68. tags
  69. .entry(tag.to_string())
  70. .or_insert_with(|| vec![])
  71. .push(page.clone());
  72. }
  73. }
  74. }
  75. // Then make TaxonomyItem out of them, after sorting it
  76. let tags_taxonomy = Taxonomy::new(TaxonomyKind::Tags, tags);
  77. let categories_taxonomy = Taxonomy::new(TaxonomyKind::Categories, categories);
  78. (tags_taxonomy, categories_taxonomy)
  79. }
  80. fn new(kind: TaxonomyKind, items: HashMap<String, Vec<Page>>) -> Taxonomy {
  81. let mut sorted_items = vec![];
  82. for (name, pages) in &items {
  83. sorted_items.push(
  84. TaxonomyItem::new(name, pages.clone())
  85. );
  86. }
  87. sorted_items.sort_by(|a, b| b.pages.len().cmp(&a.pages.len()));
  88. Taxonomy {
  89. kind,
  90. items: sorted_items,
  91. }
  92. }
  93. pub fn len(&self) -> usize {
  94. self.items.len()
  95. }
  96. pub fn is_empty(&self) -> bool {
  97. self.len() == 0
  98. }
  99. pub fn get_single_item_name(&self) -> String {
  100. match self.kind {
  101. TaxonomyKind::Tags => "tag".to_string(),
  102. TaxonomyKind::Categories => "category".to_string(),
  103. }
  104. }
  105. pub fn get_list_name(&self) -> String {
  106. match self.kind {
  107. TaxonomyKind::Tags => "tags".to_string(),
  108. TaxonomyKind::Categories => "categories".to_string(),
  109. }
  110. }
  111. pub fn render_single_item(&self, item: &TaxonomyItem, tera: &Tera, config: &Config) -> Result<String> {
  112. let name = self.get_single_item_name();
  113. let mut context = Context::new();
  114. context.add("config", config);
  115. context.add(&name, item);
  116. context.add("current_url", &config.make_permalink(&format!("{}/{}", name, item.slug)));
  117. context.add("current_path", &format!("/{}/{}", name, item.slug));
  118. tera.render(&format!("{}.html", name), &context)
  119. .chain_err(|| format!("Failed to render {} page.", name))
  120. }
  121. pub fn render_list(&self, tera: &Tera, config: &Config) -> Result<String> {
  122. let name = self.get_list_name();
  123. let mut context = Context::new();
  124. context.add("config", config);
  125. context.add(&name, &self.items);
  126. context.add("current_url", &config.make_permalink(&name));
  127. context.add("current_path", &name);
  128. tera.render(&format!("{}.html", name), &context)
  129. .chain_err(|| format!("Failed to render {} page.", name))
  130. }
  131. }