dom.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. //! Implementation of a renderer for Dioxus on the web.
  2. //!
  3. //! Oustanding todos:
  4. //! - Removing event listeners (delegation)
  5. //! - Passive event listeners
  6. //! - no-op event listener patch for safari
  7. //! - tests to ensure dyn_into works for various event types.
  8. //! - Partial delegation?>
  9. use dioxus_core::{
  10. BorrowedAttributeValue, ElementId, Mutation, Template, TemplateAttribute, TemplateNode,
  11. };
  12. use dioxus_html::{event_bubbles, CompositionData, FileEngine, FormData, MountedData};
  13. use dioxus_interpreter_js::{get_node, minimal_bindings, save_template, Channel};
  14. use futures_channel::mpsc;
  15. use js_sys::Array;
  16. use rustc_hash::FxHashMap;
  17. use std::{any::Any, rc::Rc, sync::Arc};
  18. use wasm_bindgen::{closure::Closure, prelude::wasm_bindgen, JsCast, JsValue};
  19. use web_sys::{Document, Element, Event};
  20. use crate::{file_engine::WebFileEngine, Config};
  21. pub struct WebsysDom {
  22. document: Document,
  23. #[allow(dead_code)]
  24. pub(crate) root: Element,
  25. templates: FxHashMap<String, u32>,
  26. max_template_id: u32,
  27. pub(crate) interpreter: Channel,
  28. event_channel: mpsc::UnboundedSender<UiEvent>,
  29. }
  30. pub struct UiEvent {
  31. pub name: String,
  32. pub bubbles: bool,
  33. pub element: ElementId,
  34. pub data: Rc<dyn Any>,
  35. }
  36. impl WebsysDom {
  37. pub fn new(cfg: Config, event_channel: mpsc::UnboundedSender<UiEvent>) -> Self {
  38. // eventually, we just want to let the interpreter do all the work of decoding events into our event type
  39. // a match here in order to avoid some error during runtime browser test
  40. let document = load_document();
  41. let root = match document.get_element_by_id(&cfg.rootname) {
  42. Some(root) => root,
  43. None => document.create_element("body").ok().unwrap(),
  44. };
  45. let interpreter = Channel::default();
  46. let handler: Closure<dyn FnMut(&Event)> = Closure::wrap(Box::new({
  47. let event_channel = event_channel.clone();
  48. move |event: &web_sys::Event| {
  49. let name = event.type_();
  50. let element = walk_event_for_id(event);
  51. let bubbles = dioxus_html::event_bubbles(name.as_str());
  52. if let Some((element, target)) = element {
  53. if let Some(prevent_requests) = target
  54. .get_attribute("dioxus-prevent-default")
  55. .as_deref()
  56. .map(|f| f.split_whitespace())
  57. {
  58. if prevent_requests
  59. .map(|f| f.trim_start_matches("on"))
  60. .any(|f| f == name)
  61. {
  62. event.prevent_default();
  63. }
  64. }
  65. let data = virtual_event_from_websys_event(event.clone(), target);
  66. let _ = event_channel.unbounded_send(UiEvent {
  67. name,
  68. bubbles,
  69. element,
  70. data,
  71. });
  72. }
  73. }
  74. }));
  75. dioxus_interpreter_js::initilize(
  76. root.clone().unchecked_into(),
  77. handler.as_ref().unchecked_ref(),
  78. );
  79. handler.forget();
  80. Self {
  81. document,
  82. root,
  83. interpreter,
  84. templates: FxHashMap::default(),
  85. max_template_id: 0,
  86. event_channel,
  87. }
  88. }
  89. pub fn mount(&mut self) {
  90. self.interpreter.mount_to_root();
  91. }
  92. pub fn load_templates(&mut self, templates: &[Template]) {
  93. for template in templates {
  94. let mut roots = vec![];
  95. for root in template.roots {
  96. roots.push(self.create_template_node(root))
  97. }
  98. self.templates
  99. .insert(template.name.to_owned(), self.max_template_id);
  100. save_template(roots, self.max_template_id);
  101. self.max_template_id += 1
  102. }
  103. }
  104. fn create_template_node(&self, v: &TemplateNode) -> web_sys::Node {
  105. use TemplateNode::*;
  106. match v {
  107. Element {
  108. tag,
  109. namespace,
  110. attrs,
  111. children,
  112. ..
  113. } => {
  114. let el = match namespace {
  115. Some(ns) => self.document.create_element_ns(Some(ns), tag).unwrap(),
  116. None => self.document.create_element(tag).unwrap(),
  117. };
  118. for attr in *attrs {
  119. if let TemplateAttribute::Static {
  120. name,
  121. value,
  122. namespace,
  123. } = attr
  124. {
  125. minimal_bindings::setAttributeInner(
  126. el.clone().into(),
  127. name,
  128. JsValue::from_str(value),
  129. *namespace,
  130. );
  131. }
  132. }
  133. for child in *children {
  134. let _ = el.append_child(&self.create_template_node(child));
  135. }
  136. el.dyn_into().unwrap()
  137. }
  138. Text { text } => self.document.create_text_node(text).dyn_into().unwrap(),
  139. DynamicText { .. } => self.document.create_text_node("p").dyn_into().unwrap(),
  140. Dynamic { .. } => {
  141. let el = self.document.create_element("pre").unwrap();
  142. let _ = el.toggle_attribute("hidden");
  143. el.dyn_into().unwrap()
  144. }
  145. }
  146. }
  147. pub fn apply_edits(&mut self, mut edits: Vec<Mutation>) {
  148. use Mutation::*;
  149. let i = &mut self.interpreter;
  150. // we need to apply the mount events last, so we collect them here
  151. let mut to_mount = Vec::new();
  152. for edit in &edits {
  153. match edit {
  154. AppendChildren { id, m } => i.append_children(id.0 as u32, *m as u32),
  155. AssignId { path, id } => {
  156. i.assign_id(path.as_ptr() as u32, path.len() as u8, id.0 as u32)
  157. }
  158. CreatePlaceholder { id } => i.create_placeholder(id.0 as u32),
  159. CreateTextNode { value, id } => i.create_text_node(value, id.0 as u32),
  160. HydrateText { path, value, id } => {
  161. i.hydrate_text(path.as_ptr() as u32, path.len() as u8, value, id.0 as u32)
  162. }
  163. LoadTemplate { name, index, id } => {
  164. if let Some(tmpl_id) = self.templates.get(*name) {
  165. i.load_template(*tmpl_id, *index as u32, id.0 as u32)
  166. }
  167. }
  168. ReplaceWith { id, m } => i.replace_with(id.0 as u32, *m as u32),
  169. ReplacePlaceholder { path, m } => {
  170. i.replace_placeholder(path.as_ptr() as u32, path.len() as u8, *m as u32)
  171. }
  172. InsertAfter { id, m } => i.insert_after(id.0 as u32, *m as u32),
  173. InsertBefore { id, m } => i.insert_before(id.0 as u32, *m as u32),
  174. SetAttribute {
  175. name,
  176. value,
  177. id,
  178. ns,
  179. } => match value {
  180. BorrowedAttributeValue::Text(txt) => {
  181. i.set_attribute(id.0 as u32, name, txt, ns.unwrap_or_default())
  182. }
  183. BorrowedAttributeValue::Float(f) => {
  184. i.set_attribute(id.0 as u32, name, &f.to_string(), ns.unwrap_or_default())
  185. }
  186. BorrowedAttributeValue::Int(n) => {
  187. i.set_attribute(id.0 as u32, name, &n.to_string(), ns.unwrap_or_default())
  188. }
  189. BorrowedAttributeValue::Bool(b) => i.set_attribute(
  190. id.0 as u32,
  191. name,
  192. if *b { "true" } else { "false" },
  193. ns.unwrap_or_default(),
  194. ),
  195. BorrowedAttributeValue::None => {
  196. i.remove_attribute(id.0 as u32, name, ns.unwrap_or_default())
  197. }
  198. _ => unreachable!(),
  199. },
  200. SetText { value, id } => i.set_text(id.0 as u32, value),
  201. NewEventListener { name, id, .. } => {
  202. match *name {
  203. // mounted events are fired immediately after the element is mounted.
  204. "mounted" => {
  205. to_mount.push(*id);
  206. }
  207. _ => {
  208. i.new_event_listener(name, id.0 as u32, event_bubbles(name) as u8);
  209. }
  210. }
  211. }
  212. RemoveEventListener { name, id } => match *name {
  213. "mounted" => {}
  214. _ => {
  215. i.remove_event_listener(name, id.0 as u32, event_bubbles(name) as u8);
  216. }
  217. },
  218. Remove { id } => i.remove(id.0 as u32),
  219. PushRoot { id } => i.push_root(id.0 as u32),
  220. }
  221. }
  222. edits.clear();
  223. i.flush();
  224. for id in to_mount {
  225. let node = get_node(id.0 as u32);
  226. if let Some(element) = node.dyn_ref::<Element>() {
  227. log::info!("mounted event fired: {}", id.0);
  228. let data: MountedData = element.into();
  229. let data = Rc::new(data);
  230. let _ = self.event_channel.unbounded_send(UiEvent {
  231. name: "mounted".to_string(),
  232. bubbles: false,
  233. element: id,
  234. data,
  235. });
  236. }
  237. }
  238. }
  239. }
  240. // todo: some of these events are being casted to the wrong event type.
  241. // We need tests that simulate clicks/etc and make sure every event type works.
  242. pub fn virtual_event_from_websys_event(event: web_sys::Event, target: Element) -> Rc<dyn Any> {
  243. use dioxus_html::events::*;
  244. match event.type_().as_str() {
  245. "copy" | "cut" | "paste" => Rc::new(ClipboardData {}),
  246. "compositionend" | "compositionstart" | "compositionupdate" => {
  247. make_composition_event(&event)
  248. }
  249. "keydown" | "keypress" | "keyup" => Rc::new(KeyboardData::from(event)),
  250. "focus" | "blur" | "focusout" | "focusin" => Rc::new(FocusData {}),
  251. "change" | "input" | "invalid" | "reset" | "submit" => read_input_to_data(target),
  252. "click" | "contextmenu" | "dblclick" | "doubleclick" | "mousedown" | "mouseenter"
  253. | "mouseleave" | "mousemove" | "mouseout" | "mouseover" | "mouseup" => {
  254. Rc::new(MouseData::from(event))
  255. }
  256. "drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart"
  257. | "drop" => {
  258. let mouse = MouseData::from(event);
  259. Rc::new(DragData { mouse })
  260. }
  261. "pointerdown" | "pointermove" | "pointerup" | "pointercancel" | "gotpointercapture"
  262. | "lostpointercapture" | "pointerenter" | "pointerleave" | "pointerover" | "pointerout" => {
  263. Rc::new(PointerData::from(event))
  264. }
  265. "select" => Rc::new(SelectionData {}),
  266. "touchcancel" | "touchend" | "touchmove" | "touchstart" => Rc::new(TouchData::from(event)),
  267. "scroll" => Rc::new(()),
  268. "wheel" => Rc::new(WheelData::from(event)),
  269. "animationstart" | "animationend" | "animationiteration" => {
  270. Rc::new(AnimationData::from(event))
  271. }
  272. "transitionend" => Rc::new(TransitionData::from(event)),
  273. "abort" | "canplay" | "canplaythrough" | "durationchange" | "emptied" | "encrypted"
  274. | "ended" | "loadeddata" | "loadedmetadata" | "loadstart" | "pause" | "play"
  275. | "playing" | "progress" | "ratechange" | "seeked" | "seeking" | "stalled" | "suspend"
  276. | "timeupdate" | "volumechange" | "waiting" => Rc::new(MediaData {}),
  277. "error" => Rc::new(ImageData { load_error: true }),
  278. "load" => Rc::new(ImageData { load_error: false }),
  279. "toggle" => Rc::new(ToggleData {}),
  280. _ => Rc::new(()),
  281. }
  282. }
  283. fn make_composition_event(event: &Event) -> Rc<CompositionData> {
  284. let evt: &web_sys::CompositionEvent = event.dyn_ref().unwrap();
  285. Rc::new(CompositionData {
  286. data: evt.data().unwrap_or_default(),
  287. })
  288. }
  289. pub(crate) fn load_document() -> Document {
  290. web_sys::window()
  291. .expect("should have access to the Window")
  292. .document()
  293. .expect("should have access to the Document")
  294. }
  295. fn read_input_to_data(target: Element) -> Rc<FormData> {
  296. // todo: these handlers might get really slow if the input box gets large and allocation pressure is heavy
  297. // don't have a good solution with the serialized event problem
  298. let value: String = target
  299. .dyn_ref()
  300. .map(|input: &web_sys::HtmlInputElement| {
  301. // todo: special case more input types
  302. match input.type_().as_str() {
  303. "checkbox" => {
  304. match input.checked() {
  305. true => "true".to_string(),
  306. false => "false".to_string(),
  307. }
  308. },
  309. _ => {
  310. input.value()
  311. }
  312. }
  313. })
  314. .or_else(|| {
  315. target
  316. .dyn_ref()
  317. .map(|input: &web_sys::HtmlTextAreaElement| input.value())
  318. })
  319. // select elements are NOT input events - because - why woudn't they be??
  320. .or_else(|| {
  321. target
  322. .dyn_ref()
  323. .map(|input: &web_sys::HtmlSelectElement| input.value())
  324. })
  325. .or_else(|| {
  326. target
  327. .dyn_ref::<web_sys::HtmlElement>()
  328. .unwrap()
  329. .text_content()
  330. })
  331. .expect("only an InputElement or TextAreaElement or an element with contenteditable=true can have an oninput event listener");
  332. let mut values = std::collections::HashMap::new();
  333. // try to fill in form values
  334. if let Some(form) = target.dyn_ref::<web_sys::HtmlFormElement>() {
  335. let form_data = get_form_data(form);
  336. for value in form_data.entries().into_iter().flatten() {
  337. if let Ok(array) = value.dyn_into::<Array>() {
  338. if let Some(name) = array.get(0).as_string() {
  339. if let Ok(item_values) = array.get(1).dyn_into::<Array>() {
  340. let item_values =
  341. item_values.iter().filter_map(|v| v.as_string()).collect();
  342. values.insert(name, item_values);
  343. }
  344. }
  345. }
  346. }
  347. }
  348. let files = target
  349. .dyn_ref()
  350. .and_then(|input: &web_sys::HtmlInputElement| {
  351. input.files().and_then(|files| {
  352. WebFileEngine::new(files).map(|f| Arc::new(f) as Arc<dyn FileEngine>)
  353. })
  354. });
  355. Rc::new(FormData {
  356. value,
  357. values,
  358. files,
  359. })
  360. }
  361. // web-sys does not expose the keys api for form data, so we need to manually bind to it
  362. #[wasm_bindgen(inline_js = r#"
  363. export function get_form_data(form) {
  364. let values = new Map();
  365. const formData = new FormData(form);
  366. for (let name of formData.keys()) {
  367. values.set(name, formData.getAll(name));
  368. }
  369. return values;
  370. }
  371. "#)]
  372. extern "C" {
  373. fn get_form_data(form: &web_sys::HtmlFormElement) -> js_sys::Map;
  374. }
  375. fn walk_event_for_id(event: &web_sys::Event) -> Option<(ElementId, web_sys::Element)> {
  376. let target = event
  377. .target()
  378. .expect("missing target")
  379. .dyn_into::<web_sys::Node>()
  380. .expect("not a valid node");
  381. let mut current_target_element = target.dyn_ref::<web_sys::Element>().cloned();
  382. loop {
  383. match (
  384. current_target_element
  385. .as_ref()
  386. .and_then(|el| el.get_attribute("data-dioxus-id").map(|f| f.parse())),
  387. current_target_element,
  388. ) {
  389. // This node is an element, and has a dioxus id, so we can stop walking
  390. (Some(Ok(id)), Some(target)) => return Some((ElementId(id), target)),
  391. // Walk the tree upwards until we actually find an event target
  392. (None, target_element) => {
  393. let parent = match target_element.as_ref() {
  394. Some(el) => el.parent_element(),
  395. // if this is the first node and not an element, we need to get the parent from the target node
  396. None => target.parent_element(),
  397. };
  398. match parent {
  399. Some(parent) => current_target_element = Some(parent),
  400. _ => return None,
  401. }
  402. }
  403. // This node is an element with an invalid dioxus id, give up
  404. _ => return None,
  405. }
  406. }
  407. }