dom.rs 15 KB

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