model.rs 7.5 KB

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