1
0

calculator.rs 7.6 KB

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