slider.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. use std::collections::HashMap;
  2. use dioxus_html::{input_data::keyboard_types::Key, KeyboardData, MouseData};
  3. use dioxus_native_core::{
  4. custom_element::CustomElement,
  5. node::{OwnedAttributeDiscription, OwnedAttributeValue},
  6. node_ref::AttributeMask,
  7. prelude::{ElementNode, NodeType},
  8. real_dom::{ElementNodeMut, NodeImmutable, NodeMut, NodeTypeMut, RealDom},
  9. NodeId,
  10. };
  11. use shipyard::UniqueView;
  12. use super::{RinkWidget, WidgetContext};
  13. use crate::{query::get_layout, Event, EventData, FormData, Query};
  14. #[derive(Debug)]
  15. pub(crate) struct Slider {
  16. div_wrapper: NodeId,
  17. pre_cursor_div: NodeId,
  18. post_cursor_div: NodeId,
  19. min: f64,
  20. max: f64,
  21. step: Option<f64>,
  22. value: f64,
  23. border: bool,
  24. }
  25. impl Default for Slider {
  26. fn default() -> Self {
  27. Self {
  28. div_wrapper: Default::default(),
  29. pre_cursor_div: Default::default(),
  30. post_cursor_div: Default::default(),
  31. min: 0.0,
  32. max: 100.0,
  33. step: None,
  34. value: 0.0,
  35. border: false,
  36. }
  37. }
  38. }
  39. impl Slider {
  40. fn size(&self) -> f64 {
  41. self.max - self.min
  42. }
  43. fn step(&self) -> f64 {
  44. self.step.unwrap_or(self.size() / 10.0)
  45. }
  46. fn width(el: &ElementNodeMut) -> String {
  47. if let Some(value) = el
  48. .get_attribute(&OwnedAttributeDiscription {
  49. name: "width".to_string(),
  50. namespace: Some("style".to_string()),
  51. })
  52. .and_then(|value| value.as_text())
  53. .map(|value| value.to_string())
  54. {
  55. value
  56. } else {
  57. "1px".to_string()
  58. }
  59. }
  60. fn height(el: &ElementNodeMut) -> String {
  61. if let Some(value) = el
  62. .get_attribute(&OwnedAttributeDiscription {
  63. name: "height".to_string(),
  64. namespace: Some("style".to_string()),
  65. })
  66. .and_then(|value| value.as_text())
  67. .map(|value| value.to_string())
  68. {
  69. value
  70. } else {
  71. "1px".to_string()
  72. }
  73. }
  74. fn update_min_attr(&mut self, el: &ElementNodeMut) {
  75. if let Some(value) = el
  76. .get_attribute(&OwnedAttributeDiscription {
  77. name: "min".to_string(),
  78. namespace: None,
  79. })
  80. .and_then(|value| value.as_text())
  81. .map(|value| value.to_string())
  82. {
  83. self.min = value.parse().ok().unwrap_or(0.0);
  84. }
  85. }
  86. fn update_max_attr(&mut self, el: &ElementNodeMut) {
  87. if let Some(value) = el
  88. .get_attribute(&OwnedAttributeDiscription {
  89. name: "max".to_string(),
  90. namespace: None,
  91. })
  92. .and_then(|value| value.as_text())
  93. .map(|value| value.to_string())
  94. {
  95. self.max = value.parse().ok().unwrap_or(100.0);
  96. }
  97. }
  98. fn update_step_attr(&mut self, el: &ElementNodeMut) {
  99. if let Some(value) = el
  100. .get_attribute(&OwnedAttributeDiscription {
  101. name: "step".to_string(),
  102. namespace: None,
  103. })
  104. .and_then(|value| value.as_text())
  105. .map(|value| value.to_string())
  106. {
  107. self.step = value.parse().ok();
  108. }
  109. }
  110. fn update_size_attr(&mut self, el: &mut ElementNodeMut) {
  111. let width = Self::width(el);
  112. let height = Self::height(el);
  113. let single_char = width
  114. .strip_prefix("px")
  115. .and_then(|n| n.parse::<u32>().ok().filter(|num| *num > 3))
  116. .is_some()
  117. || height
  118. .strip_prefix("px")
  119. .and_then(|n| n.parse::<u32>().ok().filter(|num| *num > 3))
  120. .is_some();
  121. self.border = !single_char;
  122. let border_style = if self.border { "solid" } else { "none" };
  123. el.set_attribute(
  124. OwnedAttributeDiscription {
  125. name: "border-style".to_string(),
  126. namespace: Some("style".to_string()),
  127. },
  128. border_style.to_string(),
  129. );
  130. }
  131. fn update_value(&mut self, new: f64) {
  132. self.value = new.clamp(self.min, self.max);
  133. }
  134. fn update_value_attr(&mut self, el: &ElementNodeMut) {
  135. if let Some(value) = el
  136. .get_attribute(&OwnedAttributeDiscription {
  137. name: "value".to_string(),
  138. namespace: None,
  139. })
  140. .and_then(|value| value.as_text())
  141. .map(|value| value.to_string())
  142. {
  143. self.update_value(value.parse().ok().unwrap_or(0.0));
  144. }
  145. }
  146. fn write_value(&self, rdom: &mut RealDom, id: NodeId) {
  147. let value_percent = (self.value - self.min) / self.size() * 100.0;
  148. if let Some(mut div) = rdom.get_mut(self.pre_cursor_div) {
  149. let node_type = div.node_type_mut();
  150. let NodeTypeMut::Element(mut element) = node_type else { panic!("input must be an element") };
  151. element.set_attribute(
  152. OwnedAttributeDiscription {
  153. name: "width".to_string(),
  154. namespace: Some("style".to_string()),
  155. },
  156. format!("{}%", value_percent),
  157. );
  158. }
  159. if let Some(mut div) = rdom.get_mut(self.post_cursor_div) {
  160. let node_type = div.node_type_mut();
  161. let NodeTypeMut::Element(mut element) = node_type else { panic!("input must be an element") };
  162. element.set_attribute(
  163. OwnedAttributeDiscription {
  164. name: "width".to_string(),
  165. namespace: Some("style".to_string()),
  166. },
  167. format!("{}%", 100.0 - value_percent),
  168. );
  169. }
  170. // send the event
  171. let world = rdom.raw_world_mut();
  172. {
  173. let ctx: UniqueView<WidgetContext> = world.borrow().expect("expected widget context");
  174. let data = FormData {
  175. value: self.value.to_string(),
  176. values: HashMap::new(),
  177. files: None,
  178. };
  179. ctx.send(Event {
  180. id,
  181. name: "input",
  182. data: EventData::Form(data),
  183. bubbles: true,
  184. });
  185. }
  186. }
  187. fn handle_keydown(&mut self, mut root: NodeMut, data: &KeyboardData) {
  188. let key = data.key();
  189. let step = self.step();
  190. match key {
  191. Key::ArrowDown | Key::ArrowLeft => {
  192. self.update_value(self.value - step);
  193. }
  194. Key::ArrowUp | Key::ArrowRight => {
  195. self.update_value(self.value + step);
  196. }
  197. _ => {
  198. return;
  199. }
  200. }
  201. let id = root.id();
  202. let rdom = root.real_dom_mut();
  203. self.write_value(rdom, id);
  204. }
  205. fn handle_mousemove(&mut self, mut root: NodeMut, data: &MouseData) {
  206. if !data.held_buttons().is_empty() {
  207. let id = root.id();
  208. let rdom = root.real_dom_mut();
  209. let world = rdom.raw_world_mut();
  210. let taffy = {
  211. let query: UniqueView<Query> = world.borrow().unwrap();
  212. query.stretch.clone()
  213. };
  214. let taffy = taffy.lock().unwrap();
  215. let layout = get_layout(rdom.get(self.div_wrapper).unwrap(), &taffy).unwrap();
  216. let width = layout.size.width as f64;
  217. let offset = data.element_coordinates();
  218. self.update_value(self.min + self.size() * offset.x / width);
  219. self.write_value(rdom, id);
  220. }
  221. }
  222. }
  223. impl CustomElement for Slider {
  224. const NAME: &'static str = "input";
  225. fn roots(&self) -> Vec<NodeId> {
  226. vec![self.div_wrapper]
  227. }
  228. fn create(mut root: dioxus_native_core::real_dom::NodeMut) -> Self {
  229. let node_type = root.node_type();
  230. let NodeType::Element(el) = &*node_type else { panic!("input must be an element") };
  231. let value = el.attributes.get(&OwnedAttributeDiscription {
  232. name: "value".to_string(),
  233. namespace: None,
  234. });
  235. let value = value
  236. .and_then(|value| match value {
  237. OwnedAttributeValue::Text(text) => text.as_str().parse().ok(),
  238. OwnedAttributeValue::Float(float) => Some(*float),
  239. OwnedAttributeValue::Int(int) => Some(*int as f64),
  240. _ => None,
  241. })
  242. .unwrap_or(0.0);
  243. drop(node_type);
  244. let rdom = root.real_dom_mut();
  245. let pre_cursor_div = rdom.create_node(NodeType::Element(ElementNode {
  246. tag: "div".to_string(),
  247. attributes: [(
  248. OwnedAttributeDiscription {
  249. name: "background-color".to_string(),
  250. namespace: Some("style".to_string()),
  251. },
  252. "rgba(10,10,10,0.5)".to_string().into(),
  253. )]
  254. .into_iter()
  255. .collect(),
  256. ..Default::default()
  257. }));
  258. let pre_cursor_div_id = pre_cursor_div.id();
  259. let cursor_text = rdom.create_node("|".to_string());
  260. let cursor_text_id = cursor_text.id();
  261. let mut cursor_span = rdom.create_node(NodeType::Element(ElementNode {
  262. tag: "div".to_string(),
  263. attributes: [].into_iter().collect(),
  264. ..Default::default()
  265. }));
  266. cursor_span.add_child(cursor_text_id);
  267. let cursor_span_id = cursor_span.id();
  268. let post_cursor_div = rdom.create_node(NodeType::Element(ElementNode {
  269. tag: "span".to_string(),
  270. attributes: [
  271. (
  272. OwnedAttributeDiscription {
  273. name: "width".to_string(),
  274. namespace: Some("style".to_string()),
  275. },
  276. "100%".to_string().into(),
  277. ),
  278. (
  279. OwnedAttributeDiscription {
  280. name: "background-color".to_string(),
  281. namespace: Some("style".to_string()),
  282. },
  283. "rgba(10,10,10,0.5)".to_string().into(),
  284. ),
  285. ]
  286. .into_iter()
  287. .collect(),
  288. ..Default::default()
  289. }));
  290. let post_cursor_div_id = post_cursor_div.id();
  291. let mut div_wrapper = rdom.create_node(NodeType::Element(ElementNode {
  292. tag: "div".to_string(),
  293. attributes: [
  294. (
  295. OwnedAttributeDiscription {
  296. name: "display".to_string(),
  297. namespace: Some("style".to_string()),
  298. },
  299. "flex".to_string().into(),
  300. ),
  301. (
  302. OwnedAttributeDiscription {
  303. name: "flex-direction".to_string(),
  304. namespace: Some("style".to_string()),
  305. },
  306. "row".to_string().into(),
  307. ),
  308. (
  309. OwnedAttributeDiscription {
  310. name: "width".to_string(),
  311. namespace: Some("style".to_string()),
  312. },
  313. "100%".to_string().into(),
  314. ),
  315. (
  316. OwnedAttributeDiscription {
  317. name: "height".to_string(),
  318. namespace: Some("style".to_string()),
  319. },
  320. "100%".to_string().into(),
  321. ),
  322. ]
  323. .into_iter()
  324. .collect(),
  325. ..Default::default()
  326. }));
  327. let div_wrapper_id = div_wrapper.id();
  328. div_wrapper.add_child(pre_cursor_div_id);
  329. div_wrapper.add_child(cursor_span_id);
  330. div_wrapper.add_child(post_cursor_div_id);
  331. root.add_event_listener("mousemove");
  332. root.add_event_listener("mousedown");
  333. root.add_event_listener("keydown");
  334. Self {
  335. pre_cursor_div: pre_cursor_div_id,
  336. post_cursor_div: post_cursor_div_id,
  337. div_wrapper: div_wrapper_id,
  338. value,
  339. ..Default::default()
  340. }
  341. }
  342. fn attributes_changed(
  343. &mut self,
  344. mut root: dioxus_native_core::real_dom::NodeMut,
  345. attributes: &dioxus_native_core::node_ref::AttributeMask,
  346. ) {
  347. match attributes {
  348. AttributeMask::All => {
  349. {
  350. let node_type = root.node_type_mut();
  351. let NodeTypeMut::Element(mut el) = node_type else { panic!("input must be an element") };
  352. self.update_value_attr(&el);
  353. self.update_size_attr(&mut el);
  354. self.update_max_attr(&el);
  355. self.update_min_attr(&el);
  356. self.update_step_attr(&el);
  357. }
  358. let id = root.id();
  359. self.write_value(root.real_dom_mut(), id);
  360. }
  361. AttributeMask::Some(attrs) => {
  362. {
  363. let node_type = root.node_type_mut();
  364. let NodeTypeMut::Element(mut el) = node_type else { panic!("input must be an element") };
  365. if attrs.contains("width") || attrs.contains("height") {
  366. self.update_size_attr(&mut el);
  367. }
  368. if attrs.contains("max") {
  369. self.update_max_attr(&el);
  370. }
  371. if attrs.contains("min") {
  372. self.update_min_attr(&el);
  373. }
  374. if attrs.contains("step") {
  375. self.update_step_attr(&el);
  376. }
  377. if attrs.contains("value") {
  378. self.update_value_attr(&el);
  379. }
  380. }
  381. if attrs.contains("value") {
  382. let id = root.id();
  383. self.write_value(root.real_dom_mut(), id);
  384. }
  385. }
  386. }
  387. }
  388. }
  389. impl RinkWidget for Slider {
  390. fn handle_event(&mut self, event: &crate::Event, node: dioxus_native_core::real_dom::NodeMut) {
  391. match event.name {
  392. "keydown" => {
  393. if let EventData::Keyboard(data) = &event.data {
  394. self.handle_keydown(node, data);
  395. }
  396. }
  397. "mousemove" => {
  398. if let EventData::Mouse(data) = &event.data {
  399. self.handle_mousemove(node, data);
  400. }
  401. }
  402. "mousedown" => {
  403. if let EventData::Mouse(data) = &event.data {
  404. self.handle_mousemove(node, data);
  405. }
  406. }
  407. _ => {}
  408. }
  409. }
  410. }