docs: move around examples

This commit is contained in:
Jonathan Kelley committed 2021-06-17 18:00:32 -04:00
1 parent b9ff95fa12
commit 70cd46dbb2
45 files changed
+3742 -2291

No files matched your search

+143
View File
@@ -0,0 +1,143 @@
#![allow(unused)]
/*
This example shows how to encapsulate sate in dioxus components with the reducer pattern.
This pattern is very useful when a single component can handle many types of input that can
be represented by an enum. This particular pattern is very powerful in rust where ADTs can simplify
much of the traditional reducer boilerplate.
*/
fn main() {}
use dioxus::prelude::*;
use std::future::Future;
enum Actions {
Pause,
Play,
}
struct SomeState {
is_playing: bool,
}
impl SomeState {
fn new() -> Self {
Self { is_playing: false }
}
fn reduce(&mut self, action: Actions) {
match action {
Actions::Pause => self.is_playing = false,
Actions::Play => self.is_playing = true,
}
}
fn is_playing(&self) -> &'static str {
match self.is_playing {
true => "currently playing!",
false => "not currently playing",
}
}
}
pub static ExampleReducer: FC<()> = |ctx| {
let (state, reduce) = use_reducer(&ctx, SomeState::new, SomeState::reduce);
let is_playing = state.is_playing();
ctx.render(rsx! {
div {
h1 {"Select an option"}
h3 {"The radio is... {is_playing}!"}
button {
"Pause"
onclick: move |_| reduce(Actions::Pause)
}
button {
"Play"
onclick: move |_| reduce(Actions::Play)
}
}
})
};
/*
*/
struct AppContext {
name: String,
}
enum KindaState {
Ready,
Complete,
Erred,
}
static EnumReducer: FC<()> = |ctx| {
let (state, reduce) = use_reducer(&ctx, || KindaState::Ready, |cur, new| *cur = new);
let status = match state {
KindaState::Ready => "Ready",
KindaState::Complete => "Complete",
KindaState::Erred => "Erred",
};
ctx.render(rsx! {
div {
h1 {"{status}"}
button {
"Set Ready"
onclick: move |_| reduce(KindaState::Ready)
}
button {
"Set Complete"
onclick: move |_| reduce(KindaState::Complete)
}
button {
"Set Erred"
onclick: move |_| reduce(KindaState::Erred)
}
ul {
{(0..10).map(|f| {
rsx!{
li {
"hello there!"
}
}
})}
}
}
})
};
/// Demonstrate how the DebugRenderer can be used to unit test components without needing a browser
/// These tests can run locally.
/// They use the "compare" method of the debug renderer to do partial tree compares for succint
#[test]
fn ensure_it_works_properly() -> dioxus::error::Result<()> {
let mut test = DebugRenderer::new(EnumReducer);
test.compare(rsx! { div { h1 {"Ready"} } })?;
test.trigger_listener(1)?;
test.compare(rsx! { div { h1 {"Ready"} } })?;
test.trigger_listener(2)?;
test.compare(rsx! { div { h1 {"Complete"} } })?;
test.trigger_listener(3)?;
test.compare(rsx! { div { h1 {"Erred"} } })?;
Ok(())
}
-94
View File
@@ -1,94 +0,0 @@
//! Example App
//! --------------
//!
//! This example shows how to use the cross-platform abilities of dioxus to generate everything a dioxus app might need.
//! All of your apps will look like this.
//!
//! cargo run --features dioxus/static
use std::u32;
use dioxus::prelude::Context;
// #[allow(unused_lifetimes)]
#[derive(Debug, PartialEq, Hash)]
struct Pool<'a> {
a: u32,
b: &'a str,
}
struct UserData {}
type Query<In, Out> = fn(&Pool, In) -> Result<Out, ()>;
// type Query<In, Out> = fn(&Pool, In) -> Out;
static GET_USER: Query<String, Vec<UserData>> = |pool, name| {
//
let b = Ok(())?;
let b = Ok(())?;
let b = Ok(())?;
let b = Ok(())?;
let b = Ok(())?;
let b = Ok(())?;
todo!()
};
static SET_USER: Query<String, Vec<UserData>> = |pool, name| {
//
todo!()
};
fn main() {
// // returns a future
// let user_data = use_db(&ctx, GET_USER, || "Bill");
// use_try_suspense(&ctx, async move {
// match user_data.await? {
// Ok() => {}
// Err(err) => {}
// }
// })
// }
// fn use_try_suspense(ctx: &Context<()>) {
// let c: Result<(), ()> = {
// // let b = Ok(());
// // b?
// };
}
mod launches {
#[cfg(feature = "wasm")]
fn launch() {
// launch the wasm_rednerer
}
#[cfg(feature = "static")]
fn launch() {
// render the tree to text
}
// #[cfg(features = "server")]
// fn launch() {
// // launch the app
// }
// #[cfg(features = "liveview")]
// fn launch() {
// // launch the app
// }
// #[cfg(features = "desktop")]
// fn launch() {
// // launch the app
// }
// #[cfg(features = "android")]
// fn launch() {
// // launch a simulator in dev mode
// }
// #[cfg(features = "ios")]
// fn launch() {
// // launch a simulator in dev mode
// }
}
-39
View File
@@ -1,39 +0,0 @@
//! Example: External Updates
//! -------------------------
//!
//! Cause updates to the VirtualDOM state from outside the component lifecycle.
//! The root props could be changed or the use_receiver hook could be used.
//!
//!
fn main() {
let (recv, sender) = channel();
async_std::task::spawn({
for location in ["a", "b", "c", "d"] {
sender.send(location);
}
});
let app = diouxs_webview::launch_with_props(App, RootProps { recv }).await;
}
struct RootProps {
navigator: Receiver<&'static str>,
}
fn App(ctx: Context, props: &RootProps) -> VNode {
let router = use_router(&ctx, |router| {});
let navigator = use_history(&ctx);
use_receiver(&ctx, || ctx.recv.clone(), |to| navigator.navigate(to));
ctx.render(rsx! {
div {
a { href: "/dogs/"}
a { href: "/cats/"}
{content}
}
})
}
+30
View File
@@ -0,0 +1,30 @@
#![allow(unused, non_upper_case_globals)]
use dioxus_core::prelude::*;
fn main() {
Some(10)
.map(|f| f * 5)
.map(|f| f / 3)
.map(|f| f * 5)
.map(|f| f / 3);
}
static Example: FC<()> = |ctx| {
let (name, set_name) = use_state(&ctx, || "...?");
ctx.render(rsx!(
div {
h1 { "Hello, {name}" }
// look ma - we can rsx! and html! together
{["jack", "jill"].iter().map(|f| html!(<button onclick={move |_| set_name(f)}> "{f}" </button>))}
}
))
};
pub fn render<'src, 'a, F: for<'b> FnOnce(&'b NodeCtx<'src>) -> VNode<'src> + 'src + 'a, P>(
ctx: &'a Context<'src, P>,
lazy_nodes: LazyNodes<'src, F>,
) -> VNode<'src> {
ctx.render(lazy_nodes)
}
-65
View File
@@ -1,65 +0,0 @@
use dioxus::prelude::*;
use tide::{with_state, Request};
use tide_websockets::{WebSocket, WebSocketConnection};
fn main() {
let mut g = Context { props: &() };
LiveComponent(&mut g);
}
#[cfg(not(target_arch = "wasm32"))]
async fn server() -> tide::Result<()> {
// Build the API
let mut app = tide::with_state(());
app.at("/app").get(WebSocket::new(live_handler));
// Launch the server
app.listen("127.0.0.1:8080").await?;
Ok(())
}
async fn live_handler(req: Request<()>, stream: WebSocketConnection) -> tide::Result<()> {
Ok(())
}
static LiveComponent: FC<()> = |ctx| {
use_live_component(
ctx,
#[cfg(target_arch = "wasm32")]
|| {
// Always wait on the context's live component API
// suspend the component until this promise arrives, or fall back
let g = &LiveComponent;
html! {
<div>
{"Hello world!"}
</div>
}
},
#[cfg(not(target_arch = "wasm32"))]
|| {
// actually use the code originally specified in the component
// this gives use the function pointer. We don't necessarily get to hash the same pointer between two binaries
// Some key will need to be made, likely based on the function parameter
let g = &LiveComponent;
html! {
<div>
{"Hello world!"}
</div>
}
},
)
};
/// This hooks connects with the LiveContext at the top of the app.
fn use_live_component<T>(ctx: &mut Context<T>, b: fn() -> VNode) -> VNode {
todo!()
}
/// LiveContext is a special, limited form of the context api that disallows the "Context API"
/// Its purpose is to shield the original Context where calls to use_context will fail. Instead of panicing and confusing
/// users, we simply disallow usage of "use_context" and "childen". In effect, only serialiable props can be allowed.
///
/// In the future, we might try to lift these restrictions (esp children since they are virtual) but are limited via the web connection
struct LiveContext {}
-42
View File
@@ -1,42 +0,0 @@
//! Dioxus Router
//! -------------
//!
//! This exmaple showcases the Dioxus Router hook. This hook makes it possible to using the browser's navigation API to
//! display different content based on the Page's URL. The hook provides a configuration object that calls various
//! specified callbacks whenever the page URL changes. Using this hook should feel like building a "URL directory", similar
//! to how Tide handles paths.
use dioxus::prelude::*;
fn main() {
diouxs_webview::launch(App).run().await
}
fn App(ctx: Context<()>) -> VNode {
let router = use_router(&ctx, |router| {
//
router.get("/dogs/:dogId/").render(|ctx, request| {
rsx! {
div {
}
}
});
router.get("/cats/:catId/").render(|ctx, request| {
rsx! {
div {
}
}
});
});
ctx.render(rsx! {
div {
a { href: "/dogs/"}
a { href: "/cats/"}
{router.render()}
}
})
}
+60
View File
@@ -0,0 +1,60 @@
fn main() {}
mod components {
use baller::Baller;
use dioxus::prelude::*;
fn example() {
let g = rsx! {
div {
crate::components::baller::Baller {}
baller::Baller {
}
Taller {
a: "asd"
}
baller::Baller {}
baller::Baller {}
Baller {
// todo: manual props
// {...BallerProps {}}
}
div {
a: "asd",
a: "asd",
a: "asd",
a: "asd",
div {
"asdas",
"asdas",
"asdas",
"asdas",
div {},
div {
class: "asdasd"
},
}
}
}
};
}
mod baller {
use super::*;
pub struct BallerProps {}
pub fn Baller(ctx: Context<()>) -> VNode {
todo!()
}
}
#[derive(Debug, PartialEq, Props)]
pub struct TallerProps {
a: &'static str,
}
pub fn Taller(ctx: Context<TallerProps>) -> VNode {
let b = true;
todo!()
}
}
-45
View File
@@ -1,45 +0,0 @@
//! DioxusLabs Webiste
//! ------------------
//!
//! This is the example powering the DioxusLabs website :)
//! It's always good to dogfood your code, right?
use dioxus::prelude::*;
fn main() {}
mod state {
pub struct AppState {
cur_page: Route,
}
pub enum Route {
Homepage,
Docs,
}
}
static APP: FC<()> = |ctx| {
ctx.render(html! {
<div>
<div>
})
};
/// Draw the navbar on top of the screen
static Navbar: FC<state::Route> = |ctx| {
ctx.render(html! {
<div>
<div>
})
};
static Homepage: FC<()> = |ctx| {
ctx.render(html! {
<div>
<div>
})
};
+3 -3
View File
@@ -9,8 +9,8 @@
use dioxus::prelude::*;
async fn main() {
dioxus_webview::launch(|ctx| {
fn main() {
dioxus::webview::launch(|ctx| {
let (count, set_count) = use_state(&ctx, || 0);
ctx.render(rsx! {
@@ -23,5 +23,5 @@ async fn main() {
}
}
})
}).await;
});
}