diff --git a/src/App.tsx b/src/App.tsx index 81e011f432..332aa14ba6 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,26 +1,305 @@ -/* eslint-disable max-len */ -/* eslint-disable jsx-a11y/control-has-associated-label */ -import React from 'react'; +import React, { useEffect, useMemo, useRef, useState } from 'react'; +import { ErrorNotification } from './components/ErrorNotification'; +import { Footer } from './components/Footer'; +import { Header } from './components/Header'; +import { TodoList } from './components/TodoList'; import { UserWarning } from './UserWarning'; +import { + USER_ID, + createTodo, + deleteTodo, + getTodos, + updateTodo, +} from './api/todos'; +import { Filter } from './types/Filter'; +import { TempTodo } from './types/TempTodo'; +import { Todo } from './types/Todo'; -const USER_ID = 0; +const TEMP_TODO_ID = 0; + +const getFilterFromHash = (): Filter => { + switch (window.location.hash) { + case '#/active': + return 'active'; + + case '#/completed': + return 'completed'; + + default: + return 'all'; + } +}; export const App: React.FC = () => { + const [todos, setTodos] = useState([]); + const [filter, setFilter] = useState(getFilterFromHash); + const [newTodoTitle, setNewTodoTitle] = useState(''); + const [tempTodo, setTempTodo] = useState(null); + const [loadingTodoIds, setLoadingTodoIds] = useState([]); + const [errorMessage, setErrorMessage] = useState(''); + const [editingTodoId, setEditingTodoId] = useState(null); + const [editingTitle, setEditingTitle] = useState(''); + + const newTodoField = useRef(null); + const errorTimerId = useRef(null); + const editingCanceled = useRef(false); + + const hideError = React.useCallback(() => { + setErrorMessage(''); + + if (errorTimerId.current) { + window.clearTimeout(errorTimerId.current); + errorTimerId.current = null; + } + }, []); + + const showError = React.useCallback( + (message: string) => { + hideError(); + setErrorMessage(message); + + errorTimerId.current = window.setTimeout(() => { + setErrorMessage(''); + errorTimerId.current = null; + }, 3000); + }, + [hideError], + ); + + const markTodoAsLoading = (todoId: number) => { + setLoadingTodoIds(currentIds => [...currentIds, todoId]); + }; + + const unmarkTodoAsLoading = (todoId: number) => { + setLoadingTodoIds(currentIds => currentIds.filter(id => id !== todoId)); + }; + + useEffect(() => { + const handleHashChange = () => setFilter(getFilterFromHash()); + + window.addEventListener('hashchange', handleHashChange); + + return () => { + window.removeEventListener('hashchange', handleHashChange); + }; + }, []); + + useEffect(() => { + hideError(); + + getTodos() + .then(setTodos) + .catch(() => showError('Unable to load todos')); + + return () => { + if (errorTimerId.current) { + window.clearTimeout(errorTimerId.current); + } + }; + }, [hideError, showError]); + + useEffect(() => { + newTodoField.current?.focus(); + }, [todos.length, tempTodo, errorMessage]); + + const visibleTodos = useMemo(() => { + return todos.filter(todo => { + switch (filter) { + case 'active': + return !todo.completed; + + case 'completed': + return todo.completed; + + default: + return true; + } + }); + }, [todos, filter]); + + const activeTodosCount = todos.filter(todo => !todo.completed).length; + const completedTodosCount = todos.length - activeTodosCount; + const allTodosCompleted = todos.length > 0 && activeTodosCount === 0; + const isAdding = Boolean(tempTodo); + + const handleAddTodo = (event: React.FormEvent) => { + event.preventDefault(); + + const trimmedTitle = newTodoTitle.trim(); + + if (!trimmedTitle) { + showError('Title should not be empty'); + + return; + } + + hideError(); + setTempTodo({ + id: TEMP_TODO_ID, + userId: USER_ID, + title: trimmedTitle, + completed: false, + }); + + createTodo(trimmedTitle) + .then(todo => { + setTodos(currentTodos => [...currentTodos, todo]); + setNewTodoTitle(''); + }) + .catch(() => showError('Unable to add a todo')) + .finally(() => setTempTodo(null)); + }; + + const handleDeleteTodo = (todoId: number) => { + hideError(); + markTodoAsLoading(todoId); + + return deleteTodo(todoId) + .then(() => { + setTodos(currentTodos => + currentTodos.filter(todo => todo.id !== todoId), + ); + }) + .catch(error => { + showError('Unable to delete a todo'); + throw error; + }) + .finally(() => unmarkTodoAsLoading(todoId)); + }; + + const handleUpdateTodo = (todoId: number, data: Partial) => { + hideError(); + markTodoAsLoading(todoId); + + return updateTodo(todoId, data) + .then(updatedTodo => { + setTodos(currentTodos => + currentTodos.map(todo => (todo.id === todoId ? updatedTodo : todo)), + ); + }) + .catch(error => { + showError('Unable to update a todo'); + throw error; + }) + .finally(() => unmarkTodoAsLoading(todoId)); + }; + + const handleToggleTodo = (todo: Todo) => { + handleUpdateTodo(todo.id, { completed: !todo.completed }).catch(() => {}); + }; + + const handleToggleAll = () => { + const newCompletedStatus = !allTodosCompleted; + + todos + .filter(todo => todo.completed !== newCompletedStatus) + .forEach(todo => { + handleUpdateTodo(todo.id, { completed: newCompletedStatus }).catch( + () => {}, + ); + }); + }; + + const startEditing = (todo: Todo | TempTodo) => { + if (todo.id === TEMP_TODO_ID) { + return; + } + + editingCanceled.current = false; + setEditingTodoId(todo.id); + setEditingTitle(todo.title); + }; + + const cancelEditing = () => { + editingCanceled.current = true; + setEditingTodoId(null); + setEditingTitle(''); + }; + + const submitTodoTitle = (todo: Todo) => { + if (editingCanceled.current) { + editingCanceled.current = false; + + return; + } + + const trimmedTitle = editingTitle.trim(); + + if (trimmedTitle === todo.title) { + cancelEditing(); + + return; + } + + if (!trimmedTitle) { + handleDeleteTodo(todo.id) + .then(cancelEditing) + .catch(() => {}); + + return; + } + + handleUpdateTodo(todo.id, { title: trimmedTitle }) + .then(cancelEditing) + .catch(() => {}); + }; + + const handleClearCompleted = () => { + todos + .filter(todo => todo.completed) + .forEach(todo => { + handleDeleteTodo(todo.id).catch(() => {}); + }); + }; + if (!USER_ID) { return ; } return ( -
-

- Copy all you need from the prev task: -
- - React Todo App - Add and Delete - -

- -

Styles are already copied

-
+
+

todos

+ +
+
+ + {(todos.length > 0 || tempTodo) && ( + handleDeleteTodo(todoId).catch(() => {})} + onStartEditing={startEditing} + onEditingTitleChange={setEditingTitle} + onCancelEditing={cancelEditing} + onSubmitTodoTitle={submitTodoTitle} + /> + )} + + {todos.length > 0 && ( +
+ )} +
+ + +
); }; diff --git a/src/api/todos.ts b/src/api/todos.ts new file mode 100644 index 0000000000..cffb2c5a21 --- /dev/null +++ b/src/api/todos.ts @@ -0,0 +1,24 @@ +import { Todo } from '../types/Todo'; +import { client } from '../utils/fetchClient'; + +export const USER_ID = 4351; + +export const getTodos = () => { + return client.get(`/todos?userId=${USER_ID}`); +}; + +export const createTodo = (title: string) => { + return client.post('/todos', { + userId: USER_ID, + title, + completed: false, + }); +}; + +export const deleteTodo = (todoId: number) => { + return client.delete(`/todos/${todoId}`); +}; + +export const updateTodo = (todoId: number, data: Partial) => { + return client.patch(`/todos/${todoId}`, data); +}; diff --git a/src/components/ErrorNotification.tsx b/src/components/ErrorNotification.tsx new file mode 100644 index 0000000000..31bff110c0 --- /dev/null +++ b/src/components/ErrorNotification.tsx @@ -0,0 +1,27 @@ +/* eslint-disable jsx-a11y/control-has-associated-label */ +import React from 'react'; + +type Props = { + errorMessage: string; + onHideError: () => void; +}; + +export const ErrorNotification: React.FC = ({ + errorMessage, + onHideError, +}) => ( +
+
+); diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx new file mode 100644 index 0000000000..27d9ea4369 --- /dev/null +++ b/src/components/Footer.tsx @@ -0,0 +1,58 @@ +import React from 'react'; +import { Filter } from '../types/Filter'; + +type Props = { + activeTodosCount: number; + completedTodosCount: number; + filter: Filter; + onClearCompleted: () => void; +}; + +export const Footer: React.FC = ({ + activeTodosCount, + completedTodosCount, + filter, + onClearCompleted, +}) => ( + +); diff --git a/src/components/Header.tsx b/src/components/Header.tsx new file mode 100644 index 0000000000..83e7535593 --- /dev/null +++ b/src/components/Header.tsx @@ -0,0 +1,48 @@ +/* eslint-disable jsx-a11y/control-has-associated-label */ +import React from 'react'; + +type Props = { + todosCount: number; + allTodosCompleted: boolean; + newTodoTitle: string; + isAdding: boolean; + newTodoField: React.RefObject; + onAddTodo: (event: React.FormEvent) => void; + onNewTodoTitleChange: (title: string) => void; + onToggleAll: () => void; +}; + +export const Header: React.FC = ({ + todosCount, + allTodosCompleted, + newTodoTitle, + isAdding, + newTodoField, + onAddTodo, + onNewTodoTitleChange, + onToggleAll, +}) => ( +
+ {todosCount > 0 && ( +
+); diff --git a/src/components/TodoItem.tsx b/src/components/TodoItem.tsx new file mode 100644 index 0000000000..0da5374dcc --- /dev/null +++ b/src/components/TodoItem.tsx @@ -0,0 +1,101 @@ +/* eslint-disable jsx-a11y/label-has-associated-control */ +/* eslint-disable jsx-a11y/control-has-associated-label */ +import React from 'react'; +import { Todo } from '../types/Todo'; +import { TempTodo } from '../types/TempTodo'; + +type Props = { + todo: Todo | TempTodo; + isTemp: boolean; + isLoading: boolean; + isEditing: boolean; + editingTitle: string; + onToggle: (todo: Todo) => void; + onDelete: (todoId: number) => void; + onStartEditing: (todo: Todo | TempTodo) => void; + onEditingTitleChange: (title: string) => void; + onCancelEditing: () => void; + onSubmitTitle: (todo: Todo) => void; +}; + +export const TodoItem: React.FC = ({ + todo, + isTemp, + isLoading, + isEditing, + editingTitle, + onToggle, + onDelete, + onStartEditing, + onEditingTitleChange, + onCancelEditing, + onSubmitTitle, +}) => ( +
+ + + {isEditing && !isTemp ? ( +
{ + event.preventDefault(); + onSubmitTitle(todo as Todo); + }} + > + onEditingTitleChange(event.target.value)} + onBlur={() => onSubmitTitle(todo as Todo)} + onKeyUp={event => { + if (event.key === 'Escape') { + onCancelEditing(); + } + }} + /> +
+ ) : ( + <> + onStartEditing(todo)} + > + {todo.title} + + + + + )} + +
+
+
+
+
+); diff --git a/src/components/TodoList.tsx b/src/components/TodoList.tsx new file mode 100644 index 0000000000..3b8c55b53c --- /dev/null +++ b/src/components/TodoList.tsx @@ -0,0 +1,62 @@ +import React from 'react'; +import { Todo } from '../types/Todo'; +import { TempTodo } from '../types/TempTodo'; +import { TodoItem } from './TodoItem'; + +type Props = { + todos: Todo[]; + tempTodo: TempTodo | null; + tempTodoId: number; + loadingTodoIds: number[]; + editingTodoId: number | null; + editingTitle: string; + onToggleTodo: (todo: Todo) => void; + onDeleteTodo: (todoId: number) => void; + onStartEditing: (todo: Todo | TempTodo) => void; + onEditingTitleChange: (title: string) => void; + onCancelEditing: () => void; + onSubmitTodoTitle: (todo: Todo) => void; +}; + +export const TodoList: React.FC = ({ + todos, + tempTodo, + tempTodoId, + loadingTodoIds, + editingTodoId, + editingTitle, + onToggleTodo, + onDeleteTodo, + onStartEditing, + onEditingTitleChange, + onCancelEditing, + onSubmitTodoTitle, +}) => { + const todosToRender = tempTodo ? [...todos, tempTodo] : todos; + + return ( +
+ {todosToRender.map(todo => { + const isTemp = todo.id === tempTodoId; + const isLoading = isTemp || loadingTodoIds.includes(todo.id); + + return ( + + ); + })} +
+ ); +}; diff --git a/src/types/Filter.ts b/src/types/Filter.ts new file mode 100644 index 0000000000..5d90d45a1b --- /dev/null +++ b/src/types/Filter.ts @@ -0,0 +1 @@ +export type Filter = 'all' | 'active' | 'completed'; diff --git a/src/types/TempTodo.ts b/src/types/TempTodo.ts new file mode 100644 index 0000000000..7c8bc556a9 --- /dev/null +++ b/src/types/TempTodo.ts @@ -0,0 +1,3 @@ +import { Todo } from './Todo'; + +export type TempTodo = Omit & { id: number }; diff --git a/src/types/Todo.ts b/src/types/Todo.ts new file mode 100644 index 0000000000..3f52a5fdde --- /dev/null +++ b/src/types/Todo.ts @@ -0,0 +1,6 @@ +export interface Todo { + id: number; + userId: number; + title: string; + completed: boolean; +} diff --git a/src/utils/fetchClient.ts b/src/utils/fetchClient.ts new file mode 100644 index 0000000000..708ac4c17b --- /dev/null +++ b/src/utils/fetchClient.ts @@ -0,0 +1,46 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +const BASE_URL = 'https://mate.academy/students-api'; + +// returns a promise resolved after a given delay +function wait(delay: number) { + return new Promise(resolve => { + setTimeout(resolve, delay); + }); +} + +// To have autocompletion and avoid mistypes +type RequestMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE'; + +function request( + url: string, + method: RequestMethod = 'GET', + data: any = null, // we can send any data to the server +): Promise { + const options: RequestInit = { method }; + + if (data) { + // We add body and Content-Type only for the requests with data + options.body = JSON.stringify(data); + options.headers = { + 'Content-Type': 'application/json; charset=UTF-8', + }; + } + + // DON'T change the delay it is required for tests + return wait(100) + .then(() => fetch(BASE_URL + url, options)) + .then(response => { + if (!response.ok) { + throw new Error(); + } + + return response.json(); + }); +} + +export const client = { + get: (url: string) => request(url), + post: (url: string, data: any) => request(url, 'POST', data), + patch: (url: string, data: any) => request(url, 'PATCH', data), + delete: (url: string) => request(url, 'DELETE'), +};