1
0

pattern_model.rs 9.1 KB

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