todomvc.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. //! The typical TodoMVC app, implemented in Dioxus.
  2. use dioxus::prelude::*;
  3. use dioxus_elements::input_data::keyboard_types::Key;
  4. use std::collections::HashMap;
  5. fn main() {
  6. launch(app);
  7. }
  8. #[derive(PartialEq, Eq, Clone, Copy)]
  9. enum FilterState {
  10. All,
  11. Active,
  12. Completed,
  13. }
  14. #[derive(Debug, PartialEq, Eq)]
  15. struct TodoItem {
  16. id: u32,
  17. checked: bool,
  18. contents: String,
  19. }
  20. fn app() -> Element {
  21. // We store the todos in a HashMap in a Signal.
  22. // Each key is the id of the todo, and the value is the todo itself.
  23. let mut todos = use_signal(HashMap::<u32, TodoItem>::new);
  24. let filter = use_signal(|| FilterState::All);
  25. // We use a simple memoized signal to calculate the number of active todos.
  26. // Whenever the todos change, the active_todo_count will be recalculated.
  27. let active_todo_count =
  28. use_memo(move || todos.read().values().filter(|item| !item.checked).count());
  29. // We use a memoized signal to filter the todos based on the current filter state.
  30. // Whenever the todos or filter change, the filtered_todos will be recalculated.
  31. // Note that we're only storing the IDs of the todos, not the todos themselves.
  32. let filtered_todos = use_memo(move || {
  33. let mut filtered_todos = todos
  34. .read()
  35. .iter()
  36. .filter(|(_, item)| match filter() {
  37. FilterState::All => true,
  38. FilterState::Active => !item.checked,
  39. FilterState::Completed => item.checked,
  40. })
  41. .map(|f| *f.0)
  42. .collect::<Vec<_>>();
  43. filtered_todos.sort_unstable();
  44. filtered_todos
  45. });
  46. // Toggle all the todos to the opposite of the current state.
  47. // If all todos are checked, uncheck them all. If any are unchecked, check them all.
  48. let toggle_all = move |_| {
  49. let check = active_todo_count() != 0;
  50. for (_, item) in todos.write().iter_mut() {
  51. item.checked = check;
  52. }
  53. };
  54. rsx! {
  55. style { {include_str!("./assets/todomvc.css")} }
  56. section { class: "todoapp",
  57. TodoHeader { todos }
  58. section { class: "main",
  59. if !todos.read().is_empty() {
  60. input {
  61. id: "toggle-all",
  62. class: "toggle-all",
  63. r#type: "checkbox",
  64. onchange: toggle_all,
  65. checked: active_todo_count() == 0,
  66. }
  67. label { r#for: "toggle-all" }
  68. }
  69. // Render the todos using the filtered_todos signal
  70. // We pass the ID into the TodoEntry component so it can access the todo from the todos signal.
  71. // Since we store the todos in a signal too, we also need to send down the todo list
  72. ul { class: "todo-list",
  73. for id in filtered_todos() {
  74. TodoEntry { key: "{id}", id, todos }
  75. }
  76. }
  77. // We only show the footer if there are todos.
  78. if !todos.read().is_empty() {
  79. ListFooter { active_todo_count, todos, filter }
  80. }
  81. }
  82. }
  83. // A simple info footer
  84. footer { class: "info",
  85. p { "Double-click to edit a todo" }
  86. p { "Created by " a { href: "http://github.com/jkelleyrtp/", "jkelleyrtp" } }
  87. p { "Part of " a { href: "http://todomvc.com", "TodoMVC" } }
  88. }
  89. }
  90. }
  91. #[component]
  92. fn TodoHeader(mut todos: Signal<HashMap<u32, TodoItem>>) -> Element {
  93. let mut draft = use_signal(|| "".to_string());
  94. let mut todo_id = use_signal(|| 0);
  95. let onkeydown = move |evt: KeyboardEvent| {
  96. if evt.key() == Key::Enter && !draft.read().is_empty() {
  97. let id = todo_id();
  98. let todo = TodoItem {
  99. id,
  100. checked: false,
  101. contents: draft.to_string(),
  102. };
  103. todos.write().insert(id, todo);
  104. todo_id += 1;
  105. draft.set("".to_string());
  106. }
  107. };
  108. rsx! {
  109. header { class: "header",
  110. h1 { "todos" }
  111. input {
  112. class: "new-todo",
  113. placeholder: "What needs to be done?",
  114. value: "{draft}",
  115. autofocus: "true",
  116. oninput: move |evt| draft.set(evt.value()),
  117. onkeydown,
  118. }
  119. }
  120. }
  121. }
  122. /// A single todo entry
  123. /// This takes the ID of the todo and the todos signal as props
  124. /// We can use these together to memoize the todo contents and checked state
  125. #[component]
  126. fn TodoEntry(mut todos: Signal<HashMap<u32, TodoItem>>, id: u32) -> Element {
  127. let mut is_editing = use_signal(|| false);
  128. // To avoid re-rendering this component when the todo list changes, we isolate our reads to memos
  129. // This way, the component will only re-render when the contents of the todo change, or when the editing state changes.
  130. // This does involve taking a local clone of the todo contents, but it allows us to prevent this component from re-rendering
  131. let checked = use_memo(move || todos.read().get(&id).unwrap().checked);
  132. let contents = use_memo(move || todos.read().get(&id).unwrap().contents.clone());
  133. rsx! {
  134. li {
  135. // Dioxus lets you use if statements in rsx to conditionally render attributes
  136. // These will get merged into a single class attribute
  137. class: if checked() { "completed" },
  138. class: if is_editing() { "editing" },
  139. // Some basic controls for the todo
  140. div { class: "view",
  141. input {
  142. class: "toggle",
  143. r#type: "checkbox",
  144. id: "cbg-{id}",
  145. checked: "{checked}",
  146. oninput: move |evt| todos.write().get_mut(&id).unwrap().checked = evt.checked(),
  147. }
  148. label {
  149. r#for: "cbg-{id}",
  150. ondoubleclick: move |_| is_editing.set(true),
  151. prevent_default: "onclick",
  152. "{contents}"
  153. }
  154. button {
  155. class: "destroy",
  156. onclick: move |_| { todos.write().remove(&id); },
  157. prevent_default: "onclick"
  158. }
  159. }
  160. // Only render the actual input if we're editing
  161. if is_editing() {
  162. input {
  163. class: "edit",
  164. value: "{contents}",
  165. oninput: move |evt| todos.write().get_mut(&id).unwrap().contents = evt.value(),
  166. autofocus: "true",
  167. onfocusout: move |_| is_editing.set(false),
  168. onkeydown: move |evt| {
  169. match evt.key() {
  170. Key::Enter | Key::Escape | Key::Tab => is_editing.set(false),
  171. _ => {}
  172. }
  173. }
  174. }
  175. }
  176. }
  177. }
  178. }
  179. #[component]
  180. fn ListFooter(
  181. mut todos: Signal<HashMap<u32, TodoItem>>,
  182. active_todo_count: ReadOnlySignal<usize>,
  183. mut filter: Signal<FilterState>,
  184. ) -> Element {
  185. // We use a memoized signal to calculate whether we should show the "Clear completed" button.
  186. // This will recompute whenever the todos change, and if the value is true, the button will be shown.
  187. let show_clear_completed = use_memo(move || todos.read().values().any(|todo| todo.checked));
  188. rsx! {
  189. footer { class: "footer",
  190. span { class: "todo-count",
  191. strong { "{active_todo_count} " }
  192. span {
  193. match active_todo_count() {
  194. 1 => "item",
  195. _ => "items",
  196. }
  197. " left"
  198. }
  199. }
  200. ul { class: "filters",
  201. for (state , state_text , url) in [
  202. (FilterState::All, "All", "#/"),
  203. (FilterState::Active, "Active", "#/active"),
  204. (FilterState::Completed, "Completed", "#/completed"),
  205. ] {
  206. li {
  207. a {
  208. href: url,
  209. class: if filter() == state { "selected" },
  210. onclick: move |_| filter.set(state),
  211. prevent_default: "onclick",
  212. {state_text}
  213. }
  214. }
  215. }
  216. }
  217. if show_clear_completed() {
  218. button {
  219. class: "clear-completed",
  220. onclick: move |_| todos.write().retain(|_, todo| !todo.checked),
  221. "Clear completed"
  222. }
  223. }
  224. }
  225. }
  226. }