dom.rs 17 KB

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