model.rs 7.4 KB

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