Skip to main content

Route

Struct Route 

Source
pub struct Route {
    pub config: RouteConfig,
    pub builder: Option<RouteBuilder>,
    pub children: Vec<RouteRef>,
    pub named_children: HashMap<String, Vec<RouteRef>>,
    pub guards: Vec<BoxedGuard>,
    pub middleware: Vec<BoxedMiddleware>,
    pub lifecycle: Option<BoxedLifecycle>,
    pub transition: TransitionConfig,
}
Expand description

Route definition with render function

Fields§

§config: RouteConfig

Route configuration

§builder: Option<RouteBuilder>

Builder function to create the view for this route

§children: Vec<RouteRef>

Child routes with their own builders This is the preferred way to define nested routes (instead of RouteConfig.children)

§named_children: HashMap<String, Vec<RouteRef>>

Named outlets - map of outlet name to child routes Allows multiple outlet areas in a single parent route

§guards: Vec<BoxedGuard>
Available on crate feature guard only.

Guards that control access to this route

§middleware: Vec<BoxedMiddleware>
Available on crate feature middleware only.

Middleware that runs before and after navigation to this route

§lifecycle: Option<BoxedLifecycle>

Lifecycle hooks for this route

§transition: TransitionConfig
Available on crate feature transition only.

Transition animation for this route

Implementations§

Source§

impl Route

Source

pub fn new<F, E>(path: impl Into<String>, builder: F) -> Self
where E: IntoElement, F: Fn(&mut Window, &mut App, &RouteParams) -> E + Send + Sync + 'static,

Create a route with a builder function

Routes are registered with a path pattern and a builder function that creates the view. The builder receives the window, app context and extracted route parameters.

§Example
use gpui_navigator::Route;
use gpui::*;

// Simple static route
Route::new("/home", |window, cx, params| {
    div().child("Home Page")
});

// Route with dynamic parameter
Route::new("/users/:id", |window, cx, params| {
    let id = params.get("id").unwrap();
    div().child(format!("User: {}", id))
});
Source

pub fn view<F>(path: impl Into<String>, view: F) -> Self
where F: Fn() -> AnyElement + Send + Sync + 'static,

Create a stateless route from a simple view function

Use this for simple, stateless pages that don’t need access to route params, window, or context. The view function is called on every render.

§Example
use gpui_navigator::Route;
use gpui::*;

Route::view("/about", || {
    div().child("About Page").into_any_element()
});
Source

pub fn component<T, F>(path: impl Into<String>, create: F) -> Self
where T: Render + 'static, F: Fn() -> T + Send + Sync + 'static + Clone,

Create a stateful route with an Entity-based component

Use this for pages that maintain internal state across navigation. The component is cached using window.use_keyed_state(), so navigating back to the route will preserve the component’s state.

§Example
use gpui_navigator::Route;
use gpui::*;

struct CounterPage {
    count: i32,
}

impl CounterPage {
    fn new() -> Self {
        Self { count: 0 }
    }
}

impl Render for CounterPage {
    fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
        div().child(format!("Count: {}", self.count))
    }
}

Route::component("/counter", CounterPage::new);
Source

pub fn component_with_params<T, F>(path: impl Into<String>, create: F) -> Self
where T: Render + 'static, F: Fn(&RouteParams) -> T + Send + Sync + 'static + Clone,

Create a stateful route with parameters

Like component(), but the create function receives route parameters. The component is cached per unique set of parameter values, so navigating to /user/1 and /user/2 will create two separate component instances.

§Example
use gpui_navigator::{Route, RouteParams};
use gpui::*;

struct UserPage {
    user_id: String,
}

impl UserPage {
    fn new(user_id: String) -> Self {
        Self { user_id }
    }
}

impl Render for UserPage {
    fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
        div().child(format!("User: {}", self.user_id))
    }
}

Route::component_with_params("/user/:id", |params| {
    let id = params.get("id").unwrap().to_string();
    UserPage::new(id)
});
Source

pub fn children(self, children: Vec<RouteRef>) -> Self

Add child routes to this route

Child routes will be rendered in a RouterOutlet within the parent’s layout.

§Example
use gpui_navigator::{Route, render_router_outlet};
use gpui::*;

Route::new("/dashboard", |window, cx, params| {
    div()
        .child("Dashboard Header")
        .child(render_router_outlet(window, cx, None)) // Children render here
})
.children(vec![
    Route::new("overview", |_, _cx, _params| {
        div().child("Overview")
    })
    .into(),
    Route::new("settings", |_, _cx, _params| {
        div().child("Settings")
    })
    .into(),
]);
Source

pub fn child(self, child: RouteRef) -> Self

Add a single child route

§Example
use gpui_navigator::Route;
use gpui::*;

Route::new("/dashboard", |_, _cx, _params| div())
    .child(Route::new("overview", |_, _cx, _params| div()).into())
    .child(Route::new("settings", |_, _cx, _params| div()).into());
Source

pub fn name(self, name: impl Into<String>) -> Self

Set route name

Named routes can be referenced by name instead of path.

Source

