1
0

todomvc.rs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. //! The typical TodoMVC app, implemented in Dioxus.
  2. use dioxus::prelude::*;
  3. use std::collections::HashMap;
  4. const STYLE: &str = include_str!("../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. style {
  54. {STYLE}
  55. }
  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 {
  87. "Created by "
  88. a { href: "http://github.com/jkelleyrtp/", "jkelleyrtp" }
  89. }
  90. p {
  91. "Part of "
  92. a { href: "http://todomvc.com", "TodoMVC" }
  93. }
  94. }
  95. }
  96. }
  97. #[component]
  98. fn TodoHeader(mut todos: Signal<HashMap<u32, TodoItem>>) -> Element {
  99. let mut draft = use_signal(|| "".to_string());
  100. let mut todo_id = use_signal(|| 0);
  101. let onkeydown = move |evt: KeyboardEvent| {
  102. if evt.key() == Key::Enter && !draft.read().is_empty() {
  103. let id = todo_id();
  104. let todo = TodoItem {
  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. onclick: |evt| evt.prevent_default(),
  157. "{contents}"
  158. }
  159. button {
  160. class: "destroy",
  161. onclick: move |evt| {
  162. evt.prevent_default();
  163. todos.write().remove(&id);
  164. },
  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 |evt| {
  218. evt.prevent_default();
  219. filter.set(state)
  220. },
  221. {state_text}
  222. }
  223. }
  224. }
  225. }
  226. if show_clear_completed() {
  227. button {
  228. class: "clear-completed",
  229. onclick: move |_| todos.write().retain(|_, todo| !todo.checked),
  230. "Clear completed"
  231. }
  232. }
  233. }
  234. }
  235. }