pattern_model.rs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. #![allow(non_snake_case)]
  2. //! Example: Calculator
  3. //! -------------------
  4. //!
  5. //! Some components benefit through the use of "Models". Models are a single block of encapsulated state that allow mutative
  6. //! methods to be performed on them. Dioxus exposes the ability to use the model pattern through the "use_model" hook.
  7. //!
  8. //! Models are commonly used in the "Model-View-Component" approach for building UI state.
  9. //!
  10. //! `use_model` is basically just a fancy wrapper around set_state, but saves a "working copy" of the new state behind a
  11. //! RefCell. To modify the working copy, you need to call "get_mut" which returns the RefMut. This makes it easy to write
  12. //! fully encapsulated apps that retain a certain feel of native Rusty-ness. A calculator app is a good example of when this
  13. //! is useful.
  14. //!
  15. //! Do note that "get_mut" returns a `RefMut` (a lock over a RefCell). If two `RefMut`s are held at the same time (ie in a loop)
  16. //! the RefCell will panic and crash. You can use `try_get_mut` or `.modify` to avoid this problem, or just not hold two
  17. //! RefMuts at the same time.
  18. use dioxus::events::*;
  19. use dioxus::html::input_data::keyboard_types::Key;
  20. use dioxus::html::MouseEvent;
  21. use dioxus::prelude::*;
  22. use dioxus_desktop::tao::dpi::LogicalSize;
  23. use dioxus_desktop::{Config, WindowBuilder};
  24. fn main() {
  25. let cfg = Config::new().with_window(
  26. WindowBuilder::new()
  27. .with_title("Calculator Demo")
  28. .with_resizable(false)
  29. .with_inner_size(LogicalSize::new(320.0, 530.0)),
  30. );
  31. LaunchBuilder::new(app).cfg(cfg);
  32. }
  33. const STYLE: &str = include_str!("./assets/calculator.css");
  34. fn app() -> Element {
  35. let mut state = use_signal(Calculator::new);
  36. rsx! {
  37. style { {STYLE} }
  38. div { id: "wrapper",
  39. div { class: "app",
  40. div { class: "calculator", onkeypress: move |evt| state.write().handle_keydown(evt),
  41. div { class: "calculator-display", {state.read().formatted_display()} }
  42. div { class: "calculator-keypad",
  43. div { class: "input-keys",
  44. div { class: "function-keys",
  45. CalculatorKey {
  46. name: "key-clear",
  47. onclick: move |_| state.write().clear_display(),
  48. if state.read().display_value == "0" { "C" } else { "AC" }
  49. }
  50. CalculatorKey {
  51. name: "key-sign",
  52. onclick: move |_| state.write().toggle_sign(),
  53. "±"
  54. }
  55. CalculatorKey {
  56. name: "key-percent",
  57. onclick: move |_| state.write().toggle_percent(),
  58. "%"
  59. }
  60. }
  61. div { class: "digit-keys",
  62. CalculatorKey {
  63. name: "key-0",
  64. onclick: move |_| state.write().input_digit(0),
  65. "0"
  66. }
  67. CalculatorKey {
  68. name: "key-dot",
  69. onclick: move |_| state.write().input_dot(),
  70. "●"
  71. }
  72. for k in 1..10 {
  73. CalculatorKey {
  74. key: "{k}",
  75. name: "key-{k}",
  76. onclick: move |_| state.write().input_digit(k),
  77. "{k}"
  78. }
  79. }
  80. }
  81. }
  82. div { class: "operator-keys",
  83. CalculatorKey {
  84. name: "key-divide",
  85. onclick: move |_| state.write().set_operator(Operator::Div),
  86. "÷"
  87. }
  88. CalculatorKey {
  89. name: "key-multiply",
  90. onclick: move |_| state.write().set_operator(Operator::Mul),
  91. "×"
  92. }
  93. CalculatorKey {
  94. name: "key-subtract",
  95. onclick: move |_| state.write().set_operator(Operator::Sub),
  96. "−"
  97. }
  98. CalculatorKey {
  99. name: "key-add",
  100. onclick: move |_| state.write().set_operator(Operator::Add),
  101. "+"
  102. }
  103. CalculatorKey {
  104. name: "key-equals",
  105. onclick: move |_| state.write().perform_operation(),
  106. "="
  107. }
  108. }
  109. }
  110. }
  111. }
  112. }
  113. }
  114. }
  115. #[component]
  116. fn CalculatorKey(
  117. #[props(into)] name: String,
  118. onclick: EventHandler<MouseEvent>,
  119. children: Element,
  120. ) -> Element {
  121. rsx! {
  122. button {
  123. class: "calculator-key {name}",
  124. onclick: move |e| onclick.call(e),
  125. {&children}
  126. }
  127. }
  128. }
  129. struct Calculator {
  130. display_value: String,
  131. operator: Option<Operator>,
  132. waiting_for_operand: bool,
  133. cur_val: f64,
  134. }
  135. #[derive(Clone)]
  136. enum Operator {
  137. Add,
  138. Sub,
  139. Mul,
  140. Div,
  141. }
  142. impl Calculator {
  143. fn new() -> Self {
  144. Calculator {
  145. display_value: "0".to_string(),
  146. operator: None,
  147. waiting_for_operand: false,
  148. cur_val: 0.0,
  149. }
  150. }
  151. fn formatted_display(&self) -> String {
  152. use separator::Separatable;
  153. self.display_value
  154. .parse::<f64>()
  155. .unwrap()
  156. .separated_string()
  157. }
  158. fn clear_display(&mut self) {
  159. self.display_value = "0".to_string();
  160. }
  161. fn input_digit(&mut self, digit: u8) {
  162. let content = digit.to_string();
  163. if self.waiting_for_operand || self.display_value == "0" {
  164. self.waiting_for_operand = false;
  165. self.display_value = content;
  166. } else {
  167. self.display_value.push_str(content.as_str());
  168. }
  169. }
  170. fn input_dot(&mut self) {
  171. if !self.display_value.contains('.') {
  172. self.display_value.push('.');
  173. }
  174. }
  175. fn perform_operation(&mut self) {
  176. if let Some(op) = &self.operator {
  177. let rhs = self.display_value.parse::<f64>().unwrap();
  178. let new_val = match op {
  179. Operator::Add => self.cur_val + rhs,
  180. Operator::Sub => self.cur_val - rhs,
  181. Operator::Mul => self.cur_val * rhs,
  182. Operator::Div => self.cur_val / rhs,
  183. };
  184. self.cur_val = new_val;
  185. self.display_value = new_val.to_string();
  186. self.operator = None;
  187. }
  188. }
  189. fn toggle_sign(&mut self) {
  190. if self.display_value.starts_with('-') {
  191. self.display_value = self.display_value.trim_start_matches('-').to_string();
  192. } else {
  193. self.display_value = format!("-{}", self.display_value);
  194. }
  195. }
  196. fn toggle_percent(&mut self) {
  197. self.display_value = (self.display_value.parse::<f64>().unwrap() / 100.0).to_string();
  198. }
  199. fn backspace(&mut self) {
  200. if !self.display_value.as_str().eq("0") {
  201. self.display_value.pop();
  202. }
  203. }
  204. fn set_operator(&mut self, operator: Operator) {
  205. self.operator = Some(operator);
  206. self.cur_val = self.display_value.parse::<f64>().unwrap();
  207. self.waiting_for_operand = true;
  208. }
  209. fn handle_keydown(&mut self, evt: KeyboardEvent) {
  210. match evt.key() {
  211. Key::Backspace => self.backspace(),
  212. Key::Character(c) => match c.as_str() {
  213. "0" => self.input_digit(0),
  214. "1" => self.input_digit(1),
  215. "2" => self.input_digit(2),
  216. "3" => self.input_digit(3),
  217. "4" => self.input_digit(4),
  218. "5" => self.input_digit(5),
  219. "6" => self.input_digit(6),
  220. "7" => self.input_digit(7),
  221. "8" => self.input_digit(8),
  222. "9" => self.input_digit(9),
  223. "+" => self.operator = Some(Operator::Add),
  224. "-" => self.operator = Some(Operator::Sub),
  225. "/" => self.operator = Some(Operator::Div),
  226. "*" => self.operator = Some(Operator::Mul),
  227. _ => {}
  228. },
  229. _ => {}
  230. }
  231. }
  232. }