model.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. //! Example: Calculator
  2. //! -------------------
  3. //!
  4. //! Some components benefit through the use of "Models". Models are a single block of encapsulated state that allow mutative
  5. //! methods to be performed on them. Dioxus exposes the ability to use the model pattern through the "use_model" hook.
  6. //!
  7. //! Models are commonly used in the "Model-View-Component" approach for building UI state.
  8. //!
  9. //! `use_model` is basically just a fancy wrapper around set_state, but saves a "working copy" of the new state behind a
  10. //! RefCell. To modify the working copy, you need to call "get_mut" which returns the RefMut. This makes it easy to write
  11. //! fully encapsulated apps that retain a certain feel of native Rusty-ness. A calculator app is a good example of when this
  12. //! is useful.
  13. //!
  14. //! 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)
  15. //! the RefCell will panic and crash. You can use `try_get_mut` or `.modify` to avoid this problem, or just not hold two
  16. //! RefMuts at the same time.
  17. use dioxus::events::on::*;
  18. use dioxus::prelude::*;
  19. use dioxus_core as dioxus;
  20. use dioxus_web::WebsysRenderer;
  21. const STYLE: &str = include_str!("../../../examples/assets/calculator.css");
  22. fn main() {
  23. // Setup logging
  24. wasm_logger::init(wasm_logger::Config::new(log::Level::Debug));
  25. console_error_panic_hook::set_once();
  26. // Run the app
  27. wasm_bindgen_futures::spawn_local(WebsysRenderer::start(App));
  28. }
  29. static App: FC<()> = |cx| {
  30. let state = use_model(&cx, || Calculator::new());
  31. let clear_display = state.display_value.eq("0");
  32. let clear_text = if clear_display { "C" } else { "AC" };
  33. let formatted = state.formatted_display();
  34. cx.render(rsx! {
  35. div { id: "wrapper"
  36. div { class: "app", style { "{STYLE}" }
  37. div { class: "calculator", onkeypress: move |evt| state.get_mut().handle_keydown(evt),
  38. div { class: "calculator-display", "{formatted}"}
  39. div { class: "calculator-keypad"
  40. div { class: "input-keys"
  41. div { class: "function-keys"
  42. CalculatorKey { name: "key-clear", onclick: move |_| state.get_mut().clear_display(), "{clear_text}" }
  43. CalculatorKey { name: "key-sign", onclick: move |_| state.get_mut().toggle_sign(), "±"}
  44. CalculatorKey { name: "key-percent", onclick: move |_| state.get_mut().toggle_percent(), "%"}
  45. }
  46. div { class: "digit-keys"
  47. CalculatorKey { name: "key-0", onclick: move |_| state.get_mut().input_digit(0), "0" }
  48. CalculatorKey { name: "key-dot", onclick: move |_| state.get_mut().input_dot(), "●" }
  49. {(1..10).map(move |k| rsx!{
  50. CalculatorKey { key: "{k}", name: "key-{k}", onclick: move |_| state.get_mut().input_digit(k), "{k}" }
  51. })}
  52. }
  53. }
  54. div { class: "operator-keys"
  55. CalculatorKey { name:"key-divide", onclick: move |_| state.get_mut().set_operator(Operator::Div), "÷" }
  56. CalculatorKey { name:"key-multiply", onclick: move |_| state.get_mut().set_operator(Operator::Mul), "×" }
  57. CalculatorKey { name:"key-subtract", onclick: move |_| state.get_mut().set_operator(Operator::Sub), "−" }
  58. CalculatorKey { name:"key-add", onclick: move |_| state.get_mut().set_operator(Operator::Add), "+" }
  59. CalculatorKey { name:"key-equals", onclick: move |_| state.get_mut().perform_operation(), "=" }
  60. }
  61. }
  62. }
  63. }
  64. }
  65. })
  66. };
  67. #[derive(Props)]
  68. struct CalculatorKeyProps<'a> {
  69. name: &'static str,
  70. onclick: &'a dyn Fn(MouseEvent),
  71. }
  72. fn CalculatorKey<'a, 'r>(cx: Context<'a, CalculatorKeyProps<'r>>) -> VNode<'a> {
  73. cx.render(rsx! {
  74. button {
  75. class: "calculator-key {cx.name}"
  76. onclick: {cx.onclick}
  77. {cx.children()}
  78. }
  79. })
  80. }
  81. #[derive(Clone)]
  82. struct Calculator {
  83. display_value: String,
  84. operator: Option<Operator>,
  85. waiting_for_operand: bool,
  86. cur_val: f64,
  87. }
  88. #[derive(Clone)]
  89. enum Operator {
  90. Add,
  91. Sub,
  92. Mul,
  93. Div,
  94. }
  95. impl Calculator {
  96. fn new() -> Self {
  97. Calculator {
  98. display_value: "0".to_string(),
  99. operator: None,
  100. waiting_for_operand: false,
  101. cur_val: 0.0,
  102. }
  103. }
  104. fn formatted_display(&self) -> String {
  105. use separator::Separatable;
  106. self.display_value
  107. .parse::<f64>()
  108. .unwrap()
  109. .separated_string()
  110. }
  111. fn clear_display(&mut self) {
  112. self.display_value = "0".to_string();
  113. }
  114. fn input_digit(&mut self, digit: u8) {
  115. let content = digit.to_string();
  116. if self.waiting_for_operand || self.display_value == "0" {
  117. self.waiting_for_operand = false;
  118. self.display_value = content;
  119. } else {
  120. self.display_value.push_str(content.as_str());
  121. }
  122. }
  123. fn input_dot(&mut self) {
  124. if self.display_value.find(".").is_none() {
  125. self.display_value.push_str(".");
  126. }
  127. }
  128. fn perform_operation(&mut self) {
  129. if let Some(op) = &self.operator {
  130. let rhs = self.display_value.parse::<f64>().unwrap();
  131. let new_val = match op {
  132. Operator::Add => self.cur_val + rhs,
  133. Operator::Sub => self.cur_val - rhs,
  134. Operator::Mul => self.cur_val * rhs,
  135. Operator::Div => self.cur_val / rhs,
  136. };
  137. self.cur_val = new_val;
  138. self.display_value = new_val.to_string();
  139. self.operator = None;
  140. }
  141. }
  142. fn toggle_sign(&mut self) {
  143. if self.display_value.starts_with("-") {
  144. self.display_value = self.display_value.trim_start_matches("-").to_string();
  145. } else {
  146. self.display_value = format!("-{}", self.display_value);
  147. }
  148. }
  149. fn toggle_percent(&mut self) {
  150. self.display_value = (self.display_value.parse::<f64>().unwrap() / 100.0).to_string();
  151. }
  152. fn backspace(&mut self) {
  153. if !self.display_value.as_str().eq("0") {
  154. self.display_value.pop();
  155. }
  156. }
  157. fn set_operator(&mut self, operator: Operator) {
  158. self.operator = Some(operator);
  159. self.cur_val = self.display_value.parse::<f64>().unwrap();
  160. self.waiting_for_operand = true;
  161. }
  162. fn handle_keydown(&mut self, evt: KeyboardEvent) {
  163. match evt.key_code() {
  164. KeyCode::Backspace => self.backspace(),
  165. KeyCode::_0 => self.input_digit(0),
  166. KeyCode::_1 => self.input_digit(1),
  167. KeyCode::_2 => self.input_digit(2),
  168. KeyCode::_3 => self.input_digit(3),
  169. KeyCode::_4 => self.input_digit(4),
  170. KeyCode::_5 => self.input_digit(5),
  171. KeyCode::_6 => self.input_digit(6),
  172. KeyCode::_7 => self.input_digit(7),
  173. KeyCode::_8 => self.input_digit(8),
  174. KeyCode::_9 => self.input_digit(9),
  175. KeyCode::Add => self.operator = Some(Operator::Add),
  176. KeyCode::Subtract => self.operator = Some(Operator::Sub),
  177. KeyCode::Divide => self.operator = Some(Operator::Div),
  178. KeyCode::Multiply => self.operator = Some(Operator::Mul),
  179. _ => {}
  180. }
  181. }
  182. }