pattern_model.rs 7.7 KB

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