calculator_.rs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. use dioxus::events::on::*;
  2. use dioxus::prelude::*;
  3. use dioxus_core as dioxus;
  4. const STYLE: &str = include_str!("../../../examples/assets/calculator.css");
  5. fn main() {
  6. dioxus_desktop::launch(
  7. |builder| {
  8. builder
  9. .title("Test Dioxus App")
  10. .size(340, 560)
  11. .resizable(false)
  12. .debug(true)
  13. },
  14. (),
  15. App,
  16. )
  17. .expect("Webview finished");
  18. }
  19. static App: FC<()> = |cx, props| {
  20. let state = use_model(&cx, || Calculator::new());
  21. let clear_display = state.display_value.eq("0");
  22. let clear_text = if clear_display { "C" } else { "AC" };
  23. let formatted = state.formatted_display();
  24. cx.render(rsx! {
  25. div { id: "wrapper"
  26. div { class: "app", style { "{STYLE}" }
  27. div { class: "calculator", onkeypress: move |evt| state.get_mut().handle_keydown(evt),
  28. div { class: "calculator-display", "{formatted}"}
  29. div { class: "calculator-keypad"
  30. div { class: "input-keys"
  31. div { class: "function-keys"
  32. CalculatorKey { name: "key-clear", onclick: move |_| state.get_mut().clear_display(), "{clear_text}" }
  33. CalculatorKey { name: "key-sign", onclick: move |_| state.get_mut().toggle_sign(), "±"}
  34. CalculatorKey { name: "key-percent", onclick: move |_| state.get_mut().toggle_percent(), "%"}
  35. }
  36. div { class: "digit-keys"
  37. CalculatorKey { name: "key-0", onclick: move |_| state.get_mut().input_digit(0), "0" }
  38. CalculatorKey { name: "key-dot", onclick: move |_| state.get_mut().input_dot(), "●" }
  39. {(1..10).map(move |k| rsx!{
  40. CalculatorKey { key: "{k}", name: "key-{k}", onclick: move |_| state.get_mut().input_digit(k), "{k}" }
  41. })}
  42. }
  43. }
  44. div { class: "operator-keys"
  45. CalculatorKey { name:"key-divide", onclick: move |_| state.get_mut().set_operator(Operator::Div), "÷" }
  46. CalculatorKey { name:"key-multiply", onclick: move |_| state.get_mut().set_operator(Operator::Mul), "×" }
  47. CalculatorKey { name:"key-subtract", onclick: move |_| state.get_mut().set_operator(Operator::Sub), "−" }
  48. CalculatorKey { name:"key-add", onclick: move |_| state.get_mut().set_operator(Operator::Add), "+" }
  49. CalculatorKey { name:"key-equals", onclick: move |_| state.get_mut().perform_operation(), "=" }
  50. }
  51. }
  52. }
  53. }
  54. }
  55. })
  56. };
  57. #[derive(Props)]
  58. struct CalculatorKeyProps<'a> {
  59. name: &'static str,
  60. onclick: &'a dyn Fn(MouseEvent),
  61. }
  62. fn CalculatorKey<'a, 'r>(cx: Context<'a, CalculatorKeyProps<'r>>) -> DomTree<'a> {
  63. cx.render(rsx! {
  64. button {
  65. class: "calculator-key {cx.name}"
  66. onclick: {cx.onclick}
  67. {cx.children()}
  68. }
  69. })
  70. }
  71. #[derive(Clone)]
  72. struct Calculator {
  73. display_value: String,
  74. operator: Option<Operator>,
  75. waiting_for_operand: bool,
  76. cur_val: f64,
  77. }
  78. #[derive(Clone)]
  79. enum Operator {
  80. Add,
  81. Sub,
  82. Mul,
  83. Div,
  84. }
  85. impl Calculator {
  86. fn new() -> Self {
  87. Calculator {
  88. display_value: "0".to_string(),
  89. operator: None,
  90. waiting_for_operand: false,
  91. cur_val: 0.0,
  92. }
  93. }
  94. fn formatted_display(&self) -> String {
  95. // use separator::Separatable;
  96. self.display_value.clone()
  97. // .parse::<f64>()
  98. // .unwrap()
  99. // .separated_string()
  100. }
  101. fn clear_display(&mut self) {
  102. self.display_value = "0".to_string();
  103. }
  104. fn input_digit(&mut self, digit: u8) {
  105. let content = digit.to_string();
  106. if self.waiting_for_operand || self.display_value == "0" {
  107. self.waiting_for_operand = false;
  108. self.display_value = content;
  109. } else {
  110. self.display_value.push_str(content.as_str());
  111. }
  112. }
  113. fn input_dot(&mut self) {
  114. if self.display_value.find(".").is_none() {
  115. self.display_value.push_str(".");
  116. }
  117. }
  118. fn perform_operation(&mut self) {
  119. if let Some(op) = &self.operator {
  120. let rhs = self.display_value.parse::<f64>().unwrap();
  121. let new_val = match op {
  122. Operator::Add => self.cur_val + rhs,
  123. Operator::Sub => self.cur_val - rhs,
  124. Operator::Mul => self.cur_val * rhs,
  125. Operator::Div => self.cur_val / rhs,
  126. };
  127. self.cur_val = new_val;
  128. self.display_value = new_val.to_string();
  129. self.operator = None;
  130. }
  131. }
  132. fn toggle_sign(&mut self) {
  133. if self.display_value.starts_with("-") {
  134. self.display_value = self.display_value.trim_start_matches("-").to_string();
  135. } else {
  136. self.display_value = format!("-{}", self.display_value);
  137. }
  138. }
  139. fn toggle_percent(&mut self) {
  140. self.display_value = (self.display_value.parse::<f64>().unwrap() / 100.0).to_string();
  141. }
  142. fn backspace(&mut self) {
  143. if !self.display_value.as_str().eq("0") {
  144. self.display_value.pop();
  145. }
  146. }
  147. fn set_operator(&mut self, operator: Operator) {
  148. self.operator = Some(operator);
  149. self.cur_val = self.display_value.parse::<f64>().unwrap();
  150. self.waiting_for_operand = true;
  151. }
  152. fn handle_keydown(&mut self, evt: KeyboardEvent) {
  153. match evt.key_code() {
  154. KeyCode::Backspace => self.backspace(),
  155. KeyCode::_0 => self.input_digit(0),
  156. KeyCode::_1 => self.input_digit(1),
  157. KeyCode::_2 => self.input_digit(2),
  158. KeyCode::_3 => self.input_digit(3),
  159. KeyCode::_4 => self.input_digit(4),
  160. KeyCode::_5 => self.input_digit(5),
  161. KeyCode::_6 => self.input_digit(6),
  162. KeyCode::_7 => self.input_digit(7),
  163. KeyCode::_8 => self.input_digit(8),
  164. KeyCode::_9 => self.input_digit(9),
  165. KeyCode::Add => self.operator = Some(Operator::Add),
  166. KeyCode::Subtract => self.operator = Some(Operator::Sub),
  167. KeyCode::Divide => self.operator = Some(Operator::Div),
  168. KeyCode::Multiply => self.operator = Some(Operator::Mul),
  169. _ => {}
  170. }
  171. }
  172. }