1
0

model.rs 6.3 KB

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