dom.rs 18 KB

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