pattern_model.rs 9.1 KB

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