model.rs 7.2 KB

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