model.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. //! Example: Calculator
  2. //! -------------------
  3. //!
  4. //! Some components benefit through the use of "Models". Models are a single block of encapsulated state that allow mutative
  5. //! methods to be performed on them. Dioxus exposes the ability to use the model pattern through the "use_model" hook.
  6. //!
  7. //! Models are commonly used in the "Model-View-Component" approach for building UI state.
  8. //!
  9. //! `use_model` is basically just a fancy wrapper around set_state, but saves a "working copy" of the new state behind a
  10. //! RefCell. To modify the working copy, you need to call "get_mut" which returns the RefMut. This makes it easy to write
  11. //! fully encapsulated apps that retain a certain feel of native Rusty-ness. A calculator app is a good example of when this
  12. //! is useful.
  13. //!
  14. //! Do note that "get_mut" returns a `RefMut` (a lock over a RefCell). If two `RefMut`s are held at the same time (ie in a loop)
  15. //! the RefCell will panic and crash. You can use `try_get_mut` or `.modify` to avoid this problem, or just not hold two
  16. //! RefMuts at the same time.
  17. use dioxus::events::on::*;
  18. use dioxus::prelude::*;
  19. const STYLE: &str = include_str!("./assets/calculator.css");
  20. fn main() {
  21. dioxus::desktop::launch(App, |cfg| {
  22. cfg.title("Calculator Demo").resizable(false).size(350, 550)
  23. });
  24. }
  25. enum Operator {
  26. Add,
  27. Sub,
  28. Mul,
  29. Div,
  30. }
  31. static App: FC<()> = |cx| {
  32. let (cur_val, set_cur_val) = use_state_classic(cx, || 0.0_f64);
  33. let (operator, set_operator) = use_state_classic(cx, || None as Option<Operator>);
  34. let (display_value, set_display_value) = use_state_classic(cx, || "0".to_string());
  35. let clear_display = display_value.eq("0");
  36. let clear_text = if clear_display { "C" } else { "AC" };
  37. let input_digit = move |num: u8| {
  38. let mut new = if operator.is_some() {
  39. String::new()
  40. } else if display_value == "0" {
  41. String::new()
  42. } else {
  43. display_value.clone()
  44. };
  45. if operator.is_some() {
  46. let val = display_value.parse::<f64>().unwrap();
  47. set_cur_val(val);
  48. }
  49. new.push_str(num.to_string().as_str());
  50. set_display_value(new);
  51. };
  52. let input_dot = move || {
  53. let mut new = display_value.clone();
  54. new.push_str(".");
  55. set_display_value(new);
  56. };
  57. let perform_operation = move || {
  58. if let Some(op) = operator.as_ref() {
  59. let rhs = display_value.parse::<f64>().unwrap();
  60. let new_val = match op {
  61. Operator::Add => *cur_val + rhs,
  62. Operator::Sub => *cur_val - rhs,
  63. Operator::Mul => *cur_val * rhs,
  64. Operator::Div => *cur_val / rhs,
  65. };
  66. set_cur_val(new_val);
  67. set_display_value(new_val.to_string());
  68. set_operator(None);
  69. }
  70. };
  71. let toggle_sign = move |_| {
  72. if display_value.starts_with("-") {
  73. set_display_value(display_value.trim_start_matches("-").to_string())
  74. } else {
  75. set_display_value(format!("-{}", *display_value))
  76. }
  77. };
  78. let toggle_percent = move |_| todo!();
  79. let clear_key = move |_| {
  80. set_display_value("0".to_string());
  81. if !clear_display {
  82. set_operator(None);
  83. set_cur_val(0.0);
  84. }
  85. };
  86. let keydownhandler = move |evt: KeyboardEvent| match evt.key_code() {
  87. KeyCode::Backspace => {
  88. let mut new = display_value.clone();
  89. if !new.as_str().eq("0") {
  90. new.pop();
  91. }
  92. set_display_value(new);
  93. }
  94. KeyCode::_0 => input_digit(0),
  95. KeyCode::_1 => input_digit(1),
  96. KeyCode::_2 => input_digit(2),
  97. KeyCode::_3 => input_digit(3),
  98. KeyCode::_4 => input_digit(4),
  99. KeyCode::_5 => input_digit(5),
  100. KeyCode::_6 => input_digit(6),
  101. KeyCode::_7 => input_digit(7),
  102. KeyCode::_8 => input_digit(8),
  103. KeyCode::_9 => input_digit(9),
  104. KeyCode::Add => set_operator(Some(Operator::Add)),
  105. KeyCode::Subtract => set_operator(Some(Operator::Sub)),
  106. KeyCode::Divide => set_operator(Some(Operator::Div)),
  107. KeyCode::Multiply => set_operator(Some(Operator::Mul)),
  108. _ => {}
  109. };
  110. cx.render(rsx! {
  111. div {
  112. id: "wrapper"
  113. div { class: "app" onkeydown: {keydownhandler}
  114. style { "{STYLE}" }
  115. div { class: "calculator",
  116. CalculatorDisplay { val: &display_value}
  117. div { class: "calculator-keypad"
  118. div { class: "input-keys"
  119. div { class: "function-keys"
  120. CalculatorKey { name: "key-clear", onclick: {clear_key} "{clear_text}" }
  121. CalculatorKey { name: "key-sign", onclick: {toggle_sign}, "±"}
  122. CalculatorKey { name: "key-percent", onclick: {toggle_percent} "%"}
  123. }
  124. div { class: "digit-keys"
  125. CalculatorKey { name: "key-0", onclick: move |_| input_digit(0), "0" }
  126. CalculatorKey { name: "key-dot", onclick: move |_| input_dot(), "●" }
  127. {(1..10).map(move |k| rsx!{
  128. CalculatorKey { key: "{k}", name: "key-{k}", onclick: move |_| input_digit(k), "{k}" }
  129. })}
  130. }
  131. }
  132. div { class: "operator-keys"
  133. CalculatorKey { name: "key-divide", onclick: move |_| set_operator(Some(Operator::Div)) "÷" }
  134. CalculatorKey { name: "key-multiply", onclick: move |_| set_operator(Some(Operator::Mul)) "×" }
  135. CalculatorKey { name: "key-subtract", onclick: move |_| set_operator(Some(Operator::Sub)) "−" }
  136. CalculatorKey { name: "key-add", onclick: move |_| set_operator(Some(Operator::Add)) "+" }
  137. CalculatorKey { name: "key-equals", onclick: move |_| perform_operation() "=" }
  138. }
  139. }
  140. }
  141. }
  142. }
  143. })
  144. };
  145. #[derive(Props)]
  146. struct CalculatorKeyProps<'a> {
  147. /// Name!
  148. name: &'static str,
  149. /// Click!
  150. onclick: &'a dyn Fn(MouseEvent),
  151. }
  152. fn CalculatorKey<'a, 'r>(cx: Context<'a, CalculatorKeyProps<'r>>) -> VNode<'a> {
  153. cx.render(rsx! {
  154. button {
  155. class: "calculator-key {cx.name}"
  156. onclick: {cx.onclick}
  157. {cx.children()}
  158. }
  159. })
  160. }
  161. #[derive(Props, PartialEq)]
  162. struct CalculatorDisplayProps<'a> {
  163. val: &'a str,
  164. }
  165. fn CalculatorDisplay<'a>(cx: Context<'a, CalculatorDisplayProps>) -> VNode<'a> {
  166. use separator::Separatable;
  167. // Todo, add float support to the num-format crate
  168. let formatted = cx.val.parse::<f64>().unwrap().separated_string();
  169. // TODO: make it autoscaling with css
  170. cx.render(rsx! {
  171. div { class: "calculator-display"
  172. div { class: "auto-scaling-text", "{formatted}" }
  173. }
  174. })
  175. }