todomvc.rs 8.9 KB

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