feat: remove dioxus id on non-event elements

This commit is contained in:
Jonathan Kelley 2022-01-21 15:06:57 -05:00
parent 997684a390
commit 95e93ed0bc
7 changed files with 888 additions and 903 deletions

View file

@ -0,0 +1,33 @@
//! Nested Listeners
//!
//! This example showcases how to control event bubbling from child to parents.
//!
//! Both web and desktop support bubbling and bubble cancelation.
use dioxus::prelude::*;
fn main() {
dioxus::desktop::launch(app);
}
fn app(cx: Scope) -> Element {
cx.render(rsx! {
div {
onclick: move |_| println!("clicked! top"),
button {
onclick: move |_| println!("clicked! bottom propoate"),
"Propogate"
}
button {
onclick: move |evt| {
println!("clicked! bottom no bubbling");
evt.cancel_bubble();
},
"Dont propogate"
}
button {
"Does not handle clicks"
}
}
})
}

View file

@ -13,8 +13,10 @@
</div>
</body>
<script>var exports = {};</script>
<script type="text/javascript" src="index.js" type="module"></script>
<script>main()</script>
<script>
import("./index.js").then(function (module) {
module.main();
});
</script>
</html>

View file

@ -205,7 +205,7 @@ pub fn launch_with_props<P: 'static + Send>(
}
None
})
.with_custom_protocol("dioxus".into(), move |request| {
.with_custom_protocol(String::from("dioxus"), move |request| {
// Any content that that uses the `dioxus://` scheme will be shuttled through this handler as a "special case"
// For now, we only serve two pieces of content which get included as bytes into the final binary.
let path = request.uri().replace("dioxus://", "");
@ -225,10 +225,10 @@ pub fn launch_with_props<P: 'static + Send>(
}
})
.with_file_drop_handler(move |window, evet| {
if let Some(handler) = file_handler.as_ref() {
return handler(window, evet);
}
false
file_handler
.as_ref()
.map(|handler| handler(window, evet))
.unwrap_or_default()
});
for (name, handler) in cfg.protocos.drain(..) {

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,319 @@
export function main() {
let root = window.document.getElementById("main");
if (root != null) {
window.interpreter = new Interpreter(root);
window.rpc.call("initialize");
}
}
declare global {
interface Window {
interpreter: Interpreter;
rpc: { call: (method: string, args?: any) => void };
}
}
export class Interpreter {
root: Element;
stack: Element[];
listeners: { [key: string]: number };
handlers: { [key: string]: (evt: Event) => void };
lastNodeWasText: boolean;
nodes: Element[];
constructor(root: Element) {
this.root = root;
this.stack = [root];
this.listeners = {};
this.handlers = {};
this.lastNodeWasText = false;
this.nodes = [root];
}
top() {
return this.stack[this.stack.length - 1];
}
pop() {
return this.stack.pop();
}
PushRoot(root: number) {
const node = this.nodes[root];
this.stack.push(node);
}
AppendChildren(many: number) {
let root = this.stack[this.stack.length - (1 + many)];
let to_add = this.stack.splice(this.stack.length - many);
for (let i = 0; i < many; i++) {
root.appendChild(to_add[i]);
}
}
ReplaceWith(root_id: number, m: number) {
let root = this.nodes[root_id] as Element;
let els = this.stack.splice(this.stack.length - m);
root.replaceWith(...els);
}
InsertAfter(root: number, n: number) {
let old = this.nodes[root] as Element;
let new_nodes = this.stack.splice(this.stack.length - n);
old.after(...new_nodes);
}
InsertBefore(root: number, n: number) {
let old = this.nodes[root] as Element;
let new_nodes = this.stack.splice(this.stack.length - n);
old.before(...new_nodes);
}
Remove(root: number) {
let node = this.nodes[root] as Element;
if (node !== undefined) {
node.remove();
}
}
CreateTextNode(text: string, root: number) {
// todo: make it so the types are okay
const node = document.createTextNode(text) as any as Element;
this.nodes[root] = node;
this.stack.push(node);
}
CreateElement(tag: string, root: number) {
const el = document.createElement(tag);
// el.setAttribute("data-dioxus-id", `${root}`);
this.nodes[root] = el;
this.stack.push(el);
}
CreateElementNs(tag: string, root: number, ns: string) {
let el = document.createElementNS(ns, tag);
this.stack.push(el);
this.nodes[root] = el;
}
CreatePlaceholder(root: number) {
let el = document.createElement("pre");
el.hidden = true;
this.stack.push(el);
this.nodes[root] = el;
}
NewEventListener(event_name: string, root: number, handler: (evt: Event) => void) {
const element = this.nodes[root];
element.setAttribute("data-dioxus-id", `${root}`);
if (this.listeners[event_name] === undefined) {
this.listeners[event_name] = 0;
this.handlers[event_name] = handler;
this.root.addEventListener(event_name, handler);
} else {
this.listeners[event_name]++;
}
}
RemoveEventListener(root: number, event_name: string) {
const element = this.nodes[root];
element.removeAttribute(`data-dioxus-id`);
this.listeners[event_name]--;
if (this.listeners[event_name] === 0) {
this.root.removeEventListener(event_name, this.handlers[event_name]);
delete this.listeners[event_name];
delete this.handlers[event_name];
}
}
SetText(root: number, text: string) {
this.nodes[root].textContent = text;
}
SetAttribute(root: number, field: string, value: string, ns: string | undefined) {
const name = field;
const node = this.nodes[root];
if (ns == "style") {
// @ts-ignore
(node as HTMLElement).style[name] = value;
} else if (ns != null || ns != undefined) {
node.setAttributeNS(ns, name, value);
} else {
switch (name) {
case "value":
if (value != (node as HTMLInputElement).value) {
(node as HTMLInputElement).value = value;
}
break;
case "checked":
(node as HTMLInputElement).checked = value === "true";
break;
case "selected":
(node as HTMLOptionElement).selected = value === "true";
break;
case "dangerous_inner_html":
node.innerHTML = value;
break;
default:
// https://github.com/facebook/react/blob/8b88ac2592c5f555f315f9440cbb665dd1e7457a/packages/react-dom/src/shared/DOMProperty.js#L352-L364
if (value == "false" && bool_attrs.hasOwnProperty(name)) {
node.removeAttribute(name);
} else {
node.setAttribute(name, value);
}
}
}
}
RemoveAttribute(root: number, name: string) {
const node = this.nodes[root];
node.removeAttribute(name);
if (name === "value") {
(node as HTMLInputElement).value = "";
}
if (name === "checked") {
(node as HTMLInputElement).checked = false;
}
if (name === "selected") {
(node as HTMLOptionElement).selected = false;
}
}
handleEdits(edits: DomEdit[]) {
this.stack.push(this.root);
for (let edit of edits) {
this.handleEdit(edit);
}
}
handleEdit(edit: DomEdit) {
switch (edit.type) {
case "PushRoot":
this.PushRoot(edit.root);
break;
case "AppendChildren":
this.AppendChildren(edit.many);
break;
case "ReplaceWith":
this.ReplaceWith(edit.root, edit.m);
break;
case "InsertAfter":
this.InsertAfter(edit.root, edit.n);
break;
case "InsertBefore":
this.InsertBefore(edit.root, edit.n);
break;
case "Remove":
this.Remove(edit.root);
break;
case "CreateTextNode":
this.CreateTextNode(edit.text, edit.root);
break;
case "CreateElement":
this.CreateElement(edit.tag, edit.root);
break;
case "CreateElementNs":
this.CreateElementNs(edit.tag, edit.root, edit.ns);
break;
case "CreatePlaceholder":
this.CreatePlaceholder(edit.root);
break;
case "RemoveEventListener":
this.RemoveEventListener(edit.root, edit.event_name);
break;
case "NewEventListener":
// this handler is only provided on desktop implementations since this
// method is not used by the web implementation
let handler = (event: Event) => {
let target = event.target as Element | null;
if (target != null) {
let realId = target.getAttribute(`data-dioxus-id`);
// walk the tree to find the real element
while (realId == null && target.parentElement != null) {
target = target.parentElement;
realId = target.getAttribute(`data-dioxus-id`);
}
const shouldPreventDefault = target.getAttribute(`dioxus-prevent-default`);
let contents = serialize_event(event);
if (shouldPreventDefault === `on${event.type}`) {
event.preventDefault();
}
if (event.type == "submit") {
event.preventDefault();
}
if (event.type == "click") {
event.preventDefault();
if (shouldPreventDefault !== `onclick`) {
if (target.tagName == "A") {
const href = target.getAttribute("href")
if (href !== "" && href !== null && href !== undefined && realId != null) {
window.rpc.call("browser_open", {
mounted_dom_id: parseInt(realId),
href
});
}
}
}
}
if (realId == null) {
return;
}
window.rpc.call("user_event", {
event: (edit as NewEventListener).event_name,
mounted_dom_id: parseInt(realId),
contents: contents,
});
}
};
this.NewEventListener(edit.event_name, edit.root, handler);
break;
case "SetText":
this.SetText(edit.root, edit.text);
break;
case "SetAttribute":
this.SetAttribute(edit.root, edit.field, edit.value, edit.ns);
break;
case "RemoveAttribute":
this.RemoveAttribute(edit.root, edit.name);
break;
}
}
}
function serialize_event(event: Event) {
switch (event.type) {
case "copy":
@ -327,307 +643,6 @@ const bool_attrs = {
truespeed: true,
};
export class Interpreter {
root: Element;
stack: Element[];
listeners: { [key: string]: number };
handlers: { [key: string]: (evt: Event) => void };
lastNodeWasText: boolean;
nodes: Element[];
constructor(root: Element) {
this.root = root;
this.stack = [root];
this.listeners = {};
this.handlers = {};
this.lastNodeWasText = false;
this.nodes = [root];
}
top() {
return this.stack[this.stack.length - 1];
}
pop() {
return this.stack.pop();
}
PushRoot(root: number) {
const node = this.nodes[root];
this.stack.push(node);
}
AppendChildren(many: number) {
let root = this.stack[this.stack.length - (1 + many)];
let to_add = this.stack.splice(this.stack.length - many);
for (let i = 0; i < many; i++) {
root.appendChild(to_add[i]);
}
}
ReplaceWith(root_id: number, m: number) {
let root = this.nodes[root_id] as Element;
let els = this.stack.splice(this.stack.length - m);
root.replaceWith(...els);
}
InsertAfter(root: number, n: number) {
let old = this.nodes[root] as Element;
let new_nodes = this.stack.splice(this.stack.length - n);
old.after(...new_nodes);
}
InsertBefore(root: number, n: number) {
let old = this.nodes[root] as Element;
let new_nodes = this.stack.splice(this.stack.length - n);
old.before(...new_nodes);
}
Remove(root: number) {
let node = this.nodes[root] as Element;
if (node !== undefined) {
node.remove();
}
}
CreateTextNode(text: string, root: number) {
// todo: make it so the types are okay
const node = document.createTextNode(text) as any as Element;
this.nodes[root] = node;
this.stack.push(node);
}
CreateElement(tag: string, root: number) {
const el = document.createElement(tag);
el.setAttribute("dioxus-id", `${root}`);
this.nodes[root] = el;
this.stack.push(el);
}
CreateElementNs(tag: string, root: number, ns: string) {
let el = document.createElementNS(ns, tag);
this.stack.push(el);
this.nodes[root] = el;
}
CreatePlaceholder(root: number) {
let el = document.createElement("pre");
el.hidden = true;
this.stack.push(el);
this.nodes[root] = el;
}
NewEventListener(event_name: string, scope: number, root: number, handler: (evt: Event) => void) {
// console.log('new event listener', event_name, root, scope);
const element = this.nodes[root];
element.setAttribute(
`dioxus-event-${event_name}`,
`${scope}.${root}`
);
if (this.listeners[event_name] === undefined) {
this.listeners[event_name] = 0;
this.handlers[event_name] = handler;
this.root.addEventListener(event_name, handler);
} else {
this.listeners[event_name]++;
}
}
RemoveEventListener(root: number, event_name: string) {
const element = this.nodes[root];
element.removeAttribute(
`dioxus-event-${event_name}`
);
this.listeners[event_name]--;
if (this.listeners[event_name] === 0) {
this.root.removeEventListener(event_name, this.handlers[event_name]);
delete this.listeners[event_name];
delete this.handlers[event_name];
}
}
SetText(root: number, text: string) {
this.nodes[root].textContent = text;
}
SetAttribute(root: number, field: string, value: string, ns: string | undefined) {
const name = field;
const node = this.nodes[root];
if (ns == "style") {
// @ts-ignore
(node as HTMLElement).style[name] = value;
} else if (ns != null || ns != undefined) {
node.setAttributeNS(ns, name, value);
} else {
switch (name) {
case "value":
if (value != (node as HTMLInputElement).value) {
(node as HTMLInputElement).value = value;
}
break;
case "checked":
(node as HTMLInputElement).checked = value === "true";
break;
case "selected":
(node as HTMLOptionElement).selected = value === "true";
break;
case "dangerous_inner_html":
node.innerHTML = value;
break;
default:
// https://github.com/facebook/react/blob/8b88ac2592c5f555f315f9440cbb665dd1e7457a/packages/react-dom/src/shared/DOMProperty.js#L352-L364
if (value == "false" && bool_attrs.hasOwnProperty(name)) {
node.removeAttribute(name);
} else {
node.setAttribute(name, value);
}
}
}
}
RemoveAttribute(root: number, name: string) {
const node = this.nodes[root];
node.removeAttribute(name);
if (name === "value") {
(node as HTMLInputElement).value = "";
}
if (name === "checked") {
(node as HTMLInputElement).checked = false;
}
if (name === "selected") {
(node as HTMLOptionElement).selected = false;
}
}
handleEdits(edits: DomEdit[]) {
this.stack.push(this.root);
for (let edit of edits) {
this.handleEdit(edit);
}
}
handleEdit(edit: DomEdit) {
switch (edit.type) {
case "PushRoot":
this.PushRoot(edit.root);
break;
case "AppendChildren":
this.AppendChildren(edit.many);
break;
case "ReplaceWith":
this.ReplaceWith(edit.root, edit.m);
break;
case "InsertAfter":
this.InsertAfter(edit.root, edit.n);
break;
case "InsertBefore":
this.InsertBefore(edit.root, edit.n);
break;
case "Remove":
this.Remove(edit.root);
break;
case "CreateTextNode":
this.CreateTextNode(edit.text, edit.root);
break;
case "CreateElement":
this.CreateElement(edit.tag, edit.root);
break;
case "CreateElementNs":
this.CreateElementNs(edit.tag, edit.root, edit.ns);
break;
case "CreatePlaceholder":
this.CreatePlaceholder(edit.root);
break;
case "RemoveEventListener":
this.RemoveEventListener(edit.root, edit.event_name);
break;
case "NewEventListener":
// this handler is only provided on desktop implementations since this
// method is not used by the web implementation
let handler = (event: Event) => {
const target = event.target as Element | null;
if (target != null) {
const realId = target.getAttribute(`dioxus-id`);
const shouldPreventDefault = target.getAttribute(`dioxus-prevent-default`);
let contents = serialize_event(event);
if (shouldPreventDefault === `on${event.type}`) {
event.preventDefault();
}
if (event.type == "submit") {
event.preventDefault();
}
if (event.type == "click") {
event.preventDefault();
if (shouldPreventDefault !== `onclick`) {
if (target.tagName == "A") {
const href = target.getAttribute("href")
if (href !== "" && href !== null && href !== undefined && realId != null) {
window.rpc.call("browser_open", {
mounted_dom_id: parseInt(realId),
href
});
}
}
}
}
if (realId == null) {
return;
}
window.rpc.call("user_event", {
event: (edit as NewEventListener).event_name,
mounted_dom_id: parseInt(realId),
contents: contents,
});
}
};
this.NewEventListener(edit.event_name, edit.scope, edit.root, handler);
break;
case "SetText":
this.SetText(edit.root, edit.text);
break;
case "SetAttribute":
this.SetAttribute(edit.root, edit.field, edit.value, edit.ns);
break;
case "RemoveAttribute":
this.RemoveAttribute(edit.root, edit.name);
break;
}
}
}
function main() {
let root = window.document.getElementById("main");
if (root != null) {
window.interpreter = new Interpreter(root);
window.rpc.call("initialize");
}
}
type PushRoot = { type: "PushRoot", root: number };
@ -663,14 +678,3 @@ type DomEdit =
SetText |
SetAttribute |
RemoveAttribute;
export { };
declare global {
interface Window {
interpreter: Interpreter;
rpc: { call: (method: string, args?: any) => void };
}
}

View file

@ -1,13 +1,13 @@
{
"compilerOptions": {
"target": "ES5",
"module": "ESNext",
"target": "ESNext",
"module": "ES2015",
"lib": [
"es2015",
"es5",
"es6",
"dom"
],
"strict": true
"strict": true,
}
}

View file

@ -277,9 +277,7 @@ fn virtual_event_from_websys_event(event: web_sys::Event) -> Arc<dyn Any + Send
/// This function decodes a websys event and produces an EventTrigger
/// With the websys implementation, we attach a unique key to the nodes
fn decode_trigger(event: &web_sys::Event) -> anyhow::Result<UserEvent> {
use anyhow::Context;
let target = event
let mut target = event
.target()
.expect("missing target")
.dyn_into::<Element>()
@ -287,18 +285,36 @@ fn decode_trigger(event: &web_sys::Event) -> anyhow::Result<UserEvent> {
let typ = event.type_();
let element_id = target
.get_attribute("dioxus-id")
.context("Could not find element id on event target")?
.parse()?;
Ok(UserEvent {
name: event_name_from_typ(&typ),
data: virtual_event_from_websys_event(event.clone()),
element: Some(ElementId(element_id)),
scope_id: None,
priority: dioxus_core::EventPriority::Medium,
})
loop {
match target.get_attribute("data-dioxus-id").map(|f| f.parse()) {
Some(Ok(id)) => {
return Ok(UserEvent {
name: event_name_from_typ(&typ),
data: virtual_event_from_websys_event(event.clone()),
element: Some(ElementId(id)),
scope_id: None,
priority: dioxus_core::EventPriority::Medium,
});
}
Some(Err(e)) => {
return Err(e.into());
}
None => {
// walk the tree upwards until we actually find an event target
if let Some(parent) = target.parent_element() {
target = parent;
} else {
return Ok(UserEvent {
name: event_name_from_typ(&typ),
data: virtual_event_from_websys_event(event.clone()),
element: None,
scope_id: None,
priority: dioxus_core::EventPriority::Low,
});
}
}
}
}
}
pub(crate) fn load_document() -> Document {