calculator.rs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. //! Example: Calculator
  2. //! ------------------
  3. //!
  4. //! This example showcases a basic iOS-style calculator app using classic react-style `use_state` hooks. A counterpart of
  5. //! this example is in `model.rs` which shows the same calculator app implemented using the `model` paradigm. We've found
  6. //! that the most natural Rust code is more "model-y" than "React-y", but opt to keep this example to show the different
  7. //! flavors of programming you can use in Dioxus.
  8. use dioxus::events::on::*;
  9. use dioxus::prelude::*;
  10. use dioxus_core as dioxus;
  11. use dioxus_web::WebsysRenderer;
  12. const STYLE: &str = include_str!("../../../examples/assets/calculator.css");
  13. fn main() {
  14. wasm_logger::init(wasm_logger::Config::new(log::Level::Debug));
  15. console_error_panic_hook::set_once();
  16. wasm_bindgen_futures::spawn_local(WebsysRenderer::start(App));
  17. }
  18. enum Operator {
  19. Add,
  20. Sub,
  21. Mul,
  22. Div,
  23. }
  24. static App: FC<()> = |cx| {
  25. let (cur_val, set_cur_val) = use_state_classic(&cx, || 0.0_f64);
  26. let (operator, set_operator) = use_state_classic(&cx, || None as Option<Operator>);
  27. let (display_value, set_display_value) = use_state_classic(&cx, || "0".to_string());
  28. let clear_display = display_value.eq("0");
  29. let clear_text = if clear_display { "C" } else { "AC" };
  30. let input_digit = move |num: u8| {
  31. let mut new = if operator.is_some() {
  32. String::new()
  33. } else if display_value == "0" {
  34. String::new()
  35. } else {
  36. display_value.clone()
  37. };
  38. if operator.is_some() {
  39. let val = display_value.parse::<f64>().unwrap();
  40. set_cur_val(val);
  41. }
  42. new.push_str(num.to_string().as_str());
  43. set_display_value(new);
  44. };
  45. let input_dot = move || {
  46. let mut new = display_value.clone();
  47. new.push_str(".");
  48. set_display_value(new);
  49. };
  50. let perform_operation = move || {
  51. if let Some(op) = operator.as_ref() {
  52. let rhs = display_value.parse::<f64>().unwrap();
  53. let new_val = match op {
  54. Operator::Add => *cur_val + rhs,
  55. Operator::Sub => *cur_val - rhs,
  56. Operator::Mul => *cur_val * rhs,
  57. Operator::Div => *cur_val / rhs,
  58. };
  59. set_cur_val(new_val);
  60. set_display_value(new_val.to_string());
  61. set_operator(None);
  62. }
  63. };
  64. let toggle_sign = move |_| {
  65. if display_value.starts_with("-") {
  66. set_display_value(display_value.trim_start_matches("-").to_string())
  67. } else {
  68. set_display_value(format!("-{}", *display_value))
  69. }
  70. };
  71. let toggle_percent = move |_| todo!();
  72. let clear_key = move |_| {
  73. set_display_value("0".to_string());
  74. if !clear_display {
  75. set_operator(None);
  76. set_cur_val(0.0);
  77. }
  78. };
  79. let keydownhandler = move |evt: KeyboardEvent| match evt.key_code() {
  80. KeyCode::Backspace => {
  81. let mut new = display_value.clone();
  82. if !new.as_str().eq("0") {
  83. new.pop();
  84. }
  85. set_display_value(new);
  86. }
  87. KeyCode::_0 => input_digit(0),
  88. KeyCode::_1 => input_digit(1),
  89. KeyCode::_2 => input_digit(2),
  90. KeyCode::_3 => input_digit(3),
  91. KeyCode::_4 => input_digit(4),
  92. KeyCode::_5 => input_digit(5),
  93. KeyCode::_6 => input_digit(6),
  94. KeyCode::_7 => input_digit(7),
  95. KeyCode::_8 => input_digit(8),
  96. KeyCode::_9 => input_digit(9),
  97. KeyCode::Add => set_operator(Some(Operator::Add)),
  98. KeyCode::Subtract => set_operator(Some(Operator::Sub)),
  99. KeyCode::Divide => set_operator(Some(Operator::Div)),
  100. KeyCode::Multiply => set_operator(Some(Operator::Mul)),
  101. _ => {}
  102. };
  103. cx.render(rsx! {
  104. div {
  105. id: "wrapper"
  106. div { class: "app" onkeydown: {keydownhandler}
  107. style { "{STYLE}" }
  108. div { class: "calculator",
  109. CalculatorDisplay { val: &display_value}
  110. div { class: "calculator-keypad"
  111. div { class: "input-keys"
  112. div { class: "function-keys"
  113. CalculatorKey { name: "key-clear", onclick: {clear_key} "{clear_text}" }
  114. CalculatorKey { name: "key-sign", onclick: {toggle_sign}, "±"}
  115. CalculatorKey { name: "key-percent", onclick: {toggle_percent} "%"}
  116. }
  117. div { class: "digit-keys"
  118. CalculatorKey { name: "key-0", onclick: move |_| input_digit(0), "0" }
  119. CalculatorKey { name: "key-dot", onclick: move |_| input_dot(), "●" }
  120. {(1..10).map(move |k| rsx!{
  121. CalculatorKey { key: "{k}", name: "key-{k}", onclick: move |_| input_digit(k), "{k}" }
  122. })}
  123. }
  124. }
  125. div { class: "operator-keys"
  126. CalculatorKey { name: "key-divide", onclick: move |_| set_operator(Some(Operator::Div)) "÷" }
  127. CalculatorKey { name: "key-multiply", onclick: move |_| set_operator(Some(Operator::Mul)) "×" }
  128. CalculatorKey { name: "key-subtract", onclick: move |_| set_operator(Some(Operator::Sub)) "−" }
  129. CalculatorKey { name: "key-add", onclick: move |_| set_operator(Some(Operator::Add)) "+" }
  130. CalculatorKey { name: "key-equals", onclick: move |_| perform_operation() "=" }
  131. }
  132. }
  133. }
  134. }
  135. }
  136. })
  137. };
  138. #[derive(Props)]
  139. struct CalculatorKeyProps<'a> {
  140. /// Name!
  141. name: &'static str,
  142. /// Click!
  143. onclick: &'a dyn Fn(MouseEvent),
  144. }
  145. fn CalculatorKey<'a>(cx: Context<'a, CalculatorKeyProps>) -> VNode<'a> {
  146. cx.render(rsx! {
  147. button {
  148. class: "calculator-key {cx.name}"
  149. onclick: {cx.onclick}
  150. {cx.children()}
  151. }
  152. })
  153. }
  154. #[derive(Props, PartialEq)]
  155. struct CalculatorDisplayProps<'a> {
  156. val: &'a str,
  157. }
  158. fn CalculatorDisplay<'a>(cx: Context<'a, CalculatorDisplayProps>) -> VNode<'a> {
  159. use separator::Separatable;
  160. // Todo, add float support to the num-format crate
  161. let formatted = cx.val.parse::<f64>().unwrap().separated_string();
  162. // TODO: make it autoscaling with css
  163. cx.render(rsx! {
  164. div { class: "calculator-display"
  165. div { class: "auto-scaling-text", "{display_value}" }
  166. }
  167. })
  168. }