pattern_model.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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::desktop::wry::application::dpi::LogicalSize;
  18. use dioxus::events::on::*;
  19. use dioxus::prelude::*;
  20. const STYLE: &str = include_str!("./assets/calculator.css");
  21. fn main() {
  22. env_logger::init();
  23. dioxus::desktop::launch(App, |cfg| {
  24. cfg.with_window(|w| {
  25. w.with_title("Calculator Demo")
  26. .with_resizable(false)
  27. .with_inner_size(LogicalSize::new(320.0, 530.0))
  28. })
  29. })
  30. .expect("failed to launch dioxus app");
  31. }
  32. static App: FC<()> = |cx, props| {
  33. let state = use_ref(cx, || Calculator::new());
  34. let clear_display = state.read().display_value.eq("0");
  35. let clear_text = if clear_display { "C" } else { "AC" };
  36. let formatted = state.read().formatted_display();
  37. rsx!(cx, div { id: "wrapper"
  38. div { class: "app", style { "{STYLE}" }
  39. div { class: "calculator", onkeypress: move |evt| state.write().handle_keydown(evt),
  40. div { class: "calculator-display", "{formatted}"}
  41. div { class: "calculator-keypad"
  42. div { class: "input-keys"
  43. div { class: "function-keys"
  44. CalculatorKey { name: "key-clear", onclick: move |_| state.write().clear_display(), "{clear_text}" }
  45. CalculatorKey { name: "key-sign", onclick: move |_| state.write().toggle_sign(), "±"}
  46. CalculatorKey { name: "key-percent", onclick: move |_| state.write().toggle_percent(), "%"}
  47. }
  48. div { class: "digit-keys"
  49. CalculatorKey { name: "key-0", onclick: move |_| state.write().input_digit(0), "0" }
  50. CalculatorKey { name: "key-dot", onclick: move |_| state.write().input_dot(), "●" }
  51. {(1..10).map(move |k| rsx!{
  52. CalculatorKey { key: "{k}", name: "key-{k}", onclick: move |_| state.write().input_digit(k), "{k}" }
  53. })}
  54. }
  55. }
  56. div { class: "operator-keys"
  57. CalculatorKey { name:"key-divide", onclick: move |_| state.write().set_operator(Operator::Div), "÷" }
  58. CalculatorKey { name:"key-multiply", onclick: move |_| state.write().set_operator(Operator::Mul), "×" }
  59. CalculatorKey { name:"key-subtract", onclick: move |_| state.write().set_operator(Operator::Sub), "−" }
  60. CalculatorKey { name:"key-add", onclick: move |_| state.write().set_operator(Operator::Add), "+" }
  61. CalculatorKey { name:"key-equals", onclick: move |_| state.write().perform_operation(), "=" }
  62. }
  63. }
  64. }
  65. }
  66. })
  67. };
  68. #[derive(Props)]
  69. struct CalculatorKeyProps<'a> {
  70. name: &'static str,
  71. onclick: &'a dyn Fn(MouseEvent),
  72. }
  73. fn CalculatorKey<'a, 'r>(cx: Context<'a>, props: &'a CalculatorKeyProps) -> DomTree<'a> {
  74. cx.render(rsx! {
  75. button {
  76. class: "calculator-key {props.name}"
  77. onclick: {props.onclick}
  78. {cx.children()}
  79. }
  80. })
  81. }
  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::Num0 => self.input_digit(0),
  166. KeyCode::Num1 => self.input_digit(1),
  167. KeyCode::Num2 => self.input_digit(2),
  168. KeyCode::Num3 => self.input_digit(3),
  169. KeyCode::Num4 => self.input_digit(4),
  170. KeyCode::Num5 => self.input_digit(5),
  171. KeyCode::Num6 => self.input_digit(6),
  172. KeyCode::Num7 => self.input_digit(7),
  173. KeyCode::Num8 => self.input_digit(8),
  174. KeyCode::Num9 => 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. }