calculator.rs 7.7 KB

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