gpui_router/
state.rs

1use gpui::{App, Global, SharedString};
2use hashbrown::HashMap;
3use matchit::Params;
4
5#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Debug)]
6pub struct Location {
7  /// A URL pathname, beginning with a `/`.
8  pub pathname: SharedString,
9  /// A value of arbitrary data associated with this location.
10  pub state: Params<'static, 'static>,
11}
12
13impl Default for Location {
14  fn default() -> Self {
15    Self {
16      pathname: "/".into(),
17      state: Params::default(),
18    }
19  }
20}
21
22// A PathMatch contains info about how a PathPattern matched on a URL-like pathname.
23#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Debug)]
24pub struct PathMatch {
25  /// The portion of the URL-like pathname that was matched.
26  pub pathname: SharedString,
27  /// The portion of the URL-like pathname that was matched before child routes.
28  pub pathname_base: SharedString,
29  /// The route pattern that was matched.
30  pub pattern: SharedString,
31  /// The names and values of dynamic parameters in the URL-like.
32  /// For example, if the route pattern is `/users/{id}`, and the URL pathname is `/users/123`,
33  /// then the `params` would be `{"id": "123"}`.
34  pub params: Params<'static, 'static>,
35}
36
37#[derive(PartialEq, Clone)]
38pub struct RouterState {
39  pub location: Location,
40  pub path_match: Option<PathMatch>,
41  pub params: HashMap<SharedString, SharedString>,
42}
43
44impl Global for RouterState {}
45
46impl RouterState {
47  pub fn init(cx: &mut App) {
48    let state = Self {
49      location: Location::default(),
50      path_match: None,
51      params: HashMap::new(),
52    };
53    cx.set_global::<RouterState>(state);
54  }
55
56  pub fn with_path(&mut self, pathname: SharedString) -> &mut Self {
57    self.location.pathname = pathname;
58    self
59  }
60
61  pub fn global(cx: &App) -> &Self {
62    cx.global::<Self>()
63  }
64
65  pub fn global_mut(cx: &mut App) -> &mut Self {
66    cx.global_mut::<Self>()
67  }
68}