pub fn meta(self, key: impl Into<String>, value: impl Into<String>) -> Self

Add metadata to the route

Metadata can be used for guards, analytics, titles, etc.

§Example
use gpui_navigator::Route;
use gpui::*;

Route::new("/admin", |_, _cx, _params| div())
    .meta("requiresAuth", "true")
    .meta("requiredRole", "admin")
    .meta("title", "Admin Panel");
Source

pub fn named_outlet( self, name: impl Into<String>, children: Vec<RouteRef>, ) -> Self

Add routes for a named outlet

Named outlets allow you to have multiple content areas in a single parent route. For example, a main content area and a sidebar.

§Example
use gpui_navigator::{Route, render_router_outlet};
use gpui::*;

Route::new("/dashboard", |window, cx, _params| {
    div()
        .child(render_router_outlet(window, cx, None))             // Main content
        .child(render_router_outlet(window, cx, Some("sidebar")))  // Sidebar
})
.children(vec![
    Route::new("analytics", |_, _cx, _params| div()).into(),
])
.named_outlet("sidebar", vec![
    Route::new("stats", |_, _cx, _params| div()).into(),
]);
Source

pub fn guard<G>(self, guard: G) -> Self
where G: RouteGuard<Future = Pin<Box<dyn Future<Output = GuardResult> + Send>>>,

Available on crate feature guard only.

Add a guard to this route

Guards control access to routes. If any guard denies access, navigation is blocked.

§Example
use gpui_navigator::{Route, AuthGuard, RoleGuard};
use gpui::*;

fn is_authenticated(_cx: &App) -> bool { true }
fn get_role(_cx: &App) -> Option<String> { Some("user".into()) }

Route::new("/dashboard", |_, _cx, _params| div())
    .guard(AuthGuard::new(is_authenticated, "/login"))
    .guard(RoleGuard::new(get_role, "user", Some("/forbidden")));
Source

pub fn guards(self, guards: Vec<BoxedGuard>) -> Self

Available on crate feature guard only.

Add multiple guards at once

§Example
use gpui_navigator::{Route, BoxedGuard};
use gpui::*;

Route::new("/admin", |_, _cx, _params| div())
    .guards(vec![
        // Add boxed guards here
    ]);
Source

pub fn middleware<M>(self, middleware: M) -> Self
where M: RouteMiddleware<Future = Pin<Box<dyn Future<Output = ()> + Send>>>,

Available on crate feature middleware only.

Add middleware to this route

Middleware runs before and after navigation.

§Example
use gpui_navigator::Route;
use gpui::*;

// Route::new("/dashboard", |_, _cx, _params| div().into_any_element())
//     .middleware(LoggingMiddleware::new());
Source

pub fn middlewares(self, middleware: Vec<BoxedMiddleware>) -> Self

Available on crate feature middleware only.

Add multiple middleware at once

§Example
use gpui_navigator::{Route, BoxedMiddleware};
use gpui::*;

Route::new("/dashboard", |_, _cx, _params| div().into_any_element())
    .middlewares(vec![
        // Add boxed middleware here
    ]);
Source

pub fn lifecycle<L>(self, lifecycle: L) -> Self
where L: RouteLifecycle<Future = Pin<Box<dyn Future<Output = LifecycleResult> + Send>>>,

Add lifecycle hooks to this route

Lifecycle hooks allow you to run code when entering/exiting routes.

§Example
use gpui_navigator::{Route, RouteLifecycle, LifecycleResult, NavigationRequest};
use gpui::*;
use std::pin::Pin;
use std::future::Future;

// Lifecycle hooks allow running code when entering/exiting routes
// Implement RouteLifecycle trait for custom behavior
Source

pub fn transition(self, transition: Transition) -> Self

Available on crate feature transition only.

Set the transition animation for this route

§Example
use gpui_navigator::{Route, Transition};
use gpui::*;

Route::new("/page", |_, _cx, _params| div().into_any_element())
    .transition(Transition::fade(200));
Source

pub fn get_named_children(&self, name: &str) -> Option<&[RouteRef]>

Get child routes for a named outlet

Returns None if the outlet doesn’t exist

Source

pub fn has_named_outlet(&self, name: &str) -> bool

Check if this route has a named outlet

Source

pub fn named_outlet_names(&self) -> Vec<&str>

Get all named outlet names

Source

pub fn matches(&self, path: &str) -> Option<RouteMatch>

Match a path against this route

Source

pub fn build( &self, window: &mut Window, cx: &mut App, params: &RouteParams, ) -> Option<AnyElement>

Build the view for this route

Source

pub fn find_child(&self, segment: &str) -> Option<&RouteRef>

Find a child route by path segment

Used internally by RouterOutlet to resolve child routes.

Source

pub fn get_children(&self) -> &[RouteRef]

Get all child routes

Trait Implementations§

Source§

impl Debug for Route

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Route

§

impl !RefUnwindSafe for Route

§

impl Send for Route

§

impl Sync for Route

§

impl Unpin for Route

§

impl !UnwindSafe for Route

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more