model.rs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. const STYLE: &str = include_str!("./assets/calculator.css");
  20. fn main() {
  21. dioxus::desktop::launch(App, |cfg| cfg.with_title("Calculator Demo"))
  22. .expect("failed to launch dioxus app");
  23. }
  24. static App: FC<()> = |cx| {
  25. let state = use_state(cx, || Calculator::new());
  26. let clear_display = state.display_value.eq("0");
  27. let clear_text = if clear_display { "C" } else { "AC" };
  28. let formatted = state.formatted_display();
  29. cx.render(rsx! {
  30. div { id: "wrapper"
  31. div { class: "app", style { "{STYLE}" }
  32. div { class: "calculator", onkeypress: move |evt| state.get_mut().handle_keydown(evt),
  33. div { class: "calculator-display", "{formatted}"}
  34. div { class: "calculator-keypad"
  35. div { class: "input-keys"
  36. div { class: "function-keys"
  37. CalculatorKey { name: "key-clear", onclick: move |_| state.get_mut().clear_display(), "{clear_text}" }
  38. CalculatorKey { name: "key-sign", onclick: move |_| state.get_mut().toggle_sign(), "±"}
  39. CalculatorKey { name: "key-percent", onclick: move |_| state.get_mut().toggle_percent(), "%"}
  40. }
  41. div { class: "digit-keys"
  42. CalculatorKey { name: "key-0", onclick: move |_| state.get_mut().input_digit(0), "0" }
  43. CalculatorKey { name: "key-dot", onclick: move |_| state.get_mut().input_dot(), "●" }
  44. {(1..10).map(move |k| rsx!{
  45. CalculatorKey { key: "{k}", name: "key-{k}", onclick: move |_| state.get_mut().input_digit(k), "{k}" }
  46. })}
  47. }
  48. }
  49. div { class: "operator-keys"
  50. CalculatorKey { name:"key-divide", onclick: move |_| state.get_mut().set_operator(Operator::Div), "÷" }
  51. CalculatorKey { name:"key-multiply", onclick: move |_| state.get_mut().set_operator(Operator::Mul), "×" }
  52. CalculatorKey { name:"key-subtract", onclick: move |_| state.get_mut().set_operator(Operator::Sub), "−" }
  53. CalculatorKey { name:"key-add", onclick: move |_| state.get_mut().set_operator(Operator::Add), "+" }
  54. CalculatorKey { name:"key-equals", onclick: move |_| state.get_mut().perform_operation(), "=" }
  55. }
  56. }
  57. }
  58. }
  59. }
  60. })
  61. };
  62. #[derive(Props)]
  63. struct CalculatorKeyProps<'a> {
  64. name: &'static str,
  65. onclick: &'a dyn Fn(MouseEvent),
  66. }
  67. fn CalculatorKey<'a, 'r>(cx: Context<'a, CalculatorKeyProps<'r>>) -> DomTree<'a> {
  68. cx.render(rsx! {
  69. button {
  70. class: "calculator-key {cx.name}"
  71. onclick: {cx.onclick}
  72. {cx.children()}
  73. }
  74. })
  75. }
  76. #[derive(Clone)]
  77. struct Calculator {
  78. display_value: String,
  79. operator: Option<Operator>,
  80. waiting_for_operand: bool,
  81. cur_val: f64,
  82. }
  83. #[derive(Clone)]
  84. enum Operator {
  85. Add,
  86. Sub,
  87. Mul,
  88. Div,
  89. }
  90. impl Calculator {
  91. fn new() -> Self {
  92. Calculator {
  93. display_value: "0".to_string(),
  94. operator: None,
  95. waiting_for_operand: false,
  96. cur_val: 0.0,
  97. }
  98. }
  99. fn formatted_display(&self) -> String {
  100. use separator::Separatable;
  101. self.display_value
  102. .parse::<f64>()
  103. .unwrap()
  104. .separated_string()
  105. }
  106. fn clear_display(&mut self) {
  107. self.display_value = "0".to_string();
  108. }
  109. fn input_digit(&mut self, digit: u8) {
  110. let content = digit.to_string();
  111. if self.waiting_for_operand || self.display_value == "0" {
  112. self.waiting_for_operand = false;
  113. self.display_value = content;
  114. } else {
  115. self.display_value.push_str(content.as_str());
  116. }
  117. }
  118. fn input_dot(&mut self) {
  119. if self.display_value.find(".").is_none() {
  120. self.display_value.push_str(".");
  121. }
  122. }
  123. fn perform_operation(&mut self) {
  124. if let Some(op) = &self.operator {
  125. let rhs = self.display_value.parse::<f64>().unwrap();
  126. let new_val = match op {
  127. Operator::Add => self.cur_val + rhs,
  128. Operator::Sub => self.cur_val - rhs,
  129. Operator::Mul => self.cur_val * rhs,
  130. Operator::Div => self.cur_val / rhs,
  131. };
  132. self.cur_val = new_val;
  133. self.display_value = new_val.to_string();
  134. self.operator = None;
  135. }
  136. }
  137. fn toggle_sign(&mut self) {
  138. if self.display_value.starts_with("-") {
  139. self.display_value = self.display_value.trim_start_matches("-").to_string();
  140. } else {
  141. self.display_value = format!("-{}", self.display_value);
  142. }
  143. }
  144. fn toggle_percent(&mut self) {
  145. self.display_value = (self.display_value.parse::<f64>().unwrap() / 100.0).to_string();
  146. }
  147. fn backspace(&mut self) {
  148. if !self.display_value.as_str().eq("0") {
  149. self.display_value.pop();
  150. }
  151. }
  152. fn set_operator(&mut self, operator: Operator) {
  153. self.operator = Some(operator);
  154. self.cur_val = self.display_value.parse::<f64>().unwrap();
  155. self.waiting_for_operand = true;
  156. }
  157. fn handle_keydown(&mut self, evt: KeyboardEvent) {
  158. match evt.key_code() {
  159. KeyCode::Backspace => self.backspace(),
  160. KeyCode::_0 => self.input_digit(0),
  161. KeyCode::_1 => self.input_digit(1),
  162. KeyCode::_2 => self.input_digit(2),
  163. KeyCode::_3 => self.input_digit(3),
  164. KeyCode::_4 => self.input_digit(4),
  165. KeyCode::_5 => self.input_digit(5),
  166. KeyCode::_6 => self.input_digit(6),
  167. KeyCode::_7 => self.input_digit(7),
  168. KeyCode::_8 => self.input_digit(8),
  169. KeyCode::_9 => self.input_digit(9),
  170. KeyCode::Add => self.operator = Some(Operator::Add),
  171. KeyCode::Subtract => self.operator = Some(Operator::Sub),
  172. KeyCode::Divide => self.operator = Some(Operator::Div),
  173. KeyCode::Multiply => self.operator = Some(Operator::Mul),
  174. _ => {}
  175. }
  176. }
  177. }