calculator.rs 6.7 KB

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