pattern_model.rs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. #![allow(non_snake_case)]
  2. //! Example: Calculator
  3. //! -------------------
  4. //!
  5. //! Some components benefit through the use of "Models". Models are a single block of encapsulated state that allow mutative
  6. //! methods to be performed on them. Dioxus exposes the ability to use the model pattern through the "use_model" hook.
  7. //!
  8. //! Models are commonly used in the "Model-View-Component" approach for building UI state.
  9. //!
  10. //! `use_model` is basically just a fancy wrapper around set_state, but saves a "working copy" of the new state behind a
  11. //! RefCell. To modify the working copy, you need to call "get_mut" which returns the RefMut. This makes it easy to write
  12. //! fully encapsulated apps that retain a certain feel of native Rusty-ness. A calculator app is a good example of when this
  13. //! is useful.
  14. //!
  15. //! 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)
  16. //! the RefCell will panic and crash. You can use `try_get_mut` or `.modify` to avoid this problem, or just not hold two
  17. //! RefMuts at the same time.
  18. use dioxus::desktop::wry::application::dpi::LogicalSize;
  19. use dioxus::events::*;
  20. use dioxus::prelude::*;
  21. fn main() {
  22. dioxus::desktop::launch_cfg(app, |cfg| {
  23. cfg.with_window(|w| {
  24. w.with_title("Calculator Demo")
  25. .with_resizable(false)
  26. .with_inner_size(LogicalSize::new(320.0, 530.0))
  27. })
  28. });
  29. }
  30. fn app(cx: Scope) -> Element {
  31. let state = use_ref(&cx, Calculator::new);
  32. cx.render(rsx! {
  33. style { [include_str!("./assets/calculator.css")] }
  34. div { id: "wrapper",
  35. div { class: "app",
  36. div { class: "calculator", onkeypress: move |evt| state.write().handle_keydown(evt),
  37. div { class: "calculator-display", [state.read().formatted_display()]}
  38. div { class: "calculator-keypad",
  39. div { class: "input-keys",
  40. div { class: "function-keys",
  41. CalculatorKey {
  42. name: "key-clear",
  43. onclick: move |_| state.write().clear_display(),
  44. [if state.read().display_value == "0" { "C" } else { "AC" }]
  45. }
  46. CalculatorKey {
  47. name: "key-sign",
  48. onclick: move |_| state.write().toggle_sign(),
  49. "±"
  50. }
  51. CalculatorKey {
  52. name: "key-percent",
  53. onclick: move |_| state.write().toggle_percent(),
  54. "%"
  55. }
  56. }
  57. div { class: "digit-keys",
  58. CalculatorKey {
  59. name: "key-0",
  60. onclick: move |_| state.write().input_digit(0),
  61. "0"
  62. }
  63. CalculatorKey {
  64. name: "key-dot",
  65. onclick: move |_| state.write().input_dot(),
  66. "●"
  67. }
  68. (1..10).map(move |k| rsx!{
  69. CalculatorKey {
  70. key: "{k}",
  71. name: "key-{k}",
  72. onclick: move |_| state.write().input_digit(k),
  73. "{k}"
  74. }
  75. })
  76. }
  77. }
  78. div { class: "operator-keys",
  79. CalculatorKey {
  80. name: "key-divide",
  81. onclick: move |_| state.write().set_operator(Operator::Div),
  82. "÷"
  83. }
  84. CalculatorKey {
  85. name: "key-multiply",
  86. onclick: move |_| state.write().set_operator(Operator::Mul),
  87. "×"
  88. }
  89. CalculatorKey {
  90. name: "key-subtract",
  91. onclick: move |_| state.write().set_operator(Operator::Sub),
  92. "−"
  93. }
  94. CalculatorKey {
  95. name: "key-add",
  96. onclick: move |_| state.write().set_operator(Operator::Add),
  97. "+"
  98. }
  99. CalculatorKey {
  100. name: "key-equals",
  101. onclick: move |_| state.write().perform_operation(),
  102. "="
  103. }
  104. }
  105. }
  106. }
  107. }
  108. }
  109. })
  110. }
  111. #[derive(Props)]
  112. struct CalculatorKeyProps<'a> {
  113. name: &'a str,
  114. onclick: EventHandler<'a, MouseEvent>,
  115. children: Element<'a>,
  116. }
  117. fn CalculatorKey<'a>(cx: Scope<'a, CalculatorKeyProps<'a>>) -> Element {
  118. cx.render(rsx! {
  119. button {
  120. class: "calculator-key {cx.props.name}",
  121. onclick: move |e| cx.props.onclick.call(e),
  122. &cx.props.children
  123. }
  124. })
  125. }
  126. struct Calculator {
  127. display_value: String,
  128. operator: Option<Operator>,
  129. waiting_for_operand: bool,
  130. cur_val: f64,
  131. }
  132. #[derive(Clone)]
  133. enum Operator {
  134. Add,
  135. Sub,
  136. Mul,
  137. Div,
  138. }
  139. impl Calculator {
  140. fn new() -> Self {
  141. Calculator {
  142. display_value: "0".to_string(),
  143. operator: None,
  144. waiting_for_operand: false,
  145. cur_val: 0.0,
  146. }
  147. }
  148. fn formatted_display(&self) -> String {
  149. use separator::Separatable;
  150. self.display_value
  151. .parse::<f64>()
  152. .unwrap()
  153. .separated_string()
  154. }
  155. fn clear_display(&mut self) {
  156. self.display_value = "0".to_string();
  157. }
  158. fn input_digit(&mut self, digit: u8) {
  159. let content = digit.to_string();
  160. if self.waiting_for_operand || self.display_value == "0" {
  161. self.waiting_for_operand = false;
  162. self.display_value = content;
  163. } else {
  164. self.display_value.push_str(content.as_str());
  165. }
  166. }
  167. fn input_dot(&mut self) {
  168. if !self.display_value.contains('.') {
  169. self.display_value.push('.');
  170. }
  171. }
  172. fn perform_operation(&mut self) {
  173. if let Some(op) = &self.operator {
  174. let rhs = self.display_value.parse::<f64>().unwrap();
  175. let new_val = match op {
  176. Operator::Add => self.cur_val + rhs,
  177. Operator::Sub => self.cur_val - rhs,
  178. Operator::Mul => self.cur_val * rhs,
  179. Operator::Div => self.cur_val / rhs,
  180. };
  181. self.cur_val = new_val;
  182. self.display_value = new_val.to_string();
  183. self.operator = None;
  184. }
  185. }
  186. fn toggle_sign(&mut self) {
  187. if self.display_value.starts_with('-') {
  188. self.display_value = self.display_value.trim_start_matches('-').to_string();
  189. } else {
  190. self.display_value = format!("-{}", self.display_value);
  191. }
  192. }
  193. fn toggle_percent(&mut self) {
  194. self.display_value = (self.display_value.parse::<f64>().unwrap() / 100.0).to_string();
  195. }
  196. fn backspace(&mut self) {
  197. if !self.display_value.as_str().eq("0") {
  198. self.display_value.pop();
  199. }
  200. }
  201. fn set_operator(&mut self, operator: Operator) {
  202. self.operator = Some(operator);
  203. self.cur_val = self.display_value.parse::<f64>().unwrap();
  204. self.waiting_for_operand = true;
  205. }
  206. fn handle_keydown(&mut self, evt: KeyboardEvent) {
  207. match evt.key_code {
  208. KeyCode::Backspace => self.backspace(),
  209. KeyCode::Num0 => self.input_digit(0),
  210. KeyCode::Num1 => self.input_digit(1),
  211. KeyCode::Num2 => self.input_digit(2),
  212. KeyCode::Num3 => self.input_digit(3),
  213. KeyCode::Num4 => self.input_digit(4),
  214. KeyCode::Num5 => self.input_digit(5),
  215. KeyCode::Num6 => self.input_digit(6),
  216. KeyCode::Num7 => self.input_digit(7),
  217. KeyCode::Num8 => self.input_digit(8),
  218. KeyCode::Num9 => self.input_digit(9),
  219. KeyCode::Add => self.operator = Some(Operator::Add),
  220. KeyCode::Subtract => self.operator = Some(Operator::Sub),
  221. KeyCode::Divide => self.operator = Some(Operator::Div),
  222. KeyCode::Multiply => self.operator = Some(Operator::Mul),
  223. _ => {}
  224. }
  225. }
  226. }