Improve inline docs (#2460)

Improve inline docs

* improve incorrect event handler return error message

* Improve event handler docs

* document the eval functions

* document spawn and common spawn errors

* fix event handler docs

* add notes about how you use attributes and elements in rsx

* add doc aliases for attributes and events we rename

* add some more aliases for common search terms

* don't doc ignore any public examples in core

* don't ignore public doc examples in ssr

* don't ignore examples in the dioxus package readme

* add a warning when you launch without a renderer enabled

* fix some outdated element docs

* add a bunch of examples to resource

* add notes about desktop events

* add more docs for use_resource

* add on_unimplemented hint to Dependency

* fix some unresolved links

* add examples to each of the router traits

* add not implemented errors for router traits

* add an example to the routable trait

* expand rsx macro docs

* improve memo docs

* update the dioxus readme

* mention dioxus crate features in the docs

* fix a bunch of doc tests

* fix html doc tests

* fix router doc tests

* fix dioxus signals doc tests

* fix dioxus ssr doc tests

* fix use_future example in the hooks cheat sheet

* add a javascript alias for eval

* fix hook explanation values

* remove unused embed-doc-image dependency
This commit is contained in:
Evan Almloff authored and GitHub committed 2024-06-06 18:15:17 -07:00
1 parent 054351139f
commit 0127501dbf
71 files changed
+4132 -1162

No files matched your search

+1
View File
@@ -40,6 +40,7 @@ use crate::utils::use_router_internal::use_router_internal;
/// # vdom.rebuild_in_place();
/// # assert_eq!(dioxus_ssr::render(&vdom), "<h1>App</h1><h2>Current Path</h2><p>/</p>")
/// ```
#[doc(alias = "use_url")]
#[must_use]
pub fn use_route<R: Routable + Clone>() -> R {
match use_router_internal() {
+2 -1
View File
@@ -7,7 +7,8 @@ pub fn use_router() -> RouterContext {
use_router_internal().expect("use_route must have access to a router")
}
/// Aquire the router without subscribing to updates.
/// Acquire the router without subscribing to updates.
#[doc(alias = "url")]
pub fn router() -> RouterContext {
dioxus_lib::prelude::consume_context()
}
+369 -12
View File
@@ -24,11 +24,57 @@ impl<E: Display> Display for RouteParseError<E> {
}
}
/// Something that can be created from an entire query string.
/// Something that can be created from an entire query string. This trait must be implemented for any type that is spread into the query segment like `#[route("/?:..query")]`.
///
/// This trait needs to be implemented if you want to turn a query string into a struct.
///
/// A working example can be found in the `examples` folder in the root package under `query_segments_demo`.
/// **This trait is automatically implemented for any types that implement `From<&str>`.**
///
/// ```rust
/// use dioxus::prelude::*;
///
/// #[derive(Routable, Clone, PartialEq, Debug)]
/// enum Route {
/// // FromQuery must be implemented for any types you spread into the query segment
/// #[route("/?:..query")]
/// Home {
/// query: CustomQuery
/// },
/// }
///
/// #[derive(Default, Clone, PartialEq, Debug)]
/// struct CustomQuery {
/// count: i32,
/// }
///
/// // We implement From<&str> for CustomQuery so that FromQuery is implemented automatically
/// impl From<&str> for CustomQuery {
/// fn from(query: &str) -> Self {
/// CustomQuery {
/// count: query.parse().unwrap_or(0),
/// }
/// }
/// }
///
/// // We also need to implement Display for CustomQuery which will be used to format the query string into the URL
/// impl std::fmt::Display for CustomQuery {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// write!(f, "{}", self.count)
/// }
/// }
///
/// # #[component]
/// # fn Home(query: CustomQuery) -> Element {
/// # todo!()
/// # }
/// ```
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`FromQuery` is not implemented for `{Self}`",
label = "spread query",
note = "FromQuery is automatically implemented for types that implement `From<&str>`. You need to either implement From<&str> or implement FromQuery manually."
)
)]
pub trait FromQuery {
/// Create an instance of `Self` from a query string.
fn from_query(query: &str) -> Self;
@@ -40,9 +86,63 @@ impl<T: for<'a> From<&'a str>> FromQuery for T {
}
}
/// Something that can be created from a query argument.
/// Something that can be created from a query argument. This trait must be implemented for any type that is used as a query argument like `#[route("/?:query")]`.
///
/// This trait must be implemented for every type used within a query string in the router macro.
/// **This trait is automatically implemented for any types that implement `FromStr` and `Default`.**
///
/// ```rust
/// use dioxus::prelude::*;
///
/// #[derive(Routable, Clone, PartialEq, Debug)]
/// enum Route {
/// // FromQuerySegment must be implemented for any types you use in the query segment
/// // When you don't spread the query, you can parse multiple values form the query
/// // This url will be in the format `/?query=123&other=456`
/// #[route("/?:query&:other")]
/// Home {
/// query: CustomQuery,
/// other: i32,
/// },
/// }
///
/// // We can derive Default for CustomQuery
/// // If the router fails to parse the query value, it will use the default value instead
/// #[derive(Default, Clone, PartialEq, Debug)]
/// struct CustomQuery {
/// count: i32,
/// }
///
/// // We implement FromStr for CustomQuery so that FromQuerySegment is implemented automatically
/// impl std::str::FromStr for CustomQuery {
/// type Err = <i32 as std::str::FromStr>::Err;
///
/// fn from_str(query: &str) -> Result<Self, Self::Err> {
/// Ok(CustomQuery {
/// count: query.parse()?,
/// })
/// }
/// }
///
/// // We also need to implement Display for CustomQuery which will be used to format the query string into the URL
/// impl std::fmt::Display for CustomQuery {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// write!(f, "{}", self.count)
/// }
/// }
///
/// # #[component]
/// # fn Home(query: CustomQuery, other: i32) -> Element {
/// # todo!()
/// # }
/// ```
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`FromQueryArgument` is not implemented for `{Self}`",
label = "query argument",
note = "FromQueryArgument is automatically implemented for types that implement `FromStr` and `Default`. You need to either implement FromStr and Default or implement FromQueryArgument manually."
)
)]
pub trait FromQueryArgument: Default {
/// The error that can occur when parsing a query argument.
type Err;
@@ -68,9 +168,10 @@ where
}
}
/// Something that can be created from an entire hash fragment.
/// Something that can be created from an entire hash fragment. This must be implemented for any type that is used as a hash fragment like `#[route("/#:hash_fragment")]`.
///
/// This trait needs to be implemented if you want to turn a hash fragment into a struct.
///
/// **This trait is automatically implemented for any types that implement `FromStr` and `Default`.**
///
/// # Example
///
@@ -123,6 +224,15 @@ where
/// }
/// }
/// }
/// ```
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`FromHashFragment` is not implemented for `{Self}`",
label = "hash fragment",
note = "FromHashFragment is automatically implemented for types that implement `FromStr` and `Default`. You need to either implement FromStr and Default or implement FromHashFragment manually."
)
)]
pub trait FromHashFragment {
/// Create an instance of `Self` from a hash fragment.
fn from_hash_fragment(hash: &str) -> Self;
@@ -144,7 +254,64 @@ where
}
}
/// Something that can be created from a route segment.
/// Something that can be created from a single route segment. This must be implemented for any type that is used as a route segment like `#[route("/:route_segment")]`.
///
///
/// **This trait is automatically implemented for any types that implement `FromStr` and `Default`.**
///
/// ```rust
/// use dioxus::prelude::*;
///
/// #[derive(Routable, Clone, PartialEq, Debug)]
/// enum Route {
/// // FromRouteSegment must be implemented for any types you use in the route segment
/// // When you don't spread the route, you can parse multiple values from the route
/// // This url will be in the format `/123/456`
/// #[route("/:route_segment_one/:route_segment_two")]
/// Home {
/// route_segment_one: CustomRouteSegment,
/// route_segment_two: i32,
/// },
/// }
///
/// // We can derive Default for CustomRouteSegment
/// // If the router fails to parse the route segment, it will use the default value instead
/// #[derive(Default, PartialEq, Clone, Debug)]
/// struct CustomRouteSegment {
/// count: i32,
/// }
///
/// // We implement FromStr for CustomRouteSegment so that FromRouteSegment is implemented automatically
/// impl std::str::FromStr for CustomRouteSegment {
/// type Err = <i32 as std::str::FromStr>::Err;
///
/// fn from_str(route_segment: &str) -> Result<Self, Self::Err> {
/// Ok(CustomRouteSegment {
/// count: route_segment.parse()?,
/// })
/// }
/// }
///
/// // We also need to implement Display for CustomRouteSegment which will be used to format the route segment into the URL
/// impl std::fmt::Display for CustomRouteSegment {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// write!(f, "{}", self.count)
/// }
/// }
///
/// # #[component]
/// # fn Home(route_segment_one: CustomRouteSegment, route_segment_two: i32) -> Element {
/// # todo!()
/// # }
/// ```
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`FromRouteSegment` is not implemented for `{Self}`",
label = "route segment",
note = "FromRouteSegment is automatically implemented for types that implement `FromStr` and `Default`. You need to either implement FromStr and Default or implement FromRouteSegment manually."
)
)]
pub trait FromRouteSegment: Sized {
/// The error that can occur when parsing a route segment.
type Err;
@@ -170,7 +337,68 @@ fn full_circle() {
assert_eq!(String::from_route_segment(route).unwrap(), route);
}
/// Something that can be converted to route segments.
/// Something that can be converted into multiple route segments. This must be implemented for any type that is spread into the route segment like `#[route("/:..route_segments")]`.
///
///
/// **This trait is automatically implemented for any types that implement `IntoIterator<Item=impl Display>`.**
///
/// ```rust
/// use dioxus::prelude::*;
///
/// #[derive(Routable, Clone, PartialEq, Debug)]
/// enum Route {
/// // FromRouteSegments must be implemented for any types you use in the route segment
/// // When you spread the route, you can parse multiple values from the route
/// // This url will be in the format `/123/456/789`
/// #[route("/:..numeric_route_segments")]
/// Home {
/// numeric_route_segments: NumericRouteSegments,
/// },
/// }
///
/// // We can derive Default for NumericRouteSegments
/// // If the router fails to parse the route segment, it will use the default value instead
/// #[derive(Default, PartialEq, Clone, Debug)]
/// struct NumericRouteSegments {
/// numbers: Vec<i32>,
/// }
///
/// // Implement ToRouteSegments for NumericRouteSegments so that we can display the route segments
/// impl ToRouteSegments for &NumericRouteSegments {
/// fn display_route_segments(self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// for number in &self.numbers {
/// write!(f, "/{}", number)?;
/// }
/// Ok(())
/// }
/// }
///
/// // We also need to parse the route segments with `FromRouteSegments`
/// impl FromRouteSegments for NumericRouteSegments {
/// type Err = <i32 as std::str::FromStr>::Err;
///
/// fn from_route_segments(segments: &[&str]) -> Result<Self, Self::Err> {
/// let mut numbers = Vec::new();
/// for segment in segments {
/// numbers.push(segment.parse()?);
/// }
/// Ok(NumericRouteSegments { numbers })
/// }
/// }
///
/// # #[component]
/// # fn Home(numeric_route_segments: NumericRouteSegments) -> Element {
/// # todo!()
/// # }
/// ```
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`ToRouteSegments` is not implemented for `{Self}`",
label = "route segment",
note = "ToRouteSegments is automatically implemented for types that implement `IntoIterator` with an `Item` type that implements `Display`. You need to either implement IntoIterator or implement ToRouteSegments manually."
)
)]
pub trait ToRouteSegments {
/// Display the route segments. You must url encode the segments.
fn display_route_segments(self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
@@ -205,7 +433,68 @@ fn to_route_segments() {
assert_eq!(DisplaysRoute.to_string(), "/hello/world");
}
/// Something that can be created from route segments.
/// Something that can be created from multiple route segments. This must be implemented for any type that is spread into the route segment like `#[route("/:..route_segments")]`.
///
///
/// **This trait is automatically implemented for any types that implement `FromIterator<impl Display>`.**
///
/// ```rust
/// use dioxus::prelude::*;
///
/// #[derive(Routable, Clone, PartialEq, Debug)]
/// enum Route {
/// // FromRouteSegments must be implemented for any types you use in the route segment
/// // When you spread the route, you can parse multiple values from the route
/// // This url will be in the format `/123/456/789`
/// #[route("/:..numeric_route_segments")]
/// Home {
/// numeric_route_segments: NumericRouteSegments,
/// },
/// }
///
/// // We can derive Default for NumericRouteSegments
/// // If the router fails to parse the route segment, it will use the default value instead
/// #[derive(Default, Clone, PartialEq, Debug)]
/// struct NumericRouteSegments {
/// numbers: Vec<i32>,
/// }
///
/// // Implement ToRouteSegments for NumericRouteSegments so that we can display the route segments
/// impl ToRouteSegments for &NumericRouteSegments {
/// fn display_route_segments(self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// for number in &self.numbers {
/// write!(f, "/{}", number)?;
/// }
/// Ok(())
/// }
/// }
///
/// // We also need to parse the route segments with `FromRouteSegments`
/// impl FromRouteSegments for NumericRouteSegments {
/// type Err = <i32 as std::str::FromStr>::Err;
///
/// fn from_route_segments(segments: &[&str]) -> Result<Self, Self::Err> {
/// let mut numbers = Vec::new();
/// for segment in segments {
/// numbers.push(segment.parse()?);
/// }
/// Ok(NumericRouteSegments { numbers })
/// }
/// }
///
/// # #[component]
/// # fn Home(numeric_route_segments: NumericRouteSegments) -> Element {
/// # todo!()
/// # }
/// ```
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`FromRouteSegments` is not implemented for `{Self}`",
label = "spread route segments",
note = "FromRouteSegments is automatically implemented for types that implement `FromIterator` with an `Item` type that implements `Display`. You need to either implement FromIterator or implement FromRouteSegments manually."
)
)]
pub trait FromRouteSegments: Sized {
/// The error that can occur when parsing route segments.
type Err;
@@ -233,12 +522,80 @@ type SiteMapFlattened<'a> = FlatMap<
fn(&SiteMapSegment) -> Vec<Vec<SegmentType>>,
>;
/// Something that can be:
/// The Routable trait is implemented for types that can be converted to and from a route and be rendered as a page.
///
/// A Routable object is something that can be:
/// 1. Converted from a route.
/// 2. Converted to a route.
/// 3. Rendered as a component.
///
/// This trait can be derived using the `#[derive(Routable)]` macro.
/// This trait should generally be derived using the [`dioxus_router_macro::Routable`] macro which has more information about the syntax.
///
/// ## Example
/// ```rust
/// use dioxus::prelude::*;
///
/// fn App() -> Element {
/// rsx! {
/// Router::<Route> { }
/// }
/// }
///
/// // Routes are generally enums that derive `Routable`
/// #[derive(Routable, Clone, PartialEq, Debug)]
/// enum Route {
/// // Each enum has an associated url
/// #[route("/")]
/// Home {},
/// // Routes can include dynamic segments that are parsed from the url
/// #[route("/blog/:blog_id")]
/// Blog { blog_id: usize },
/// // Or query segments that are parsed from the url
/// #[route("/edit?:blog_id")]
/// Edit { blog_id: usize },
/// // Or hash segments that are parsed from the url
/// #[route("/hashtag/#:hash")]
/// Hash { hash: String },
/// }
///
/// // Each route variant defaults to rendering a component of the same name
/// #[component]
/// fn Home() -> Element {
/// rsx! {
/// h1 { "Home" }
/// }
/// }
///
/// // If the variant has dynamic parameters, those are passed to the component
/// #[component]
/// fn Blog(blog_id: usize) -> Element {
/// rsx! {
/// h1 { "Blog" }
/// }
/// }
///
/// #[component]
/// fn Edit(blog_id: usize) -> Element {
/// rsx! {
/// h1 { "Edit" }
/// }
/// }
///
/// #[component]
/// fn Hash(hash: String) -> Element {
/// rsx! {
/// h1 { "Hashtag #{hash}" }
/// }
/// }
/// ```
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`Routable` is not implemented for `{Self}`",
label = "Route",
note = "Routable should generally be derived using the `#[derive(Routable)]` macro."
)
)]
pub trait Routable: FromStr + Display + Clone + 'static {
/// The error that can occur when parsing a route.
const SITE_MAP: &'static [SiteMapSegment];