dom.rs 14 KB

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