memory.rs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. use std::str::FromStr;
  2. use crate::routable::Routable;
  3. use super::HistoryProvider;
  4. /// A [`HistoryProvider`] that stores all navigation information in memory.
  5. pub struct MemoryHistory<R: Routable> {
  6. current: R,
  7. history: Vec<R>,
  8. future: Vec<R>,
  9. }
  10. impl<R: Routable> MemoryHistory<R>
  11. where
  12. <R as FromStr>::Err: std::fmt::Display,
  13. {
  14. /// Create a [`MemoryHistory`] starting at `path`.
  15. ///
  16. /// ```rust
  17. /// # use dioxus_router::prelude::*;
  18. /// # use dioxus::prelude::*;
  19. /// # #[inline_props]
  20. /// # fn Index(cx: Scope) -> Element { todo!() }
  21. /// # #[inline_props]
  22. /// # fn OtherPage(cx: Scope) -> Element { todo!() }
  23. /// #[derive(Clone, Routable, Debug, PartialEq)]
  24. /// enum Route {
  25. /// #[route("/")]
  26. /// Index {},
  27. /// #[route("/some-other-page")]
  28. /// OtherPage {},
  29. /// }
  30. ///
  31. /// let mut history = MemoryHistory::<Route>::with_initial_path(Route::Index {});
  32. /// assert_eq!(history.current_route(), Route::Index {});
  33. /// assert_eq!(history.can_go_back(), false);
  34. /// ```
  35. pub fn with_initial_path(path: R) -> Self {
  36. Self {
  37. current: path,
  38. history: Vec::new(),
  39. future: Vec::new(),
  40. }
  41. }
  42. }
  43. impl<R: Routable> Default for MemoryHistory<R>
  44. where
  45. <R as FromStr>::Err: std::fmt::Display,
  46. {
  47. fn default() -> Self {
  48. Self {
  49. current: "/".parse().unwrap_or_else(|err| {
  50. panic!("index route does not exist:\n{}\n use MemoryHistory::with_initial_path to set a custom path", err)
  51. }),
  52. history: Vec::new(),
  53. future: Vec::new(),
  54. }
  55. }
  56. }
  57. impl<R: Routable> HistoryProvider<R> for MemoryHistory<R> {
  58. fn current_route(&self) -> R {
  59. self.current.clone()
  60. }
  61. fn can_go_back(&self) -> bool {
  62. !self.history.is_empty()
  63. }
  64. fn go_back(&mut self) {
  65. if let Some(last) = self.history.pop() {
  66. let old = std::mem::replace(&mut self.current, last);
  67. self.future.push(old);
  68. }
  69. }
  70. fn can_go_forward(&self) -> bool {
  71. !self.future.is_empty()
  72. }
  73. fn go_forward(&mut self) {
  74. if let Some(next) = self.future.pop() {
  75. let old = std::mem::replace(&mut self.current, next);
  76. self.history.push(old);
  77. }
  78. }
  79. fn push(&mut self, new: R) {
  80. // don't push the same route twice
  81. if self.current.to_string() == new.to_string() {
  82. return;
  83. }
  84. let old = std::mem::replace(&mut self.current, new);
  85. self.history.push(old);
  86. self.future.clear();
  87. }
  88. fn replace(&mut self, path: R) {
  89. self.current = path;
  90. }
  91. }