pattern_model.rs 9.1 KB

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