feat: add prevent default attribute and upgrade router
This commit is contained in:
1 parent
cb2782b4bb
commit
427b126bc1
16 files changed
+220
-181
No files matched your search
@@ -27,7 +27,7 @@ Head over to [https://rust-lang.org](http://rust-lang.org) and install the Rust
|
|||||||
Once installed, make sure to install wasm32-unknown-unknown as a target if you're planning on deploying your app to the web.
|
Once installed, make sure to install wasm32-unknown-unknown as a target if you're planning on deploying your app to the web.
|
||||||
|
|
||||||
```
|
```
|
||||||
rustup target add wasm32-unknown-uknown
|
rustup target add wasm32-unknown-unknown
|
||||||
```
|
```
|
||||||
|
|
||||||
### Dioxus-CLI for dev server, bundling, etc.
|
### Dioxus-CLI for dev server, bundling, etc.
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ $ cargo install trunk
|
|||||||
|
|
||||||
Make sure the `wasm32-unknown-unknown` target is installed:
|
Make sure the `wasm32-unknown-unknown` target is installed:
|
||||||
```shell
|
```shell
|
||||||
$ rustup target add wasm32-unknown-uknown
|
$ rustup target add wasm32-unknown-unknown
|
||||||
```
|
```
|
||||||
|
|
||||||
Create a new project:
|
Create a new project:
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
use dioxus::prelude::*;
|
use dioxus::prelude::*;
|
||||||
|
use dioxus_desktop::tao::menu::MenuBar;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
dioxus::desktop::launch(app);
|
dioxus::desktop::launch_cfg(app, |c| c.with_window(|w| w.with_menu(MenuBar::default())));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn app(cx: Scope) -> Element {
|
fn app(cx: Scope) -> Element {
|
||||||
|
|||||||
@@ -191,6 +191,11 @@ impl Parse for ComponentField {
|
|||||||
return Ok(Self { name, content });
|
return Ok(Self { name, content });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if input.peek(LitStr) && input.peek2(LitStr) {
|
||||||
|
let item = input.parse::<LitStr>().unwrap();
|
||||||
|
proc_macro_error::emit_error!(item, "This attribute is misisng a trailing comma")
|
||||||
|
}
|
||||||
|
|
||||||
let content = ContentField::ManExpr(input.parse()?);
|
let content = ContentField::ManExpr(input.parse()?);
|
||||||
Ok(Self { name, content })
|
Ok(Self { name, content })
|
||||||
}
|
}
|
||||||
|
|||||||
+32
-19
@@ -263,7 +263,7 @@ impl<'bump> DiffState<'bump> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if deadline_expired() {
|
if deadline_expired() {
|
||||||
log::debug!("Deadline expired before we could finish!");
|
log::trace!("Deadline expired before we could finish!");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -423,16 +423,25 @@ impl<'bump> DiffState<'bump> {
|
|||||||
fn create_component_node(&mut self, vcomponent: &'bump VComponent<'bump>) {
|
fn create_component_node(&mut self, vcomponent: &'bump VComponent<'bump>) {
|
||||||
let parent_idx = self.stack.current_scope().unwrap();
|
let parent_idx = self.stack.current_scope().unwrap();
|
||||||
|
|
||||||
// Insert a new scope into our component list
|
// the component might already exist - if it does, we need to reuse it
|
||||||
let props: Box<dyn AnyProps + 'bump> = vcomponent.props.borrow_mut().take().unwrap();
|
// this makes figure out when to drop the component more complicated
|
||||||
let props: Box<dyn AnyProps + 'static> = unsafe { std::mem::transmute(props) };
|
let new_idx = if let Some(idx) = vcomponent.scope.get() {
|
||||||
let new_idx = self.scopes.new_with_key(
|
assert!(self.scopes.get_scope(idx).is_some());
|
||||||
vcomponent.user_fc,
|
idx
|
||||||
props,
|
} else {
|
||||||
Some(parent_idx),
|
// Insert a new scope into our component list
|
||||||
self.stack.element_stack.last().copied().unwrap(),
|
let props: Box<dyn AnyProps + 'bump> = vcomponent.props.borrow_mut().take().unwrap();
|
||||||
0,
|
let props: Box<dyn AnyProps + 'static> = unsafe { std::mem::transmute(props) };
|
||||||
);
|
let new_idx = self.scopes.new_with_key(
|
||||||
|
vcomponent.user_fc,
|
||||||
|
props,
|
||||||
|
Some(parent_idx),
|
||||||
|
self.stack.element_stack.last().copied().unwrap(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
new_idx
|
||||||
|
};
|
||||||
|
|
||||||
// Actually initialize the caller's slot with the right address
|
// Actually initialize the caller's slot with the right address
|
||||||
vcomponent.scope.set(Some(new_idx));
|
vcomponent.scope.set(Some(new_idx));
|
||||||
@@ -443,9 +452,6 @@ impl<'bump> DiffState<'bump> {
|
|||||||
}
|
}
|
||||||
false => {
|
false => {
|
||||||
// track this component internally so we know the right drop order
|
// track this component internally so we know the right drop order
|
||||||
// let cur_scope = self.scopes.get_scope(parent_idx).unwrap();
|
|
||||||
// let extended = unsafe { std::mem::transmute(vcomponent) };
|
|
||||||
// cur_scope.items.borrow_mut().borrowed_props.push(extended);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -680,10 +686,10 @@ impl<'bump> DiffState<'bump> {
|
|||||||
new: &'bump VComponent<'bump>,
|
new: &'bump VComponent<'bump>,
|
||||||
) {
|
) {
|
||||||
let scope_addr = old.scope.get().unwrap();
|
let scope_addr = old.scope.get().unwrap();
|
||||||
log::debug!("diff_component_nodes: {:?}", scope_addr);
|
log::trace!("diff_component_nodes: {:?}", scope_addr);
|
||||||
|
|
||||||
if std::ptr::eq(old, new) {
|
if std::ptr::eq(old, new) {
|
||||||
log::debug!("skipping component diff - component is the sames");
|
log::trace!("skipping component diff - component is the sames");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -734,7 +740,7 @@ impl<'bump> DiffState<'bump> {
|
|||||||
self.scopes.fin_head(scope_addr),
|
self.scopes.fin_head(scope_addr),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
log::debug!("memoized");
|
log::trace!("memoized");
|
||||||
// memoization has taken place
|
// memoization has taken place
|
||||||
drop(new_props);
|
drop(new_props);
|
||||||
};
|
};
|
||||||
@@ -1239,7 +1245,10 @@ impl<'bump> DiffState<'bump> {
|
|||||||
|
|
||||||
let scope_id = c.scope.get().unwrap();
|
let scope_id = c.scope.get().unwrap();
|
||||||
|
|
||||||
self.scopes.try_remove(scope_id).unwrap();
|
// we can only remove components if they are actively being diffed
|
||||||
|
if self.stack.scope_stack.contains(&c.originator) {
|
||||||
|
self.scopes.try_remove(scope_id).unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1290,7 +1299,11 @@ impl<'bump> DiffState<'bump> {
|
|||||||
let scope_id = c.scope.get().unwrap();
|
let scope_id = c.scope.get().unwrap();
|
||||||
let root = self.scopes.root_node(scope_id);
|
let root = self.scopes.root_node(scope_id);
|
||||||
self.remove_nodes(Some(root), gen_muts);
|
self.remove_nodes(Some(root), gen_muts);
|
||||||
self.scopes.try_remove(scope_id).unwrap();
|
|
||||||
|
// we can only remove this node if the originator is actively
|
||||||
|
if self.stack.scope_stack.contains(&c.originator) {
|
||||||
|
self.scopes.try_remove(scope_id).unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,10 +60,7 @@ impl<'a, 'b> LazyNodes<'a, 'b> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new<F>(_val: F) -> Self
|
pub fn new(_val: impl FnOnce(NodeFactory<'a>) -> VNode<'a> + 'b) -> Self {
|
||||||
where
|
|
||||||
F: FnOnce(NodeFactory<'a>) -> VNode<'a> + 'b,
|
|
||||||
{
|
|
||||||
// there's no way to call FnOnce without a box, so we need to store it in a slot and use static dispatch
|
// there's no way to call FnOnce without a box, so we need to store it in a slot and use static dispatch
|
||||||
let mut slot = Some(_val);
|
let mut slot = Some(_val);
|
||||||
|
|
||||||
@@ -240,57 +237,77 @@ fn round_to_words(len: usize) -> usize {
|
|||||||
(len + mem::size_of::<usize>() - 1) / mem::size_of::<usize>()
|
(len + mem::size_of::<usize>() - 1) / mem::size_of::<usize>()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[cfg(test)]
|
||||||
fn it_works() {
|
mod tests {
|
||||||
let bump = bumpalo::Bump::new();
|
use super::*;
|
||||||
|
use crate::innerlude::{Element, Scope, VirtualDom};
|
||||||
|
|
||||||
// let factory = NodeFactory { bump: &bump };
|
#[test]
|
||||||
|
fn it_works() {
|
||||||
|
fn app(cx: Scope<()>) -> Element {
|
||||||
|
cx.render(LazyNodes::new_some(|f| {
|
||||||
|
f.text(format_args!("hello world!"))
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
// let caller = LazyNodes::new_some(|f| {
|
let mut dom = VirtualDom::new(app);
|
||||||
// //
|
dom.rebuild();
|
||||||
// f.text(format_args!("hello world!"))
|
|
||||||
// });
|
|
||||||
// let g = caller.call(factory);
|
|
||||||
|
|
||||||
// dbg!(g);
|
let g = dom.base_scope().root_node();
|
||||||
}
|
dbg!(g);
|
||||||
|
}
|
||||||
#[test]
|
|
||||||
fn it_drops() {
|
#[test]
|
||||||
use std::rc::Rc;
|
fn it_drops() {
|
||||||
let bump = bumpalo::Bump::new();
|
use std::rc::Rc;
|
||||||
|
|
||||||
// let factory = NodeFactory { bump: &bump };
|
struct AppProps {
|
||||||
|
inner: Rc<i32>,
|
||||||
// struct DropInner {
|
}
|
||||||
// id: i32,
|
|
||||||
// }
|
fn app(cx: Scope<AppProps>) -> Element {
|
||||||
// impl Drop for DropInner {
|
struct DropInner {
|
||||||
// fn drop(&mut self) {
|
id: i32,
|
||||||
// log::debug!("dropping inner");
|
}
|
||||||
// }
|
impl Drop for DropInner {
|
||||||
// }
|
fn drop(&mut self) {
|
||||||
// let val = Rc::new(10);
|
log::debug!("dropping inner");
|
||||||
|
}
|
||||||
// let caller = {
|
}
|
||||||
// let it = (0..10)
|
|
||||||
// .map(|i| {
|
let caller = {
|
||||||
// let val = val.clone();
|
let it = (0..10)
|
||||||
|
.map(|i| {
|
||||||
// LazyNodes::new_some(move |f| {
|
let val = cx.props.inner.clone();
|
||||||
// log::debug!("hell closure");
|
|
||||||
// let inner = DropInner { id: i };
|
LazyNodes::new_some(move |f| {
|
||||||
// f.text(format_args!("hello world {:?}, {:?}", inner.id, val))
|
log::debug!("hell closure");
|
||||||
// })
|
let inner = DropInner { id: i };
|
||||||
// })
|
f.text(format_args!("hello world {:?}, {:?}", inner.id, val))
|
||||||
// .collect::<Vec<_>>();
|
})
|
||||||
|
})
|
||||||
// LazyNodes::new_some(|f| {
|
.collect::<Vec<_>>();
|
||||||
// log::debug!("main closure");
|
|
||||||
// f.fragment_from_iter(it)
|
LazyNodes::new_some(|f| {
|
||||||
// })
|
log::debug!("main closure");
|
||||||
// };
|
f.fragment_from_iter(it)
|
||||||
|
})
|
||||||
// let _ = caller.call(factory);
|
};
|
||||||
// assert_eq!(Rc::strong_count(&val), 1);
|
|
||||||
|
cx.render(caller)
|
||||||
|
}
|
||||||
|
|
||||||
|
let inner = Rc::new(0);
|
||||||
|
let mut dom = VirtualDom::new_with_props(
|
||||||
|
app,
|
||||||
|
AppProps {
|
||||||
|
inner: inner.clone(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
dom.rebuild();
|
||||||
|
|
||||||
|
drop(dom);
|
||||||
|
|
||||||
|
assert_eq!(Rc::strong_count(&inner), 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -350,6 +350,7 @@ impl Clone for EventHandler<'_> {
|
|||||||
/// Only supports the functional syntax
|
/// Only supports the functional syntax
|
||||||
pub struct VComponent<'src> {
|
pub struct VComponent<'src> {
|
||||||
pub key: Option<&'src str>,
|
pub key: Option<&'src str>,
|
||||||
|
pub originator: ScopeId,
|
||||||
pub scope: Cell<Option<ScopeId>>,
|
pub scope: Cell<Option<ScopeId>>,
|
||||||
pub can_memoize: bool,
|
pub can_memoize: bool,
|
||||||
pub user_fc: *const (),
|
pub user_fc: *const (),
|
||||||
@@ -526,6 +527,7 @@ impl<'a> NodeFactory<'a> {
|
|||||||
scope: Default::default(),
|
scope: Default::default(),
|
||||||
can_memoize: P::IS_STATIC,
|
can_memoize: P::IS_STATIC,
|
||||||
user_fc: component as *const (),
|
user_fc: component as *const (),
|
||||||
|
originator: self.scope.scope_id(),
|
||||||
props: RefCell::new(Some(Box::new(VComponentProps {
|
props: RefCell::new(Some(Box::new(VComponentProps {
|
||||||
// local_props: RefCell::new(Some(props)),
|
// local_props: RefCell::new(Some(props)),
|
||||||
// heap_props: RefCell::new(None),
|
// heap_props: RefCell::new(None),
|
||||||
@@ -749,19 +751,14 @@ impl IntoVNode<'_> for Arguments<'_> {
|
|||||||
impl<'a> IntoVNode<'a> for &Option<VNode<'a>> {
|
impl<'a> IntoVNode<'a> for &Option<VNode<'a>> {
|
||||||
fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
|
fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
|
||||||
self.as_ref()
|
self.as_ref()
|
||||||
.map(|f| f.decouple())
|
.map(|f| f.into_vnode(cx))
|
||||||
.unwrap_or(VNode::Placeholder(
|
.unwrap_or_else(|| cx.fragment_from_iter(None as Option<VNode>))
|
||||||
cx.bump.alloc(VPlaceholder { id: empty_cell() }),
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> IntoVNode<'a> for &VNode<'a> {
|
impl<'a> IntoVNode<'a> for &VNode<'a> {
|
||||||
fn into_vnode(self, _cx: NodeFactory<'a>) -> VNode<'a> {
|
fn into_vnode(self, _cx: NodeFactory<'a>) -> VNode<'a> {
|
||||||
|
// borrowed nodes are strange
|
||||||
self.decouple()
|
self.decouple()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
trait IntoAcceptedVnode<'a> {
|
|
||||||
fn into_accepted_vnode(self, cx: NodeFactory<'a>) -> VNode<'a>;
|
|
||||||
}
|
|
||||||
@@ -143,7 +143,7 @@ impl ScopeArena {
|
|||||||
|
|
||||||
// Removes a scope and its descendents from the arena
|
// Removes a scope and its descendents from the arena
|
||||||
pub fn try_remove(&self, id: ScopeId) -> Option<()> {
|
pub fn try_remove(&self, id: ScopeId) -> Option<()> {
|
||||||
log::debug!("removing scope {:?}", id);
|
log::trace!("removing scope {:?}", id);
|
||||||
self.ensure_drop_safety(id);
|
self.ensure_drop_safety(id);
|
||||||
|
|
||||||
// Safety:
|
// Safety:
|
||||||
@@ -189,7 +189,7 @@ impl ScopeArena {
|
|||||||
/// This also makes sure that drop order is consistent and predictable. All resources that rely on being dropped will
|
/// This also makes sure that drop order is consistent and predictable. All resources that rely on being dropped will
|
||||||
/// be dropped.
|
/// be dropped.
|
||||||
pub(crate) fn ensure_drop_safety(&self, scope_id: ScopeId) {
|
pub(crate) fn ensure_drop_safety(&self, scope_id: ScopeId) {
|
||||||
log::debug!("Ensuring drop safety for scope {:?}", scope_id);
|
log::trace!("Ensuring drop safety for scope {:?}", scope_id);
|
||||||
|
|
||||||
if let Some(scope) = self.get_scope(scope_id) {
|
if let Some(scope) = self.get_scope(scope_id) {
|
||||||
let mut items = scope.items.borrow_mut();
|
let mut items = scope.items.borrow_mut();
|
||||||
@@ -220,7 +220,7 @@ impl ScopeArena {
|
|||||||
// Cycle to the next frame and then reset it
|
// Cycle to the next frame and then reset it
|
||||||
// This breaks any latent references, invalidating every pointer referencing into it.
|
// This breaks any latent references, invalidating every pointer referencing into it.
|
||||||
// Remove all the outdated listeners
|
// Remove all the outdated listeners
|
||||||
log::debug!("Running scope {:?}", id);
|
log::trace!("Running scope {:?}", id);
|
||||||
self.ensure_drop_safety(id);
|
self.ensure_drop_safety(id);
|
||||||
|
|
||||||
// todo: we *know* that this is aliased by the contents of the scope itself
|
// todo: we *know* that this is aliased by the contents of the scope itself
|
||||||
@@ -282,18 +282,18 @@ impl ScopeArena {
|
|||||||
let nodes = self.nodes.borrow();
|
let nodes = self.nodes.borrow();
|
||||||
let mut cur_el = Some(element);
|
let mut cur_el = Some(element);
|
||||||
|
|
||||||
log::debug!("calling listener {:?}, {:?}", event, element);
|
log::trace!("calling listener {:?}, {:?}", event, element);
|
||||||
let state = Rc::new(BubbleState::new());
|
let state = Rc::new(BubbleState::new());
|
||||||
|
|
||||||
while let Some(id) = cur_el.take() {
|
while let Some(id) = cur_el.take() {
|
||||||
if let Some(el) = nodes.get(id.0) {
|
if let Some(el) = nodes.get(id.0) {
|
||||||
log::debug!("Found valid receiver element");
|
log::trace!("Found valid receiver element");
|
||||||
|
|
||||||
let real_el = unsafe { &**el };
|
let real_el = unsafe { &**el };
|
||||||
if let VNode::Element(real_el) = real_el {
|
if let VNode::Element(real_el) = real_el {
|
||||||
for listener in real_el.listeners.borrow().iter() {
|
for listener in real_el.listeners.borrow().iter() {
|
||||||
if listener.event == event.name {
|
if listener.event == event.name {
|
||||||
log::debug!("Found valid receiver event");
|
log::trace!("Found valid receiver event");
|
||||||
|
|
||||||
if state.canceled.get() {
|
if state.canceled.get() {
|
||||||
// stop bubbling if canceled
|
// stop bubbling if canceled
|
||||||
@@ -912,7 +912,7 @@ impl TaskQueue {
|
|||||||
} else {
|
} else {
|
||||||
// todo: it should be okay to remote a fut while the queue is being polled
|
// todo: it should be okay to remote a fut while the queue is being polled
|
||||||
// However, it's not currently possible to do that.
|
// However, it's not currently possible to do that.
|
||||||
log::debug!("Unable to remove task from task queue. This is probably a bug.");
|
log::trace!("Unable to remove task from task queue. This is probably a bug.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub(crate) fn has_tasks(&self) -> bool {
|
pub(crate) fn has_tasks(&self) -> bool {
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
function serialize_event(event) {
|
function serialize_event(event) {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "copy":
|
case "copy":
|
||||||
@@ -10,8 +9,8 @@ function serialize_event(event) {
|
|||||||
case "compositionstart":
|
case "compositionstart":
|
||||||
case "compositionupdate":
|
case "compositionupdate":
|
||||||
return {
|
return {
|
||||||
data: event.data
|
data: event.data,
|
||||||
}
|
};
|
||||||
|
|
||||||
case "keydown":
|
case "keydown":
|
||||||
case "keypress":
|
case "keypress":
|
||||||
@@ -29,7 +28,7 @@ function serialize_event(event) {
|
|||||||
repeat: event.repeat,
|
repeat: event.repeat,
|
||||||
which: event.which,
|
which: event.which,
|
||||||
// locale: event.locale,
|
// locale: event.locale,
|
||||||
}
|
};
|
||||||
|
|
||||||
case "focus":
|
case "focus":
|
||||||
case "blur":
|
case "blur":
|
||||||
@@ -45,7 +44,7 @@ function serialize_event(event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
value: value
|
value: value,
|
||||||
};
|
};
|
||||||
|
|
||||||
case "input":
|
case "input":
|
||||||
@@ -60,7 +59,7 @@ function serialize_event(event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
value: value
|
value: value,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,7 +94,7 @@ function serialize_event(event) {
|
|||||||
screen_x: event.screenX,
|
screen_x: event.screenX,
|
||||||
screen_y: event.screenY,
|
screen_y: event.screenY,
|
||||||
shift_key: event.shiftKey,
|
shift_key: event.shiftKey,
|
||||||
}
|
};
|
||||||
|
|
||||||
case "pointerdown":
|
case "pointerdown":
|
||||||
case "pointermove":
|
case "pointermove":
|
||||||
@@ -130,7 +129,7 @@ function serialize_event(event) {
|
|||||||
twist: event.twist,
|
twist: event.twist,
|
||||||
pointer_type: event.pointerType,
|
pointer_type: event.pointerType,
|
||||||
is_primary: event.isPrimary,
|
is_primary: event.isPrimary,
|
||||||
}
|
};
|
||||||
|
|
||||||
case "select":
|
case "select":
|
||||||
return {};
|
return {};
|
||||||
@@ -148,7 +147,7 @@ function serialize_event(event) {
|
|||||||
// changed_touches: event.changedTouches,
|
// changed_touches: event.changedTouches,
|
||||||
// target_touches: event.targetTouches,
|
// target_touches: event.targetTouches,
|
||||||
// touches: event.touches,
|
// touches: event.touches,
|
||||||
}
|
};
|
||||||
|
|
||||||
case "scroll":
|
case "scroll":
|
||||||
return {};
|
return {};
|
||||||
@@ -208,17 +207,14 @@ function serialize_event(event) {
|
|||||||
default:
|
default:
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class Interpreter {
|
class Interpreter {
|
||||||
constructor(root) {
|
constructor(root) {
|
||||||
this.root = root;
|
this.root = root;
|
||||||
this.stack = [root];
|
this.stack = [root];
|
||||||
this.listeners = {
|
this.listeners = {
|
||||||
"onclick": {}
|
onclick: {},
|
||||||
};
|
};
|
||||||
this.lastNodeWasText = false;
|
this.lastNodeWasText = false;
|
||||||
this.nodes = [root];
|
this.nodes = [root];
|
||||||
@@ -304,35 +300,45 @@ class Interpreter {
|
|||||||
this.nodes[edit.root] = el;
|
this.nodes[edit.root] = el;
|
||||||
}
|
}
|
||||||
|
|
||||||
RemoveEventListener(edit) { }
|
RemoveEventListener(edit) {}
|
||||||
|
|
||||||
NewEventListener(edit) {
|
NewEventListener(edit) {
|
||||||
const event_name = edit.event_name;
|
const event_name = edit.event_name;
|
||||||
const mounted_node_id = edit.root;
|
const mounted_node_id = edit.root;
|
||||||
const scope = edit.scope;
|
const scope = edit.scope;
|
||||||
|
|
||||||
const element = this.nodes[edit.root]
|
const element = this.nodes[edit.root];
|
||||||
element.setAttribute(`dioxus-event-${event_name}`, `${scope}.${mounted_node_id}`);
|
element.setAttribute(
|
||||||
|
`dioxus-event-${event_name}`,
|
||||||
|
`${scope}.${mounted_node_id}`
|
||||||
|
);
|
||||||
|
|
||||||
if (this.listeners[event_name] === undefined) {
|
if (this.listeners[event_name] === undefined) {
|
||||||
this.listeners[event_name] = true;
|
this.listeners[event_name] = true;
|
||||||
|
|
||||||
this.root.addEventListener(event_name, (event) => {
|
this.root.addEventListener(event_name, (event) => {
|
||||||
console.log("handling event", event);
|
|
||||||
|
|
||||||
const target = event.target;
|
const target = event.target;
|
||||||
const real_id = target.getAttribute(`dioxus-id`);
|
const real_id = target.getAttribute(`dioxus-id`);
|
||||||
|
|
||||||
|
const should_prevent_default = target.getAttribute(
|
||||||
|
`dioxus-prevent-default`
|
||||||
|
);
|
||||||
|
|
||||||
|
let contents = serialize_event(event);
|
||||||
|
|
||||||
|
if (should_prevent_default === `on${event.type}`) {
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
|
||||||
if (real_id == null) {
|
if (real_id == null) {
|
||||||
alert("no id");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
rpc.call('user_event', {
|
rpc.call("user_event", {
|
||||||
event: event_name,
|
event: event_name,
|
||||||
mounted_dom_id: parseInt(real_id),
|
mounted_dom_id: parseInt(real_id),
|
||||||
contents: serialize_event(event),
|
contents: contents,
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -346,11 +352,11 @@ class Interpreter {
|
|||||||
const name = edit.field;
|
const name = edit.field;
|
||||||
const value = edit.value;
|
const value = edit.value;
|
||||||
const ns = edit.ns;
|
const ns = edit.ns;
|
||||||
const node = this.nodes[edit.root]
|
const node = this.nodes[edit.root];
|
||||||
|
|
||||||
if (ns == "style") {
|
if (ns == "style") {
|
||||||
node.style[name] = value;
|
node.style[name] = value;
|
||||||
} else if ((ns != null) || (ns != undefined)) {
|
} else if (ns != null || ns != undefined) {
|
||||||
node.setAttributeNS(ns, name, value);
|
node.setAttributeNS(ns, name, value);
|
||||||
} else {
|
} else {
|
||||||
switch (name) {
|
switch (name) {
|
||||||
@@ -358,17 +364,15 @@ class Interpreter {
|
|||||||
node.value = value;
|
node.value = value;
|
||||||
break;
|
break;
|
||||||
case "checked":
|
case "checked":
|
||||||
// console.log("setting checked");
|
node.checked = value === "true";
|
||||||
node.checked = (value === "true");
|
|
||||||
break;
|
break;
|
||||||
case "selected":
|
case "selected":
|
||||||
node.selected = (value === "true");
|
node.selected = value === "true";
|
||||||
break;
|
break;
|
||||||
case "dangerous_inner_html":
|
case "dangerous_inner_html":
|
||||||
node.innerHTML = value;
|
node.innerHTML = value;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
// console.log("setting attr directly ", name, value);
|
|
||||||
node.setAttribute(name, value);
|
node.setAttribute(name, value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -390,11 +394,6 @@ class Interpreter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleEdits(edits) {
|
handleEdits(edits) {
|
||||||
|
|
||||||
// console.log("handling raw edits", rawedits);
|
|
||||||
// let edits = JSON.parse(rawedits);
|
|
||||||
// console.log("handling edits", edits);
|
|
||||||
|
|
||||||
this.stack.push(this.root);
|
this.stack.push(this.root);
|
||||||
|
|
||||||
for (let x = 0; x < edits.length; x++) {
|
for (let x = 0; x < edits.length; x++) {
|
||||||
@@ -410,7 +409,7 @@ function main() {
|
|||||||
window.interpreter = new Interpreter(root);
|
window.interpreter = new Interpreter(root);
|
||||||
console.log(window.interpreter);
|
console.log(window.interpreter);
|
||||||
|
|
||||||
rpc.call('initialize');
|
rpc.call("initialize");
|
||||||
}
|
}
|
||||||
|
|
||||||
main()
|
main();
|
||||||
@@ -279,37 +279,7 @@ impl DesktopController {
|
|||||||
cfg: &DesktopConfig,
|
cfg: &DesktopConfig,
|
||||||
event_loop: &EventLoopWindowTarget<UserWindowEvent>,
|
event_loop: &EventLoopWindowTarget<UserWindowEvent>,
|
||||||
) {
|
) {
|
||||||
let builder = cfg.window.clone().with_menu({
|
let builder = cfg.window.clone();
|
||||||
// create main menubar menu
|
|
||||||
let mut menu_bar_menu = MenuBar::new();
|
|
||||||
|
|
||||||
// create `first_menu`
|
|
||||||
let mut first_menu = MenuBar::new();
|
|
||||||
|
|
||||||
first_menu.add_native_item(MenuItem::About("App".to_string()));
|
|
||||||
first_menu.add_native_item(MenuItem::Services);
|
|
||||||
first_menu.add_native_item(MenuItem::Separator);
|
|
||||||
first_menu.add_native_item(MenuItem::Hide);
|
|
||||||
first_menu.add_native_item(MenuItem::HideOthers);
|
|
||||||
first_menu.add_native_item(MenuItem::ShowAll);
|
|
||||||
|
|
||||||
first_menu.add_native_item(MenuItem::Quit);
|
|
||||||
first_menu.add_native_item(MenuItem::CloseWindow);
|
|
||||||
|
|
||||||
// create second menu
|
|
||||||
let mut second_menu = MenuBar::new();
|
|
||||||
|
|
||||||
// second_menu.add_submenu("Sub menu", true, my_sub_menu);
|
|
||||||
second_menu.add_native_item(MenuItem::Copy);
|
|
||||||
second_menu.add_native_item(MenuItem::Paste);
|
|
||||||
second_menu.add_native_item(MenuItem::SelectAll);
|
|
||||||
|
|
||||||
menu_bar_menu.add_submenu("First menu", true, first_menu);
|
|
||||||
menu_bar_menu.add_submenu("Second menu", true, second_menu);
|
|
||||||
|
|
||||||
menu_bar_menu
|
|
||||||
});
|
|
||||||
|
|
||||||
let window = builder.build(event_loop).unwrap();
|
let window = builder.build(event_loop).unwrap();
|
||||||
let window_id = window.id();
|
let window_id = window.id();
|
||||||
|
|
||||||
|
|||||||
Whitespace-only changes.
@@ -37,10 +37,8 @@ pub struct LinkProps<'a> {
|
|||||||
attributes: Option<&'a [Attribute<'a>]>,
|
attributes: Option<&'a [Attribute<'a>]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn Link<'a>(cx: Scope<'a, LinkProps<'a>>) -> Element {
|
pub fn Link<'a>(cx: Scope<'a, LinkProps<'a>>) -> Element {
|
||||||
log::debug!("rendering link {:?}", cx.scope_id());
|
let service = cx.consume_context::<RouterService>().unwrap();
|
||||||
let service = cx.consume_context::<RouterService>()?;
|
|
||||||
cx.render(rsx! {
|
cx.render(rsx! {
|
||||||
a {
|
a {
|
||||||
href: "{cx.props.to}",
|
href: "{cx.props.to}",
|
||||||
@@ -48,10 +46,7 @@ pub fn Link<'a>(cx: Scope<'a, LinkProps<'a>>) -> Element {
|
|||||||
id: format_args!("{}", cx.props.id.unwrap_or("")),
|
id: format_args!("{}", cx.props.id.unwrap_or("")),
|
||||||
|
|
||||||
prevent_default: "onclick",
|
prevent_default: "onclick",
|
||||||
onclick: move |_| {
|
onclick: move |_| service.push_route(cx.props.to.clone()),
|
||||||
log::debug!("clicked");
|
|
||||||
service.push_route(cx.props.to.clone());
|
|
||||||
},
|
|
||||||
|
|
||||||
&cx.props.children
|
&cx.props.children
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,11 @@ use crate::{RouteContext, RouterService};
|
|||||||
#[derive(Props)]
|
#[derive(Props)]
|
||||||
pub struct RouteProps<'a> {
|
pub struct RouteProps<'a> {
|
||||||
to: &'a str,
|
to: &'a str,
|
||||||
|
|
||||||
children: Element<'a>,
|
children: Element<'a>,
|
||||||
|
|
||||||
|
#[props(default)]
|
||||||
|
fallback: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn Route<'a>(cx: Scope<'a, RouteProps<'a>>) -> Element {
|
pub fn Route<'a>(cx: Scope<'a, RouteProps<'a>>) -> Element {
|
||||||
@@ -34,15 +38,18 @@ pub fn Route<'a>(cx: Scope<'a, RouteProps<'a>>) -> Element {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// submit our rout
|
// submit our rout
|
||||||
router_root.register_total_route(route_context.total_route.clone(), cx.scope_id());
|
router_root.register_total_route(
|
||||||
|
route_context.total_route.clone(),
|
||||||
|
cx.scope_id(),
|
||||||
|
cx.props.fallback,
|
||||||
|
);
|
||||||
|
|
||||||
Some(RouteInner {})
|
Some(RouteInner {})
|
||||||
});
|
});
|
||||||
|
|
||||||
log::debug!("rendering route {:?}", cx.scope_id());
|
log::debug!("Checking route {}", cx.props.to);
|
||||||
|
|
||||||
if router_root.should_render(cx.scope_id()) {
|
if router_root.should_render(cx.scope_id()) {
|
||||||
log::debug!("route {:?} produced nodes", cx.scope_id());
|
|
||||||
cx.render(rsx!(&cx.props.children))
|
cx.render(rsx!(&cx.props.children))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
|
|||||||
@@ -15,14 +15,13 @@ pub struct RouterProps<'a> {
|
|||||||
onchange: Option<&'a Fn(&'a str)>,
|
onchange: Option<&'a Fn(&'a str)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
pub fn Router<'a>(cx: Scope<'a, RouterProps<'a>>) -> Element {
|
pub fn Router<'a>(cx: Scope<'a, RouterProps<'a>>) -> Element {
|
||||||
let p = cx.use_hook(|_| {
|
cx.use_hook(|_| {
|
||||||
let update = cx.schedule_update_any();
|
let update = cx.schedule_update_any();
|
||||||
cx.provide_context(RouterService::new(update, cx.scope_id()))
|
cx.provide_context(RouterService::new(update, cx.scope_id()))
|
||||||
});
|
});
|
||||||
|
|
||||||
log::debug!("rendering router {:?}", cx.scope_id());
|
|
||||||
|
|
||||||
cx.render(rsx!(
|
cx.render(rsx!(
|
||||||
div { &cx.props.children }
|
div { &cx.props.children }
|
||||||
))
|
))
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ mod hooks {
|
|||||||
pub use hooks::*;
|
pub use hooks::*;
|
||||||
|
|
||||||
mod components {
|
mod components {
|
||||||
|
#![allow(non_snake_case)]
|
||||||
|
|
||||||
mod router;
|
mod router;
|
||||||
pub use router::*;
|
pub use router::*;
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
use gloo::history::{BrowserHistory, History, HistoryListener};
|
use gloo::history::{BrowserHistory, History, HistoryListener};
|
||||||
use std::{cell::RefCell, collections::HashMap, rc::Rc};
|
use std::{
|
||||||
|
cell::{Cell, RefCell},
|
||||||
|
collections::HashMap,
|
||||||
|
rc::Rc,
|
||||||
|
};
|
||||||
|
|
||||||
use dioxus_core::ScopeId;
|
use dioxus_core::ScopeId;
|
||||||
|
|
||||||
pub struct RouterService {
|
pub struct RouterService {
|
||||||
pub(crate) regen_route: Rc<dyn Fn(ScopeId)>,
|
pub(crate) regen_route: Rc<dyn Fn(ScopeId)>,
|
||||||
history: RefCell<BrowserHistory>,
|
history: Rc<RefCell<BrowserHistory>>,
|
||||||
registerd_routes: RefCell<RouteSlot>,
|
registerd_routes: RefCell<RouteSlot>,
|
||||||
slots: RefCell<HashMap<ScopeId, String>>,
|
slots: Rc<RefCell<Vec<(ScopeId, String)>>>,
|
||||||
|
root_found: Rc<Cell<bool>>,
|
||||||
cur_root: RefCell<String>,
|
cur_root: RefCell<String>,
|
||||||
listener: HistoryListener,
|
listener: HistoryListener,
|
||||||
}
|
}
|
||||||
@@ -31,9 +36,20 @@ impl RouterService {
|
|||||||
let location = history.location();
|
let location = history.location();
|
||||||
let path = location.path();
|
let path = location.path();
|
||||||
|
|
||||||
let regen = Rc::clone(®en_route);
|
let slots: Rc<RefCell<Vec<(ScopeId, String)>>> = Default::default();
|
||||||
|
|
||||||
|
let _slots = slots.clone();
|
||||||
|
|
||||||
|
let root_found = Rc::new(Cell::new(false));
|
||||||
|
let regen = regen_route.clone();
|
||||||
|
let _root_found = root_found.clone();
|
||||||
let listener = history.listen(move || {
|
let listener = history.listen(move || {
|
||||||
regen(root_scope);
|
_root_found.set(false);
|
||||||
|
// checking if the route is valid is cheap, so we do it
|
||||||
|
for (slot, _) in _slots.borrow_mut().iter().rev() {
|
||||||
|
log::debug!("regenerating slot {:?}", slot);
|
||||||
|
regen(*slot);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
@@ -42,9 +58,10 @@ impl RouterService {
|
|||||||
total: String::from("/"),
|
total: String::from("/"),
|
||||||
rest: Vec::new(),
|
rest: Vec::new(),
|
||||||
}),
|
}),
|
||||||
history: RefCell::new(history),
|
root_found,
|
||||||
|
history: Rc::new(RefCell::new(history)),
|
||||||
regen_route,
|
regen_route,
|
||||||
slots: Default::default(),
|
slots,
|
||||||
cur_root: RefCell::new(path.to_string()),
|
cur_root: RefCell::new(path.to_string()),
|
||||||
listener,
|
listener,
|
||||||
}
|
}
|
||||||
@@ -54,20 +71,37 @@ impl RouterService {
|
|||||||
self.history.borrow_mut().push(route);
|
self.history.borrow_mut().push(route);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn register_total_route(&self, route: String, scope: ScopeId) {
|
pub fn register_total_route(&self, route: String, scope: ScopeId, fallback: bool) {
|
||||||
self.slots.borrow_mut().insert(scope, route);
|
self.slots.borrow_mut().push((scope, route));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn should_render(&self, scope: ScopeId) -> bool {
|
pub fn should_render(&self, scope: ScopeId) -> bool {
|
||||||
|
if self.root_found.get() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
let location = self.history.borrow().location();
|
let location = self.history.borrow().location();
|
||||||
let path = location.path();
|
let path = location.path();
|
||||||
|
|
||||||
let roots = self.slots.borrow();
|
let roots = self.slots.borrow();
|
||||||
|
|
||||||
let root = roots.get(&scope);
|
let root = roots.iter().find(|(id, route)| id == &scope);
|
||||||
|
|
||||||
|
// fallback logic
|
||||||
match root {
|
match root {
|
||||||
Some(r) => r == path,
|
Some((_id, route)) => {
|
||||||
|
if route == path {
|
||||||
|
self.root_found.set(true);
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
if route == "" {
|
||||||
|
self.root_found.set(true);
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
None => false,
|
None => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user