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

+7 -10
View File
@@ -5,13 +5,8 @@ use dioxus_core::prelude::*;
static Example: FC<()> = |ctx| {
ctx.render(dioxus_core::prelude::LazyNodes::new(move |ctx| {
let bump = ctx.bump();
dioxus::builder::ElementBuilder::new(ctx, "h1")
.children([{
use bumpalo::core_alloc::fmt::Write;
let mut s = bumpalo::collections::String::new_in(bump);
write!(s, "hello");
dioxus::builder::text2(s)
}])
dioxus_core::builder::ElementBuilder::new(ctx, "h1")
.children([dioxus_core::builder::text3(bump, format_args!("hello"))])
.finish()
}))
};
@@ -22,9 +17,11 @@ struct Props {
static Example2: FC<Props> = |ctx| {
ctx.render(dioxus_core::prelude::LazyNodes::new(move |__ctx| {
let bump = __ctx.bump();
dioxus::builder::ElementBuilder::new(__ctx, "h1")
.children([{ dioxus::builder::text3(bump, format_args!("{}", ctx.text)) }])
// .children([{ dioxus::builder::text3(bump, format_args!("hello")) }])
dioxus_core::builder::ElementBuilder::new(__ctx, "h1")
.children([dioxus_core::builder::text3(
bump,
format_args!("{}", ctx.props.text),
)])
.finish()
}))
};
-152
View File
@@ -1,152 +0,0 @@
/*
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.
*/
#![allow(unused)]
use std::future::Future;
use dioxus::hooks::use_reducer;
use dioxus_ssr::prelude::*;
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 contents = helper(&ctx);
let status = match state {
KindaState::Ready => "Ready",
KindaState::Complete => "Complete",
KindaState::Erred => "Erred",
};
ctx.render(rsx! {
div {
h1 {"{status}"}
{contents}
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!"
}
}
})}
}
}
})
};
fn helper(ctx: &Context) -> VNode {
ctx.render(rsx! {
div {}
})
}
/// 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(())
}
+35 -50
View File
@@ -4,14 +4,12 @@
//! It's slightly more advanced than just cloning, but well worth the investment.
//!
//! If you use the FC macro, we handle the lifetimes automatically, making it easy to write efficient & performant components.
fn main() {}
use std::{borrow::Borrow, ops::Deref, rc::Rc};
use dioxus_core::prelude::*;
use std::rc::Rc;
struct Props {
struct AppProps {
items: Vec<Rc<ListItem>>,
}
@@ -21,67 +19,54 @@ struct ListItem {
age: u32,
}
fn app(ctx: Context<Props>) -> VNode {
fn app(ctx: Context<AppProps>) -> VNode {
let (val, set_val) = use_state(&ctx, || 0);
ctx.render(dioxus::prelude::LazyNodes::new(move |c| {
let mut root = builder::ElementBuilder::new(c, "div");
for child in &ctx.items {
// notice that the child directly borrows from our vec
// this makes lists very fast (simply views reusing lifetimes)
// <ChildItem item=child hanldler=setter />
root = root.child(builder::virtual_child(
c,
ChildItem,
// create the props with nothing but the fc<T>
fc_to_builder(ChildItem)
.item(child.clone())
.item_handler(Callback(set_val.clone()))
.build(),
None,
&[],
));
}
root.finish()
ctx.render(LazyNodes::new(move |_nodectx| {
builder::ElementBuilder::new(_nodectx, "div")
.iter_child({
ctx.items.iter().map(|child| {
builder::virtual_child(
_nodectx,
ChildItem,
ChildProps {
item: child.clone(),
item_handler: set_val.clone(),
},
None,
&[],
)
})
})
.iter_child([builder::ElementBuilder::new(_nodectx, "div")
.iter_child([builder::text3(_nodectx.bump(), format_args!("{}", val))])
.finish()])
.finish()
}))
}
// props should derive a partialeq implementation automatically, but implement ptr compare for & fields
#[derive(Props, PartialEq)]
struct ChildProps {
// Pass down complex structs
item: Rc<ListItem>,
// Even pass down handlers!
item_handler: Callback<i32>,
item_handler: Rc<dyn Fn(i32)>,
}
fn ChildItem<'a>(ctx: Context<ChildProps>) -> VNode {
ctx.render(rsx! {
div {
// onclick: move |evt| (ctx.item_handler)(10)
h1 { "abcd123 {ctx.item.name}" }
h2 { "abcd123" }
div {
"abcd123"
h2 { }
p { }
}
}
})
fn ChildItem<'a>(cx: Context<'a, ChildProps>) -> VNode {
cx.render(LazyNodes::new(move |__cx| todo!()))
}
#[derive(Clone)]
struct Callback<I, O = ()>(Rc<dyn Fn(I) -> O>);
impl<I, O> Deref for Callback<I, O> {
type Target = Rc<dyn Fn(I) -> O>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<I, O> PartialEq for Callback<I, O> {
impl PartialEq for ChildProps {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
false
}
}
unsafe impl Properties for ChildProps {
type Builder = ();
const CAN_BE_MEMOIZED: bool = false;
fn builder() -> Self::Builder {
()
}
}
-29
View File
@@ -1,29 +0,0 @@
use std::{ops::Deref, rc::Rc};
use dioxus::virtual_dom::Scope;
use dioxus_core::prelude::*;
type RcStr = Rc<str>;
fn main() {
let r: RcStr = "asdasd".into();
let r: RcStr = String::from("asdasd").into();
let g = rsx! {
div {
Example {}
}
};
}
static Example: FC<()> = |ctx| {
let nodes = ctx.children();
//
rsx! { in ctx,
div {
h1 {"these are children nodes: "}
{nodes}
}
}
};
-72
View File
@@ -1,72 +0,0 @@
use dioxus_core::component::fc_to_builder;
use dioxus_core::prelude::*;
static BLAH: FC<()> = |ctx| {
let g = "asd".to_string();
ctx.render(rsx! {
div {
SomeComponent {
some_field: g
}
}
})
};
#[derive(PartialEq, Props)]
pub struct ExampleProps {
some_field: String,
}
static SomeComponent: FC<ExampleProps> = |ctx| {
let blah = rsx! {
div {}
};
let data = match 1 {
1 => ctx.render(rsx! (
div {
h1 {}
h3 {}
}
)),
1 => ctx.render(rsx!( div { "abc" } )),
2 => ctx.render(rsx!( div { "abc" } )),
3 => ctx.render(rsx!( div { "abc" } )),
_ => todo!(),
};
let data = match 1 {
1 => ctx.render(rsx! (
div {
h1 {}
h3 {}
}
)),
1 => ctx.render(rsx!(
div { "abc" }
)),
2 => ctx.render(rsx!(
div { "abc" }
)),
3 => ctx.render(rsx!(
div { "abc" }
)),
_ => todo!(),
};
let i = (0..10).map(|v| {
rsx! {
div {
"{v}"
}
}
});
ctx.render(rsx! {
div {
""
}
})
};
fn main() {}
-30
View File
@@ -1,30 +0,0 @@
#![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)
}
-59
View File
@@ -1,59 +0,0 @@
use baller::Baller;
use dioxus_core::prelude::*;
fn main() {
let g = rsx! {
div {
crate::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 {
// classes: {[ ("baller", true), ("maller", false) ]}
// class: "asdasd"
// class: "{customname}",
// class: {[("baller", true), ("hover", false)]}
},
}
}
}
};
}
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!()
}
-44
View File
@@ -1,44 +0,0 @@
#![allow(unused)]
//! Example of components in
use std::{borrow::Borrow, marker::PhantomData};
use dioxus_core::prelude::*;
fn main() {}
static Header: FC<()> = |ctx| {
let inner = use_ref(&ctx, || 0);
let handler1 = move || println!("Value is {}", inner.borrow());
ctx.render(dioxus::prelude::LazyNodes::new(|nodectx| {
builder::ElementBuilder::new(nodectx, "div")
.child(VNode::Component(nodectx.bump().alloc(VComponent::new(
nodectx,
Bottom,
(),
None,
&[],
))))
.finish()
}))
};
static Bottom: FC<()> = |ctx| {
ctx.render(html! {
<div>
<h1> "bruh 1" </h1>
<h1> "bruh 2" </h1>
</div>
})
};
fn Top(ctx: Context<()>) -> VNode {
ctx.render(html! {
<div>
<h1> "bruh 1" </h1>
<h1> "bruh 2" </h1>
</div>
})
}
-16
View File
@@ -1,16 +0,0 @@
use dioxus_core::prelude::*;
#[derive(Debug, PartialEq, Props)]
struct SomeProps {
a: i32,
// automatically do the default (none) and automatically Into<T>
#[builder(default, setter(strip_option))]
b: Option<i32>,
}
fn main() {
let g: SomeProps = SomeProps::builder().a(10).b(10).build();
let _r = g.b.unwrap_or_else(|| 10);
}
-47
View File
@@ -1,47 +0,0 @@
use dioxus_core::prelude::*;
fn main() {}
trait SProps {}
trait Comp {
type Props;
}
impl<T> Comp for FC<T> {
type Props = T;
}
fn test() {
// let g: FC<ButtonProps> = CustomButton;
}
trait Render: Sized {
fn render(ctx: Context<Self>) -> VNode;
}
// include as much as you might accept
struct Button {
onhover: Option<Box<dyn Fn()>>,
}
impl Render for Button {
fn render(ctx: Context<Self>) -> VNode {
let _onfocus = move |_evt: ()| log::debug!("Focused");
// todo!()
ctx.render(rsx! {
button {
// ..ctx.attrs,
class: "abc123",
// style: { a: 2, b: 3, c: 4 },
onclick: move |_evt| {
// log::info("hello world");
},
// Custom1 { a: 123 }
// Custom2 { a: 456, "abc", h1 {"1"}, h2 {"2"} }
// Custom3 { a: "sometext goes here" }
// Custom4 { onclick: |evt| log::info("click") }
}
})
}
}
-18
View File
@@ -1,18 +0,0 @@
//! The book of patterns
//! -----
//!
//! This "book" shows a bunch of useful patterns, ergonomic highlights, and quirks for common usecases when building components.
//!
//! Here's what's in the book:
//! - [ ] Use the builder pattern directly instead of the macro
//! - [ ] Using statics instead of functions for components without type hassle.
//! - [ ] Use the FC macro on statics and fns for inling props
//! - [ ] Using borrowed data from parent to child
//!
//! Running this example will generate a beautiful webpage. This webpage is used on the diouxs website.
fn main() {}
mod static_usage {}
mod fc_macro {}
mod borrowed_data {}
-41
View File
@@ -1,41 +0,0 @@
use dioxus_core::debug_renderer::DebugRenderer;
use dioxus_core::{component::Properties, prelude::*};
fn main() -> Result<(), ()> {
let p1 = SomeProps { name: "bob".into() };
let _vdom = DebugRenderer::new_with_props(Example, p1);
Ok(())
}
#[derive(Debug, PartialEq, Props)]
struct SomeProps {
name: String,
}
static Example: FC<SomeProps> = |ctx| {
ctx.render(html! {
<div>
<h1> "hello world!" </h1>
</div>
})
};
// #[test]
#[derive(PartialEq, Clone)]
struct MyStruct {
a: String,
}
fn check_before_to_owned() {
let new_str = MyStruct {
a: "asd".to_string(),
};
let out = town(&new_str);
}
fn town<T: ToOwned + PartialEq>(t: &T) -> T::Owned {
t.to_owned()
}
-8
View File
@@ -1,8 +0,0 @@
use dioxus_core::prelude::*;
use dioxus_core_macro::rsx_template;
fn main() {
let g = html!("<div> </div>");
let g = html!("<div> </div>");
// let g = rsx!("div { div { } } ");
}
-16
View File
@@ -1,16 +0,0 @@
use dioxus_core::prelude::*;
use dioxus_core_macro::format_args_f;
fn main() {
let num = 123;
let b = Bump::new();
let g = rsx! {
div {
"abc {num}"
div {
"asd"
}
}
};
}
-28
View File
@@ -1,28 +0,0 @@
use dioxus::virtual_dom::VirtualDom;
use dioxus_core::prelude::*;
fn main() {
let mut dom = VirtualDom::new(App);
let edits = dom.rebuild().unwrap();
dbg!(edits);
}
static App: FC<()> = |ctx| {
//
ctx.render(rsx! {
div {
"abc"
"123"
}
})
};
static Fragment: FC<()> = |ctx| {
//
let children = ctx.children();
ctx.render(LazyNodes::new(move |c: &NodeCtx| {
//
let frag = c.bump().alloc(VFragment::new(None, children));
VNode::Fragment(frag)
}))
};