1
0

calculator.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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", "{val}" }
  48. div { class: "calculator-keypad",
  49. div { class: "input-keys",
  50. div { class: "function-keys",
  51. button {
  52. class: "calculator-key key-clear",
  53. onclick: move |_| {
  54. val.set(String::new());
  55. if !val.cloned().is_empty() {
  56. val.set("0".into());
  57. }
  58. },
  59. if val.cloned().is_empty() { "C" } else { "AC" }
  60. }
  61. button {
  62. class: "calculator-key key-sign",
  63. onclick: move |_| {
  64. let new_val = calc_val(val.cloned().as_str());
  65. if new_val > 0.0 {
  66. val.set(format!("-{new_val}"));
  67. } else {
  68. val.set(format!("{}", new_val.abs()));
  69. }
  70. },
  71. "±"
  72. }
  73. button {
  74. class: "calculator-key key-percent",
  75. onclick: move |_| val.set(format!("{}", calc_val(val.cloned().as_str()) / 100.0)),
  76. "%"
  77. }
  78. }
  79. div { class: "digit-keys",
  80. button {
  81. class: "calculator-key key-0",
  82. onclick: move |_| input_digit(0.to_string()),
  83. "0"
  84. }
  85. button {
  86. class: "calculator-key key-dot",
  87. onclick: move |_| val.write().push('.'),
  88. "●"
  89. }
  90. for k in 1..10 {
  91. button {
  92. class: "calculator-key {k}",
  93. name: "key-{k}",
  94. onclick: move |_| input_digit(k.to_string()),
  95. "{k}"
  96. }
  97. }
  98. }
  99. }
  100. div { class: "operator-keys",
  101. for (key, class) in [("/", "key-divide"), ("*", "key-multiply"), ("-", "key-subtract"), ("+", "key-add")] {
  102. button {
  103. class: "calculator-key {class}",
  104. onclick: move |_| input_operator(key),
  105. "{key}"
  106. }
  107. }
  108. button {
  109. class: "calculator-key key-equals",
  110. onclick: move |_| val.set(format!("{}", calc_val(val.cloned().as_str()))),
  111. "="
  112. }
  113. }
  114. }
  115. }
  116. }
  117. }
  118. }
  119. }
  120. fn calc_val(val: &str) -> f64 {
  121. let mut temp = String::new();
  122. let mut operation = "+".to_string();
  123. let mut start_index = 0;
  124. let mut temp_value;
  125. let mut fin_index = 0;
  126. if &val[0..1] == "-" {
  127. temp_value = String::from("-");
  128. fin_index = 1;
  129. start_index += 1;
  130. } else {
  131. temp_value = String::from("");
  132. }
  133. for c in val[fin_index..].chars() {
  134. if c == '+' || c == '-' || c == '*' || c == '/' {
  135. break;
  136. }
  137. temp_value.push(c);
  138. start_index += 1;
  139. }
  140. let mut result = temp_value.parse::<f64>().unwrap();
  141. if start_index + 1 >= val.len() {
  142. return result;
  143. }
  144. for c in val[start_index..].chars() {
  145. if c == '+' || c == '-' || c == '*' || c == '/' {
  146. if !temp.is_empty() {
  147. match &operation as &str {
  148. "+" => result += temp.parse::<f64>().unwrap(),
  149. "-" => result -= temp.parse::<f64>().unwrap(),
  150. "*" => result *= temp.parse::<f64>().unwrap(),
  151. "/" => result /= temp.parse::<f64>().unwrap(),
  152. _ => unreachable!(),
  153. };
  154. }
  155. operation = c.to_string();
  156. temp = String::new();
  157. } else {
  158. temp.push(c);
  159. }
  160. }
  161. if !temp.is_empty() {
  162. match &operation as &str {
  163. "+" => result += temp.parse::<f64>().unwrap(),
  164. "-" => result -= temp.parse::<f64>().unwrap(),
  165. "*" => result *= temp.parse::<f64>().unwrap(),
  166. "/" => result /= temp.parse::<f64>().unwrap(),
  167. _ => unreachable!(),
  168. };
  169. }
  170. result
  171. }