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.

270 lines
9.3KB

  1. use std::collections::{HashMap, HashSet};
  2. use std::path::{Path, PathBuf};
  3. use slotmap::{DenseSlotMap, Key};
  4. use front_matter::SortBy;
  5. use sorting::{find_siblings, sort_pages_by_weight, sort_pages_by_date};
  6. use content::{Page, Section};
  7. /// Houses everything about pages and sections
  8. /// Think of it as a database where each page and section has an id (Key here)
  9. /// that can be used to find the actual value
  10. /// Sections and pages can then refer to other elements by those keys, which are very cheap to
  11. /// copy.
  12. /// We can assume the keys are always existing as removing a page/section deletes all references
  13. /// to that key.
  14. #[derive(Debug)]
  15. pub struct Library {
  16. /// All the pages of the site
  17. pages: DenseSlotMap<Page>,
  18. /// All the sections of the site
  19. sections: DenseSlotMap<Section>,
  20. /// A mapping path -> key for pages so we can easily get their key
  21. paths_to_pages: HashMap<PathBuf, Key>,
  22. /// A mapping path -> key for sections so we can easily get their key
  23. paths_to_sections: HashMap<PathBuf, Key>,
  24. }
  25. impl Library {
  26. pub fn new(cap_pages: usize, cap_sections: usize) -> Self {
  27. Library {
  28. pages: DenseSlotMap::with_capacity(cap_pages),
  29. sections: DenseSlotMap::with_capacity(cap_sections),
  30. paths_to_pages: HashMap::with_capacity(cap_pages),
  31. paths_to_sections: HashMap::with_capacity(cap_sections),
  32. }
  33. }
  34. /// Add a section and return its Key
  35. pub fn insert_section(&mut self, section: Section) -> Key {
  36. let path = section.file.path.clone();
  37. let key = self.sections.insert(section);
  38. self.paths_to_sections.insert(path, key);
  39. key
  40. }
  41. /// Add a page and return its Key
  42. pub fn insert_page(&mut self, page: Page) -> Key {
  43. let path = page.file.path.clone();
  44. let key = self.pages.insert(page);
  45. self.paths_to_pages.insert(path, key);
  46. key
  47. }
  48. pub fn pages(&self) -> &DenseSlotMap<Page> {
  49. &self.pages
  50. }
  51. pub fn pages_mut(&mut self) -> &mut DenseSlotMap<Page> {
  52. &mut self.pages
  53. }
  54. pub fn pages_values(&self) -> Vec<&Page> {
  55. self.pages.values().collect::<Vec<_>>()
  56. }
  57. pub fn sections(&self) -> &DenseSlotMap<Section> {
  58. &self.sections
  59. }
  60. pub fn sections_mut(&mut self) -> &mut DenseSlotMap<Section> {
  61. &mut self.sections
  62. }
  63. pub fn sections_values(&self) -> Vec<&Section> {
  64. self.sections.values().collect::<Vec<_>>()
  65. }
  66. /// Find out the direct subsections of each subsection if there are some
  67. /// as well as the pages for each section
  68. pub fn populate_sections(&mut self) {
  69. let mut grandparent_paths: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
  70. for section in self.sections.values_mut() {
  71. if let Some(ref grand_parent) = section.file.grand_parent {
  72. grandparent_paths
  73. .entry(grand_parent.to_path_buf())
  74. .or_insert_with(|| vec![])
  75. .push(section.file.path.clone());
  76. }
  77. // Make sure the pages of a section are empty since we can call that many times on `serve`
  78. section.pages = vec![];
  79. section.ignored_pages = vec![];
  80. }
  81. for (key, page) in &mut self.pages {
  82. let parent_section_path = page.file.parent.join("_index.md");
  83. if let Some(section_key) = self.paths_to_sections.get(&parent_section_path) {
  84. self.sections.get_mut(*section_key).unwrap().pages.push(key);
  85. }
  86. }
  87. self.sort_sections_pages();
  88. let sections = self.paths_to_sections.clone();
  89. let mut sections_weight = HashMap::new();
  90. for (key, section) in &self.sections {
  91. sections_weight.insert(key, section.meta.weight);
  92. }
  93. for section in self.sections.values_mut() {
  94. if let Some(paths) = grandparent_paths.get(&section.file.parent) {
  95. section.subsections = paths
  96. .iter()
  97. .map(|p| sections[p])
  98. .collect::<Vec<_>>();
  99. section.subsections
  100. .sort_by(|a, b| sections_weight[a].cmp(&sections_weight[b]));
  101. }
  102. }
  103. }
  104. /// Sort all sections pages
  105. pub fn sort_sections_pages(&mut self) {
  106. let mut updates = HashMap::new();
  107. for (key, section) in &self.sections {
  108. let (sorted_pages, cannot_be_sorted_pages) = match section.meta.sort_by {
  109. SortBy::None => continue,
  110. SortBy::Date => {
  111. let data = section.pages
  112. .iter()
  113. .map(|k| {
  114. if let Some(page) = self.pages.get(*k) {
  115. (k, page.meta.datetime, page.permalink.as_ref())
  116. } else {
  117. unreachable!("Sorting got an unknown page")
  118. }
  119. })
  120. .collect();
  121. sort_pages_by_date(data)
  122. },
  123. SortBy::Weight => {
  124. let data = section.pages
  125. .iter()
  126. .map(|k| {
  127. if let Some(page) = self.pages.get(*k) {
  128. (k, page.meta.weight, page.permalink.as_ref())
  129. } else {
  130. unreachable!("Sorting got an unknown page")
  131. }
  132. })
  133. .collect();
  134. sort_pages_by_weight(data)
  135. }
  136. };
  137. updates.insert(key, (sorted_pages, cannot_be_sorted_pages, section.meta.sort_by));
  138. }
  139. for (key, (sorted, cannot_be_sorted, sort_by)) in updates {
  140. // Find sibling between sorted pages first
  141. let with_siblings = find_siblings(sorted.iter().map(|k| {
  142. if let Some(page) = self.pages.get(*k) {
  143. (k, page.is_draft())
  144. } else {
  145. unreachable!("Sorting got an unknown page")
  146. }
  147. }).collect());
  148. for (k2, val1, val2) in with_siblings {
  149. if let Some(page) = self.pages.get_mut(k2) {
  150. match sort_by {
  151. SortBy::Date => {
  152. page.earlier = val2;
  153. page.later = val1;
  154. },
  155. SortBy::Weight => {
  156. page.lighter = val1;
  157. page.heavier = val2;
  158. },
  159. SortBy::None => unreachable!("Impossible to find siblings in SortBy::None")
  160. }
  161. } else {
  162. unreachable!("Sorting got an unknown page")
  163. }
  164. }
  165. if let Some(s) = self.sections.get_mut(key) {
  166. s.pages = sorted;
  167. s.ignored_pages = cannot_be_sorted;
  168. }
  169. }
  170. }
  171. /// Find all the orphan pages: pages that are in a folder without an `_index.md`
  172. pub fn get_all_orphan_pages(&self) -> Vec<&Page> {
  173. let pages_in_sections = self.sections
  174. .values()
  175. .flat_map(|s| &s.pages)
  176. .collect::<HashSet<_>>();
  177. self.pages
  178. .iter()
  179. .filter(|(key, _)| !pages_in_sections.contains(&key))
  180. .map(|(_, page)| page)
  181. .collect()
  182. }
  183. pub fn find_parent_section(&self, path: &Path) -> Option<&Section> {
  184. let page_key = self.paths_to_pages[path];
  185. for s in self.sections.values() {
  186. if s.pages.contains(&page_key) {
  187. return Some(s)
  188. }
  189. }
  190. None
  191. }
  192. pub fn get_section(&self, path: &PathBuf) -> Option<&Section> {
  193. self.sections.get(self.paths_to_sections.get(path).cloned().unwrap_or_default())
  194. }
  195. pub fn get_section_mut(&mut self, path: &PathBuf) -> Option<&mut Section> {
  196. self.sections.get_mut(self.paths_to_sections.get(path).cloned().unwrap_or_default())
  197. }
  198. pub fn get_section_by_key(&self, key: Key) -> &Section {
  199. self.sections.get(key).unwrap()
  200. }
  201. pub fn get_page(&self, path: &PathBuf) -> Option<&Page> {
  202. self.pages.get(self.paths_to_pages.get(path).cloned().unwrap_or_default())
  203. }
  204. pub fn get_page_by_key(&self, key: Key) -> &Page {
  205. self.pages.get(key).unwrap()
  206. }
  207. pub fn remove_section(&mut self, path: &PathBuf) -> Option<Section> {
  208. if let Some(k) = self.paths_to_sections.remove(path) {
  209. // TODO: delete section from parent subsection if there is one
  210. self.sections.remove(k)
  211. } else {
  212. None
  213. }
  214. }
  215. pub fn remove_page(&mut self, path: &PathBuf) -> Option<Page> {
  216. if let Some(k) = self.paths_to_pages.remove(path) {
  217. // TODO: delete page from all parent sections
  218. self.pages.remove(k)
  219. } else {
  220. None
  221. }
  222. }
  223. /// Used in rebuild, to check if we know it already
  224. pub fn contains_section(&self, path: &PathBuf) -> bool {
  225. self.paths_to_sections.contains_key(path)
  226. }
  227. /// Used in rebuild, to check if we know it already
  228. pub fn contains_page(&self, path: &PathBuf) -> bool {
  229. self.paths_to_pages.contains_key(path)
  230. }
  231. }