Feat: more ergonomics, more examples

This commit is contained in:
Jonathan Kelley committed 2021-03-26 15:50:28 -04:00
1 parent 44aad2746c
commit 0bcff1f88e
15 files changed
+488 -469

No files matched your search

+14 -148
View File
@@ -7,6 +7,8 @@
fn main() {}
use std::borrow::Borrow;
use dioxus_core::prelude::*;
struct Props {
@@ -19,8 +21,8 @@ struct ListItem {
age: u32,
}
fn app(ctx: Context, props: &Props) -> DomTree {
let (_f, setter) = use_state(&ctx, || 0);
fn app<'a>(ctx: Context<'a>, props: &Props) -> DomTree {
let val = use_state(&ctx, || 0);
ctx.render(dioxus::prelude::LazyNodes::new(move |c| {
let mut root = builder::ElementBuilder::new(c, "div");
@@ -34,7 +36,7 @@ fn app(ctx: Context, props: &Props) -> DomTree {
// create the props with nothing but the fc<T>
fc_to_builder(ChildItem)
.item(child)
.item_handler(setter)
.item_handler(val.setter())
.build(),
));
}
@@ -42,15 +44,6 @@ fn app(ctx: Context, props: &Props) -> DomTree {
}))
}
type StateSetter<T> = dyn Fn(T);
// struct StateSetter<T>(dyn Fn(T));
// impl<T> PartialEq for StateSetter<T> {
// fn eq(&self, other: &Self) -> bool {
// self as *const _ == other as *const _
// }
// }
// props should derive a partialeq implementation automatically, but implement ptr compare for & fields
#[derive(Props)]
struct ChildProps<'a> {
@@ -58,153 +51,26 @@ struct ChildProps<'a> {
item: &'a ListItem,
// Even pass down handlers!
item_handler: &'a StateSetter<i32>,
item_handler: &'a dyn Fn(i32),
}
impl PartialEq for ChildProps<'_> {
fn eq(&self, _other: &Self) -> bool {
// assume the dyn fn is never stable -
// wrap with use_callback if it's an issue for you
false
}
}
fn ChildItem(_ctx: Context, _props: &ChildProps) -> DomTree {
todo!()
// ctx.render(rsx! {
// div {
// item: child,
// handler: setter,
// abc: 123,
// onclick: props.item_handler,
// h1 { "abcd123" }
// h2 { "abcd123" }
// div {
// "abcd123"
// h2 { }
// p { }
// },
// }
// })
}
/*
rsx! {
ChildItem {
// props
item: child, handler: setter,
// children
div { class:"abcd", abc: 123 },
div { class:"abcd", abc: 123 },
// Auto-text coercion
"eyo matie {abc}",
// Anything that accepts Into<VChild>
{},
}
}
// dreaming of this syntax
#[derive(Properties)]
struct ChildProps<'a> {
username: &'a str,
item_handler: &'a dyn Fn(i32),
}
fn child_item(ctx: Context, props: &ChildProps) -> DomTree {
fn ChildItem<'a>(ctx: Context<'a>, props: &ChildProps) -> DomTree {
ctx.render(rsx! {
div {
class: "abc123",
abc: 123,
onclick: props.item_handler,
h1 { "Hello, {props.username}!" },
h2 { "Welcome the RSX syntax" },
onclick: move |evt| (props.item_handler)(10)
h1 { "abcd123" }
h2 { "abcd123" }
div {
h3 { "This is a subheader" }
button {
onclick: props.handler,
"This is a button"
}
"This is child text"
},
"abcd123"
h2 { }
p { }
}
}
})
}
// This is also nice
#[dioxus::component]
static CHILD: FC = |ctx, username: &str, handler: &dyn Fn(i32)| {
ctx.render(rsx! {
div {
class: "abc123",
abc: 123,
onclick: handler,
h1 { "Hello, {username}!" },
h2 { "Welcome the RSX syntax" },
div {
h3 { "This is a subheader" }
button {
onclick: props.handler,
"This is a button"
}
"This is child text"
},
}
})
}
Menlo, Monaco, 'Courier New', monospace
struct Item {
name: String,
content: String,
}
#[dioxus::live_component]
static CHILD: FC = |ctx, username: &str, handler: &dyn Fn(i32)| {
// return lazy nodes or
let ssr = ctx.suspend(async {
let data = fetch("https://google.com")
.await?
.json::<Item>()
.await?;
rsx! {
div {
h1 { "Welcome: {data.name}" }
p { "Content: \n {data.content}" }
}
}
});
ctx.render(rsx! {
div {
class: "abc123",
abc: 123,
onclick: handler,
h1 { "Hello, {username}!" },
h2 { "Welcome the RSX syntax" },
div {
h3 { "This is a subheader" }
button {
onclick: props.handler,
"This is a button"
}
{ssr}
},
}
})
}
*/
+3 -3
View File
@@ -11,13 +11,13 @@ fn main() {
}
static Example: FC<()> = |ctx, props| {
let (name, set_name) = use_state(&ctx, || "...?");
let name = use_state(&ctx, || "...?");
ctx.render(html! {
<div>
<h1> "Hello, {name}" </h1>
<button onclick={move |_| set_name("jack")}> "jack!" </button>
<button onclick={move |_| set_name("jill")}> "jill!" </button>
<button onclick={move |_| name.set("jack")}> "jack!" </button>
<button onclick={move |_| name.set("jill")}> "jill!" </button>
</div>
})
};
+2 -2
View File
@@ -61,9 +61,9 @@ impl<'a> Context<'a> {
/// Create a suspended component from a future.
///
/// When the future completes, the component will be renderered
pub fn suspend(
pub fn suspend<F: for<'b> FnOnce(&'b NodeCtx<'a>) -> VNode<'a> + 'a>(
&self,
_fut: impl Future<Output = impl FnOnce(&'a NodeCtx<'a>) -> VNode<'a>>,
_fut: impl Future<Output = LazyNodes<'a, F>>,
) -> VNode<'a> {
todo!()
}
+27
View File
@@ -40,6 +40,33 @@ impl DebugRenderer {
pub fn step(&mut self, machine: &mut DiffMachine) -> Result<()> {
Ok(())
}
// this does a "holy" compare - if something is missing in the rhs, it doesn't complain.
// it only complains if something shows up that's not in the lhs, *or* if a value is different.
// This lets you exclude various fields if you just want to drill in to a specific prop
// It leverages the internal diffing mechanism.
// If you have a list or "nth" child, you do need to list those children, but you don't need to
// fill in their children/attrs/etc
// Does not handle children or lifecycles and will always fail the test if they show up in the rhs
pub fn compare<'a, F>(&self, other: LazyNodes<'a, F>) -> Result<()>
where
F: for<'b> FnOnce(&'b NodeCtx<'a>) -> VNode<'a> + 'a,
{
Ok(())
}
// Do a full compare - everything must match
// Ignores listeners and children components
pub fn compare_full<'a, F>(&self, other: LazyNodes<'a, F>) -> Result<()>
where
F: for<'b> FnOnce(&'b NodeCtx<'a>) -> VNode<'a> + 'a,
{
Ok(())
}
pub fn trigger_listener(&mut self, id: usize) -> Result<()> {
Ok(())
}
}
#[cfg(test)]
+43 -30
View File
@@ -5,6 +5,7 @@
//! - [ ] use_reducer
//! - [ ] use_effect
pub use use_reducer_def::use_reducer;
pub use use_ref_def::use_ref;
pub use use_state_def::use_state;
@@ -12,29 +13,52 @@ mod use_state_def {
use crate::innerlude::*;
use std::{
cell::RefCell,
fmt::Display,
ops::{Deref, DerefMut},
rc::Rc,
};
struct UseState<T: 'static> {
new_val: Rc<RefCell<Option<T>>>,
pub struct UseState<T: 'static> {
modifier: Rc<RefCell<Option<Box<dyn FnOnce(&mut T)>>>>,
current_val: T,
caller: Box<dyn Fn(T) + 'static>,
update: Box<dyn Fn() + 'static>,
}
struct UseStateHandle<'a, T> {
inner: &'a T,
}
impl<'a, T> UseStateHandle<'a, T> {
fn set(&self, new_val: T) {}
fn modify(&self, f: impl FnOnce(&mut T)) {}
}
// #[derive(Clone, Copy)]
// pub struct UseStateHandle<'a, T: 'static> {
// inner: &'a UseState<T>,
// // pub setter: &'a dyn Fn(T),
// // pub modifier: &'a dyn Fn(&mut T),
// }
impl<'a, T> Deref for UseStateHandle<'a, T> {
impl<'a, T: 'static> UseState<T> {
pub fn setter(&self) -> &dyn Fn(T) {
todo!()
}
pub fn set(&self, new_val: T) {
self.modify(|f| *f = new_val);
}
// signal that we need to be updated
// save the modifier
pub fn modify(&self, f: impl FnOnce(&mut T) + 'static) {
let mut slot = self.modifier.as_ref().borrow_mut();
*slot = Some(Box::new(f));
(self.update)();
}
}
impl<'a, T: 'static> std::ops::Deref for UseState<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.inner
&self.current_val
}
}
// enable displaty for the handle
impl<'a, T: 'static + Display> std::fmt::Display for UseState<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.current_val)
}
}
@@ -63,37 +87,26 @@ mod use_state_def {
pub fn use_state<'a, 'c, T: 'static, F: FnOnce() -> T>(
ctx: &'c Context<'a>,
initial_state_fn: F,
) -> (&'a T, &'a impl Fn(T)) {
) -> &'a UseState<T> {
ctx.use_hook(
move || UseState {
new_val: Rc::new(RefCell::new(None)),
modifier: Rc::new(RefCell::new(None)),
current_val: initial_state_fn(),
caller: Box::new(|_| println!("setter called!")),
update: Box::new(|| {}),
},
move |hook| {
log::debug!("Use_state set called");
let inner = hook.new_val.clone();
let scheduled_update = ctx.schedule_update();
// get ownership of the new val and replace the current with the new
// -> as_ref -> borrow_mut -> deref_mut -> take
// -> rc -> &RefCell -> RefMut -> &Option<T> -> T
if let Some(new_val) = hook.new_val.as_ref().borrow_mut().deref_mut().take() {
hook.current_val = new_val;
if let Some(new_val) = hook.modifier.as_ref().borrow_mut().deref_mut().take() {
(new_val)(&mut hook.current_val);
}
// todo: swap out the caller with a subscription call and an internal update
hook.caller = Box::new(move |new_val| {
// update the setter with the new value
let mut new_inner = inner.as_ref().borrow_mut();
*new_inner = Some(new_val);
hook.update = Box::new(move || scheduled_update());
// Ensure the component gets updated
scheduled_update();
});
// box gets derefed into a ref which is then taken as ref with the hook
(&hook.current_val, &hook.caller)
&*hook
},
|_| {},
)
+12 -1
View File
@@ -496,6 +496,17 @@ pub trait IntoDomTree<'a> {
fn into_vnode(self, ctx: &NodeCtx<'a>) -> VNode<'a>;
}
pub trait DomTreeBuilder<'a, G>: IntoIterator<Item = G>
where
G: IntoDomTree<'a>,
{
}
impl<'a, F> DomTreeBuilder<'a, LazyNodes<'a, F>> for LazyNodes<'a, F> where
F: for<'b> FnOnce(&'b NodeCtx<'a>) -> VNode<'a> + 'a
{
}
// Cover the cases where nodes are pre-rendered.
// Likely used by enums.
// ----
@@ -547,7 +558,7 @@ where
// Required because anything that enters brackets in the rsx! macro needs to implement IntoIterator
impl<'a, G> IntoIterator for LazyNodes<'a, G>
where
G: for<'b, 'c> FnOnce(&'b NodeCtx<'c>) -> VNode<'c> + 'a,
G: for<'b> FnOnce(&'b NodeCtx<'a>) -> VNode<'a> + 'a,
{
type Item = Self;
type IntoIter = std::iter::Once<Self::Item>;