diff --git a/src/App.tsx b/src/App.tsx index 81e011f432..5fbeeff5fe 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,26 +1,185 @@ /* eslint-disable max-len */ +/* eslint-disable jsx-a11y/label-has-associated-control */ /* eslint-disable jsx-a11y/control-has-associated-label */ -import React from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { UserWarning } from './UserWarning'; - -const USER_ID = 0; +import { + createTodo, + deleteTodo, + getTodos, + updateTodo, + USER_ID, +} from './api/todos'; +import { Todo } from './types/Todo'; +import { ErrorNotification } from './components/ErrorNotification'; +import { FilterType } from './types/FilterType'; +import { TodoList } from './components/TodoList'; +import { Footer } from './components/Footer'; +import { Header } from './components/Header'; +import { ErrorType } from './types/ErrorType'; export const App: React.FC = () => { + const [todos, setTodos] = useState([]); + const [errorTodos, setErrorTodos] = useState(ErrorType.NoErrors); + const [status, setStatus] = useState(FilterType.All); + const [isLoading, setIsLoading] = useState(true); + const [loadingTodosIds, setLoadingTodosIds] = useState([]); + + const [tempTodo, setTempTodo] = useState(null); + + useEffect(() => { + setIsLoading(true); + getTodos() + .then(setTodos) + .catch(() => { + setErrorTodos(ErrorType.Loading); + }) + .finally(() => { + setIsLoading(false); + }); + }, []); + + const visibleTodos = todos.filter(todo => { + switch (status) { + case FilterType.Completed: + return todo.completed; + case FilterType.Active: + return !todo.completed; + default: + return true; + } + }); + + const activeTodosCount = useMemo( + () => todos.filter(todo => !todo.completed).length, + [todos], + ); + + const completedTodos = useMemo( + () => todos.filter(todo => todo.completed), + [todos], + ); + + const completedTodosCount = completedTodos.length; + + const handleErrorClose = useCallback(() => { + setErrorTodos(ErrorType.NoErrors); + }, []); + + const onAddTodo = useCallback( + async (newTodo: Omit): Promise => { + try { + const createdTodo = await createTodo(newTodo); + + setTodos(currentTodos => [...currentTodos, createdTodo]); + } catch (error) { + setErrorTodos(ErrorType.Add); + throw error; + } + }, + [], + ); + + const onDeleteTodo = useCallback(async (todoId: number) => { + setLoadingTodosIds(currentIds => [...currentIds, todoId]); + try { + await deleteTodo(todoId); + setTodos(currentTodos => currentTodos.filter(todo => todo.id !== todoId)); + } catch (error) { + setErrorTodos(ErrorType.Delete); + throw error; + } finally { + setLoadingTodosIds(currentIds => currentIds.filter(id => id !== todoId)); + } + }, []); + + const onDeleteAllCompleted = useCallback(() => { + completedTodos.forEach(completedTodo => { + onDeleteTodo(completedTodo.id); + }); + }, [completedTodos, onDeleteTodo]); + + const onUpdateTodo = useCallback(async (newTodo: Todo) => { + setLoadingTodosIds(currentIds => [...currentIds, newTodo.id]); + try { + const updatedTodo = await updateTodo(newTodo); + + setTodos(currentTodos => + currentTodos.map(todo => { + return todo.id === updatedTodo.id ? updatedTodo : todo; + }), + ); + } catch (error) { + setErrorTodos(ErrorType.Update); + throw error; + } finally { + setLoadingTodosIds(currentIds => + currentIds.filter(id => id !== newTodo.id), + ); + } + }, []); + + const onUpdateToggleAll = useCallback(() => { + todos.forEach(todo => { + if (todos.length === completedTodosCount) { + onUpdateTodo({ ...todo, completed: false }); + + return; + } + + if (todo.completed === false) { + onUpdateTodo({ ...todo, completed: true }); + + return; + } + }); + }, [todos, completedTodosCount, onUpdateTodo]); + 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 && ( + <> + + +
+ + )} +
+ + +
); }; diff --git a/src/api/todos.ts b/src/api/todos.ts new file mode 100644 index 0000000000..957a9b7e49 --- /dev/null +++ b/src/api/todos.ts @@ -0,0 +1,20 @@ +import { Todo } from '../types/Todo'; +import { client } from '../utils/fetchClient'; + +export const USER_ID = 2153; + +export const getTodos = () => { + return client.get(`/todos?userId=${USER_ID}`); +}; + +export const deleteTodo = (todoId: number) => { + return client.delete(`/todos/${todoId}`); +}; + +export const createTodo = (newTodo: Omit) => { + return client.post(`/todos`, newTodo); +}; + +export const updateTodo = ({ id, title, userId, completed }: Todo) => { + return client.patch(`/todos/${id}`, { id, title, userId, completed }); +}; diff --git a/src/components/ErrorNotification/ErrorNotification.tsx b/src/components/ErrorNotification/ErrorNotification.tsx new file mode 100644 index 0000000000..81acf2ae99 --- /dev/null +++ b/src/components/ErrorNotification/ErrorNotification.tsx @@ -0,0 +1,43 @@ +import React, { useEffect } from 'react'; +import cn from 'classnames'; +import { ErrorType } from '../../types/ErrorType'; + +type Props = { + error: string; + handleErrorClose: () => void; +}; + +export const ErrorNotification: React.FC = props => { + const { error, handleErrorClose } = props; + + useEffect(() => { + if (error === ErrorType.NoErrors) { + return; + } + + const timeoutId = setTimeout(() => { + handleErrorClose(); + }, 3000); + + return () => { + clearTimeout(timeoutId); + }; + }, [error, handleErrorClose]); + + return ( +
+
+ ); +}; diff --git a/src/components/ErrorNotification/index.tsx b/src/components/ErrorNotification/index.tsx new file mode 100644 index 0000000000..8cb4787920 --- /dev/null +++ b/src/components/ErrorNotification/index.tsx @@ -0,0 +1 @@ +export * from './ErrorNotification'; diff --git a/src/components/Footer/Footer.tsx b/src/components/Footer/Footer.tsx new file mode 100644 index 0000000000..2d27a22fe6 --- /dev/null +++ b/src/components/Footer/Footer.tsx @@ -0,0 +1,58 @@ +import React from 'react'; +import cn from 'classnames'; +import { FilterType } from '../../types/FilterType'; +import { Dispatch, SetStateAction } from 'react'; + +type Props = { + activeCount: number | undefined; + completedCount: number | undefined; + status: FilterType; + setStatus: Dispatch>; + onDeleteAllCompleted: () => void; +}; + +export const Footer: React.FC = props => { + const { + activeCount, + completedCount, + status, + setStatus, + onDeleteAllCompleted, + } = props; + + return ( + + ); +}; diff --git a/src/components/Footer/index.tsx b/src/components/Footer/index.tsx new file mode 100644 index 0000000000..ddcc5a9cd1 --- /dev/null +++ b/src/components/Footer/index.tsx @@ -0,0 +1 @@ +export * from './Footer'; diff --git a/src/components/Header/Header.tsx b/src/components/Header/Header.tsx new file mode 100644 index 0000000000..24d8c2570f --- /dev/null +++ b/src/components/Header/Header.tsx @@ -0,0 +1,106 @@ +/* eslint-disable max-len */ +import React, { + Dispatch, + SetStateAction, + useEffect, + useRef, + useState, +} from 'react'; +import cn from 'classnames'; +import { USER_ID } from '../../api/todos'; +import { Todo } from '../../types/Todo'; +import { ErrorType } from '../../types/ErrorType'; + +type Props = { + todos: Todo[]; + completedTodosCount: number; + onAddTodo: (newTodo: Omit) => Promise; + setErrorTodos: Dispatch>; + tempTodo: Todo | null; + setTempTodo: Dispatch>; + onUpdateToggleAll: () => void; +}; + +export const Header: React.FC = props => { + const { + todos, + completedTodosCount, + onAddTodo, + setErrorTodos, + tempTodo, + setTempTodo, + onUpdateToggleAll, + } = props; + + const [todoTitle, setTodoTitle] = useState(''); + const normalizedTitle = todoTitle.trim(); + + const inputNameRef = useRef(null); + + useEffect(() => { + if (inputNameRef.current) { + inputNameRef.current.focus(); + } + }, [todos, tempTodo]); + + const onResetTitle = () => { + setTodoTitle(''); + }; + + const handleSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + + if (!normalizedTitle) { + setErrorTodos(ErrorType.EmptyTitle); + + return; + } + + const newTodo = { + title: normalizedTitle, + userId: USER_ID, + completed: false, + }; + + setTempTodo({ + ...newTodo, + id: 0, + }); + + try { + await onAddTodo(newTodo); + onResetTitle(); + } catch (error) { + } finally { + setTempTodo(null); + } + }; + + return ( +
+ {todos.length > 0 && ( +
+ ); +}; diff --git a/src/components/Header/index.tsx b/src/components/Header/index.tsx new file mode 100644 index 0000000000..266dec8a1b --- /dev/null +++ b/src/components/Header/index.tsx @@ -0,0 +1 @@ +export * from './Header'; diff --git a/src/components/TodoComponent/TodoComponent.tsx b/src/components/TodoComponent/TodoComponent.tsx new file mode 100644 index 0000000000..e31e91f2d1 --- /dev/null +++ b/src/components/TodoComponent/TodoComponent.tsx @@ -0,0 +1,152 @@ +/* eslint-disable jsx-a11y/label-has-associated-control */ +import React, { + Dispatch, + SetStateAction, + useEffect, + useRef, + useState, +} from 'react'; +import cn from 'classnames'; + +import { Todo } from '../../types/Todo'; + +type Props = { + todo: Todo; + onDeleteTodo: (id: number) => Promise; + onUpdateTodo: (newTodo: Todo) => Promise; + isDataLoading: boolean; + isTodoLoading: boolean; + editingTodoId: number | null; + setEditingTodoId: Dispatch>; +}; + +export const TodoComponent: React.FC = props => { + const { + todo, + onDeleteTodo, + onUpdateTodo, + isDataLoading, + isTodoLoading, + editingTodoId, + setEditingTodoId, + } = props; + + const [newTitle, setNewTitle] = useState(todo.title); + + const inputNameRef = useRef(null); + + useEffect(() => { + if (inputNameRef.current) { + inputNameRef.current.focus(); + } + }, [editingTodoId]); + + const handleDelete = async (todoId: number) => { + try { + onDeleteTodo(todoId); + } catch (error) {} + }; + + const handleToggle = async (newTodo: Todo) => { + try { + await onUpdateTodo({ ...newTodo, completed: !newTodo.completed }); + } catch (error) {} + }; + + const handleEdit = async (newTodo: Todo) => { + try { + if (newTitle === newTodo.title) { + setEditingTodoId(null); + + return; + } + + if (newTitle.trim() === '') { + await onDeleteTodo(newTodo.id); + setEditingTodoId(null); + + return; + } + + await onUpdateTodo({ + ...newTodo, + title: newTitle.trim(), + }); + setEditingTodoId(null); + } catch (error) {} + }; + + const handleEscape = (event: React.KeyboardEvent) => { + if (event.key === 'Escape') { + setEditingTodoId(null); + setNewTitle(todo.title); + } + }; + + return ( +
+ + + {editingTodoId === todo.id ? ( +
{ + event.preventDefault(); + handleEdit(todo); + }} + onBlur={() => handleEdit(todo)} + > + { + setNewTitle(event.target.value); + }} + onKeyUp={handleEscape} + /> +
+ ) : ( + <> + setEditingTodoId(todo.id)} + > + {todo.title} + + + + )} + +
+
+
+
+
+ ); +}; diff --git a/src/components/TodoComponent/index.tsx b/src/components/TodoComponent/index.tsx new file mode 100644 index 0000000000..11cf5d69d2 --- /dev/null +++ b/src/components/TodoComponent/index.tsx @@ -0,0 +1 @@ +export * from './TodoComponent'; diff --git a/src/components/TodoList/TodoList.tsx b/src/components/TodoList/TodoList.tsx new file mode 100644 index 0000000000..d40f4f8e99 --- /dev/null +++ b/src/components/TodoList/TodoList.tsx @@ -0,0 +1,46 @@ +import React, { useState } from 'react'; + +import { Todo } from '../../types/Todo'; +import { TodoComponent } from '../TodoComponent'; +import { TodoTemp } from '../TodoTemp'; + +type Props = { + todos: Todo[]; + onDeleteTodo: (id: number) => Promise; + onUpdateTodo: (newTodo: Todo) => Promise; + isDataLoading: boolean; + loadingTodosIds: number[]; + tempTodo: Todo | null; +}; + +export const TodoList: React.FC = props => { + const { + todos, + onDeleteTodo, + onUpdateTodo, + isDataLoading, + loadingTodosIds, + tempTodo, + } = props; + + const [editingTodoId, setEditingTodoId] = useState(null); + + return ( +
+ {todos?.map(todo => ( + + ))} + + {tempTodo && } +
+ ); +}; diff --git a/src/components/TodoList/index.tsx b/src/components/TodoList/index.tsx new file mode 100644 index 0000000000..f239f43459 --- /dev/null +++ b/src/components/TodoList/index.tsx @@ -0,0 +1 @@ +export * from './TodoList'; diff --git a/src/components/TodoTemp/TodoTemp.tsx b/src/components/TodoTemp/TodoTemp.tsx new file mode 100644 index 0000000000..0ae1d4e051 --- /dev/null +++ b/src/components/TodoTemp/TodoTemp.tsx @@ -0,0 +1,37 @@ +/* eslint-disable jsx-a11y/label-has-associated-control */ +import React from 'react'; +import cn from 'classnames'; + +import { Todo } from '../../types/Todo'; + +type Props = { + todo: Todo; +}; + +export const TodoTemp: React.FC = props => { + const { todo } = props; + + return ( +
+ + + + {todo.title} + + +
+
+
+
+
+ ); +}; diff --git a/src/components/TodoTemp/index.tsx b/src/components/TodoTemp/index.tsx new file mode 100644 index 0000000000..c85ea5b4dd --- /dev/null +++ b/src/components/TodoTemp/index.tsx @@ -0,0 +1 @@ +export * from './TodoTemp'; diff --git a/src/types/ErrorType.ts b/src/types/ErrorType.ts new file mode 100644 index 0000000000..1ba1cf5fa5 --- /dev/null +++ b/src/types/ErrorType.ts @@ -0,0 +1,8 @@ +export enum ErrorType { + NoErrors = '', + Loading = 'Unable to load todos', + EmptyTitle = 'Title should not be empty', + Add = 'Unable to add a todo', + Delete = 'Unable to delete a todo', + Update = 'Unable to update a todo', +} diff --git a/src/types/FilterType.ts b/src/types/FilterType.ts new file mode 100644 index 0000000000..579c7f50ce --- /dev/null +++ b/src/types/FilterType.ts @@ -0,0 +1,5 @@ +export enum FilterType { + All = 'All', + Active = 'Active', + Completed = 'Completed', +} 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'), +};