todomvc.rs 8.9 KB

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