pattern_model.rs 9.0 KB

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