calculator.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. /*
  2. This example is a simple iOS-style calculator. This particular example can run any platform - Web, Mobile, Desktop.
  3. This calculator version uses React-style state management. All state is held as individual use_states.
  4. */
  5. use dioxus::events::*;
  6. use dioxus::html::input_data::keyboard_types::Key;
  7. use dioxus::prelude::*;
  8. fn main() {
  9. LaunchBuilder::new()
  10. .with_cfg(desktop!({
  11. use dioxus::desktop::{Config, LogicalSize, WindowBuilder};
  12. Config::new().with_window(
  13. WindowBuilder::default()
  14. .with_title("Calculator")
  15. .with_inner_size(LogicalSize::new(300.0, 525.0)),
  16. )
  17. }))
  18. .launch(app);
  19. }
  20. fn app() -> Element {
  21. let mut val = use_signal(|| String::from("0"));
  22. let mut input_digit = move |num: String| {
  23. if val() == "0" {
  24. val.set(String::new());
  25. }
  26. val.write().push_str(num.as_str());
  27. };
  28. let mut input_operator = move |key: &str| val.write().push_str(key);
  29. let handle_key_down_event = move |evt: KeyboardEvent| match evt.key() {
  30. Key::Backspace => {
  31. if !val().is_empty() {
  32. val.write().pop();
  33. }
  34. }
  35. Key::Character(character) => match character.as_str() {
  36. "+" | "-" | "/" | "*" => input_operator(&character),
  37. "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" => input_digit(character),
  38. _ => {}
  39. },
  40. _ => {}
  41. };
  42. rsx! {
  43. style { {include_str!("./assets/calculator.css")} }
  44. div { id: "wrapper",
  45. div { class: "app",
  46. div { class: "calculator", tabindex: "0", onkeydown: handle_key_down_event,
  47. div { class: "calculator-display",
  48. if val().is_empty() {
  49. "0"
  50. } else {
  51. "{val}"
  52. }
  53. }
  54. div { class: "calculator-keypad",
  55. div { class: "input-keys",
  56. div { class: "function-keys",
  57. button {
  58. class: "calculator-key key-clear",
  59. onclick: move |_| {
  60. val.set(String::new());
  61. if !val.cloned().is_empty() {
  62. val.set("0".into());
  63. }
  64. },
  65. if val.cloned().is_empty() { "C" } else { "AC" }
  66. }
  67. button {
  68. class: "calculator-key key-sign",
  69. onclick: move |_| {
  70. let new_val = calc_val(val.cloned().as_str());
  71. if new_val > 0.0 {
  72. val.set(format!("-{new_val}"));
  73. } else {
  74. val.set(format!("{}", new_val.abs()));
  75. }
  76. },
  77. "±"
  78. }
  79. button {
  80. class: "calculator-key key-percent",
  81. onclick: move |_| val.set(format!("{}", calc_val(val.cloned().as_str()) / 100.0)),
  82. "%"
  83. }
  84. }
  85. div { class: "digit-keys",
  86. button {
  87. class: "calculator-key key-0",
  88. onclick: move |_| input_digit(0.to_string()),
  89. "0"
  90. }
  91. button {
  92. class: "calculator-key key-dot",
  93. onclick: move |_| val.write().push('.'),
  94. "●"
  95. }
  96. for k in 1..10 {
  97. button {
  98. class: "calculator-key {k}",
  99. name: "key-{k}",
  100. onclick: move |_| input_digit(k.to_string()),
  101. "{k}"
  102. }
  103. }
  104. }
  105. }
  106. div { class: "operator-keys",
  107. for (key, class) in [("/", "key-divide"), ("*", "key-multiply"), ("-", "key-subtract"), ("+", "key-add")] {
  108. button {
  109. class: "calculator-key {class}",
  110. onclick: move |_| input_operator(key),
  111. "{key}"
  112. }
  113. }
  114. button {
  115. class: "calculator-key key-equals",
  116. onclick: move |_| val.set(format!("{}", calc_val(val.cloned().as_str()))),
  117. "="
  118. }
  119. }
  120. }
  121. }
  122. }
  123. }
  124. }
  125. }
  126. fn calc_val(val: &str) -> f64 {
  127. let mut temp = String::new();
  128. let mut operation = "+".to_string();
  129. let mut start_index = 0;
  130. let mut temp_value;
  131. let mut fin_index = 0;
  132. if &val[0..1] == "-" {
  133. temp_value = String::from("-");
  134. fin_index = 1;
  135. start_index += 1;
  136. } else {
  137. temp_value = String::from("");
  138. }
  139. for c in val[fin_index..].chars() {
  140. if c == '+' || c == '-' || c == '*' || c == '/' {
  141. break;
  142. }
  143. temp_value.push(c);
  144. start_index += 1;
  145. }
  146. let mut result = temp_value.parse::<f64>().unwrap();
  147. if start_index + 1 >= val.len() {
  148. return result;
  149. }
  150. for c in val[start_index..].chars() {
  151. if c == '+' || c == '-' || c == '*' || c == '/' {
  152. if !temp.is_empty() {
  153. match &operation as &str {
  154. "+" => result += temp.parse::<f64>().unwrap(),
  155. "-" => result -= temp.parse::<f64>().unwrap(),
  156. "*" => result *= temp.parse::<f64>().unwrap(),
  157. "/" => result /= temp.parse::<f64>().unwrap(),
  158. _ => unreachable!(),
  159. };
  160. }
  161. operation = c.to_string();
  162. temp = String::new();
  163. } else {
  164. temp.push(c);
  165. }
  166. }
  167. if !temp.is_empty() {
  168. match &operation as &str {
  169. "+" => result += temp.parse::<f64>().unwrap(),
  170. "-" => result -= temp.parse::<f64>().unwrap(),
  171. "*" => result *= temp.parse::<f64>().unwrap(),
  172. "/" => result /= temp.parse::<f64>().unwrap(),
  173. _ => unreachable!(),
  174. };
  175. }
  176. result
  177. }