pattern_model.rs 9.0 KB

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