diff --git a/README.md b/README.md index af7dae81f6..707755d7e9 100644 --- a/README.md +++ b/README.md @@ -41,4 +41,4 @@ Implement the ability to edit a todo title on double click: - Implement a solution following the [React task guideline](https://github.com/mate-academy/react_task-guideline#react-tasks-guideline). - Use the [React TypeScript cheat sheet](https://mate-academy.github.io/fe-program/js/extra/react-typescript). -- Replace `` with your Github username in the [DEMO LINK](https://.github.io/react_todo-app-with-api/) and add it to the PR description. +- Replace `` with your Github username in the [DEMO LINK](https://voronine.github.io/react_todo-app-with-api/) and add it to the PR description. diff --git a/src/App.tsx b/src/App.tsx index 5749bdf784..edff99ce95 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,24 +1,228 @@ -/* eslint-disable max-len */ -/* eslint-disable jsx-a11y/control-has-associated-label */ -import React from 'react'; -import { UserWarning } from './UserWarning'; +import React, { + useEffect, + useState, + useCallback, + useMemo, +} from 'react'; -const USER_ID = 0; +import { Todo } from './types/Todo'; +import * as todoService from './api/todos'; +import { ForComletedTodo } from './types/enumFilter'; +import { TodoItem } from './Components/TodoItem'; +import { Footer } from './Components/Footer'; +import { Header } from './Components/Header'; +import { ErrorNotification } from './Components/ErrorNotification'; +import { filterTodos } from './Components/helper'; export const App: React.FC = () => { - if (!USER_ID) { - return ; - } + const [todos, setTodos] = useState([]); + const [condition, setCondition] = useState(ForComletedTodo.All); + const [errorMessage, setErrorMessage] = useState(null); + const [inputDisabled, setInputDisabled] = useState(false); + const [processingTodoIds, setProcessingTodoIds] = useState([]); + const [tempTodo, setTempTodo] = useState(null); + const [errorTimer, setErrorTimer] = useState(null); + + const filteredTodos = useMemo(() => filterTodos(todos, condition), + [condition, todos]); + + useEffect(() => { + if (errorTimer) { + clearTimeout(errorTimer); + } + + setErrorTimer(setTimeout(() => { + setErrorMessage(null); + }, 3000)); + }, [errorMessage, errorTimer]); + + const hasTodos = !!todos.length; + + const isAllCompleted = todos.every(todo => todo.completed); + + const fetchData = useCallback(async () => { + try { + setErrorMessage(null); + const todosFetch = await todoService.getTodos(); + + setTodos(todosFetch); + } catch (err) { + setErrorMessage('Unable to load todos'); + } + }, []); + + useEffect(() => { + fetchData(); + }, []); + + const hadleAddTodo = async (title: string) => { + try { + setInputDisabled(true); + + const newTodo = { + id: 0, + userId: 0, + title: title.trim(), + completed: false, + }; + + setTempTodo(newTodo); + + const addedTodo = await todoService.addTodo(title); + + setTodos((prevTodos) => [...prevTodos, addedTodo]); + } catch (error) { + setErrorMessage('Unable to add a todo'); + throw error; + } finally { + setInputDisabled(false); + setTempTodo(null); + } + }; + + const handleDeleteTodo = (todoId: number) => { + setInputDisabled(true); + setProcessingTodoIds((prevTodoIds) => [...prevTodoIds, todoId]); + + return todoService + .deleteTodo(todoId) + .then((() => { + setTodos((prevTodos) => prevTodos.filter(todo => todo.id !== todoId)); + })) + .catch(() => { + setErrorMessage('Unable to delete a todo'); + }) + .finally(() => { + setInputDisabled(false); + setProcessingTodoIds( + (prevTodoIds) => prevTodoIds.filter(id => id !== todoId), + ); + }); + }; + + const handleRenameTodo = async (todo: Todo, newTodoTitle: string) => { + setProcessingTodoIds((prevTodoIds) => [...prevTodoIds, todo.id]); + + return todoService.updateTodo({ + ...todo, + title: newTodoTitle.trim(), + }) + .then(updatedTodo => { + setTodos(prevState => prevState.map(currentTodo => ( + currentTodo.id !== updatedTodo.id + ? currentTodo + : updatedTodo + ))); + }) + .catch(() => { + setErrorMessage('Unable to update a todo'); + }) + .finally(() => { + setProcessingTodoIds( + (prevTodoIds) => prevTodoIds.filter(id => id !== todo.id), + ); + }); + }; + + const handleClearCompletedTodos = () => { + todos.forEach(todo => { + if (todo.completed) { + handleDeleteTodo(todo.id); + } + }); + }; + + const handleToggleTodo = async (todo: Todo) => { + try { + setProcessingTodoIds((prevTodoIds) => [...prevTodoIds, todo.id]); + + const updatedTodo = await todoService.updateTodo({ + ...todo, + completed: !todo.completed, + }); + + setTodos(prevState => prevState.map(currentTodo => ( + currentTodo.id !== updatedTodo.id + ? currentTodo + : updatedTodo + ))); + } catch (error) { + setErrorMessage('Unable to update a todo'); + } finally { + setProcessingTodoIds( + (prevTodoIds) => prevTodoIds.filter(id => id !== todo.id), + ); + } + }; + + const handleToggleAllTodos = () => { + const activeTodos = todos.filter(todo => !todo.completed); + + if (isAllCompleted) { + todos.forEach(handleToggleTodo); + } else { + activeTodos.forEach(handleToggleTodo); + } + }; + + const handleDelete = async (todoId: number) => { + return handleDeleteTodo(todoId); + }; + + const handleRename = async (todo: Todo, todoTitle: string) => { + await handleRenameTodo(todo, todoTitle); + }; return ( -
-

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

- -

Styles are already copied

-
+
+

todos

+ +
+
+ +
+ {filteredTodos.map(todo => ( + handleDelete(todo.id)} + onRenameTodo={(todoTitle) => handleRename(todo, todoTitle)} + onTodoToggle={() => handleToggleTodo(todo)} + isProcessing={processingTodoIds.includes(todo.id)} + /> + ))} +
+ + {tempTodo && ( + + )} + + {hasTodos && ( +
+ )} +
+ + +
); }; diff --git a/src/Components/ErrorNotification.tsx b/src/Components/ErrorNotification.tsx new file mode 100644 index 0000000000..ceb1847c12 --- /dev/null +++ b/src/Components/ErrorNotification.tsx @@ -0,0 +1,60 @@ +import React, { useEffect } from 'react'; +import cn from 'classnames'; + +type Props = { + setErrorMessage: (errorMessage: string | null) => void; + errorMessage: string | null; + errorTimer: NodeJS.Timeout | null; + setErrorTimer: React.Dispatch>; +}; + +export const ErrorNotification: React.FC = ({ + setErrorMessage, + errorMessage, + errorTimer, + setErrorTimer, +}) => { + useEffect(() => { + if (errorTimer) { + clearTimeout(errorTimer); + } + + const newTimer = setTimeout(() => { + setErrorMessage(null); + }, 3000); + + setErrorTimer(newTimer); + + return () => { + if (newTimer) { + clearTimeout(newTimer); + } + }; + }, [errorMessage, setErrorTimer]); + + return ( +
+ +
+ ); +}; diff --git a/src/Components/Footer.tsx b/src/Components/Footer.tsx new file mode 100644 index 0000000000..2d856c82eb --- /dev/null +++ b/src/Components/Footer.tsx @@ -0,0 +1,38 @@ +import React from 'react'; +import { Todo } from '../types/Todo'; +import { NavMenu } from './NavMenu'; +import { ForComletedTodo } from '../types/enumFilter'; + +type Props = { + todos: Todo[]; + condition: ForComletedTodo; + setCondition: (condition: ForComletedTodo) => void; + handleClearCompletedTodos: () => void; +}; + +export const Footer: React.FC = ({ + todos, + condition, + setCondition, + handleClearCompletedTodos, +}) => { + const activeTodos = todos.filter(todo => !todo.completed).length; + + return ( +
+ + {`${activeTodos} item${activeTodos !== 1 ? 's' : ''} left`} + + + +
+ ); +}; diff --git a/src/Components/Header.tsx b/src/Components/Header.tsx new file mode 100644 index 0000000000..58cc302684 --- /dev/null +++ b/src/Components/Header.tsx @@ -0,0 +1,85 @@ +import React, { useEffect, useRef, useState } from 'react'; +import cn from 'classnames'; + +type Props = { + onTodoAdd: (title: string) => Promise; + isAllCompleted: boolean; + hasTodos: boolean, + onTodoAddError: (error: string | null) => void; + inputDisabled: boolean; + onToggleAll: () => void; +}; + +export const Header: React.FC = ({ + onTodoAdd, + isAllCompleted, + hasTodos, + onTodoAddError, + inputDisabled, + onToggleAll, +}) => { + const [title, setTitle] = useState(''); + + const handleTitleChange = (event: React.ChangeEvent) => { + setTitle(event.target.value); + onTodoAddError(null); + }; + + const onFormSubmit = (event: React.FormEvent) => { + event.preventDefault(); + + const trimmedTitle = title.trim(); + + if (!trimmedTitle) { + onTodoAddError('Title should not be empty'); + + return; + } + + onTodoAdd(trimmedTitle) + .then(() => { + setTitle(''); + }) + .catch((error) => { + // eslint-disable-next-line no-console + console.error(error); + }); + }; + + const inputRef = useRef(null); + + useEffect(() => { + if (!inputDisabled && inputRef.current) { + inputRef.current.focus(); + } + }, [inputDisabled]); + + return ( +
+ {Boolean(hasTodos) && ( +
+ ); +}; diff --git a/src/Components/NavMenu.tsx b/src/Components/NavMenu.tsx new file mode 100644 index 0000000000..278cc1dec3 --- /dev/null +++ b/src/Components/NavMenu.tsx @@ -0,0 +1,33 @@ +import cn from 'classnames'; +import { ForComletedTodo } from '../types/enumFilter'; + +interface Props { + condition: ForComletedTodo; + setCondition: (condition: ForComletedTodo) => void; +} + +export const NavMenu: React.FunctionComponent = ({ + condition, + setCondition, +}) => { + return ( + + ); +}; diff --git a/src/Components/TodoItem.tsx b/src/Components/TodoItem.tsx new file mode 100644 index 0000000000..f66150c9aa --- /dev/null +++ b/src/Components/TodoItem.tsx @@ -0,0 +1,147 @@ +import React, { useEffect, useRef, useState } from 'react'; +import cn from 'classnames'; +import { Todo } from '../types/Todo'; + +type Props = { + todo: Todo; + onTodoDelete?: () => void; + onRenameTodo?: (todoTitle: string) => void; + onTodoToggle?: () => Promise; + isProcessing: boolean; +}; + +export const TodoItem: React.FC = ({ + todo, + onTodoDelete = () => { }, + onRenameTodo = () => { }, + onTodoToggle = () => { }, + isProcessing, +}) => { + const { title, completed, id } = todo; + const [isEditing, setIsEditing] = useState(false); + const [todoTitle, setTodoTitle] = useState(todo.title); + + const handleTodoDoubleClick = () => { + setIsEditing(true); + }; + + const handleTodoSave = async (event: React.FormEvent) => { + event.preventDefault(); + try { + const trimmedTitle = todoTitle.trim(); + + if (!trimmedTitle) { + setIsEditing(false); + await onTodoDelete(); + + return; + } + + if (todo.title === trimmedTitle) { + setIsEditing(false); + + return; + } + + if (trimmedTitle) { + await onRenameTodo(todoTitle); + setIsEditing(false); + } else { + await onTodoDelete(); + } + + setIsEditing(false); + } catch { + // + } + }; + + const handleTodoTitleChange = ( + event: React.ChangeEvent, + ) => { + setTodoTitle(event.target.value); + }; + + const titleInputRef = useRef(null); + + useEffect(() => { + if (isEditing && titleInputRef.current) { + titleInputRef.current?.focus(); + } + }, [isEditing, isProcessing]); + + const onKeyUpHandle = (event: React.KeyboardEvent) => { + if (event.key === 'Escape') { + setIsEditing(false); + setTodoTitle(todo.title); + } + }; + + return ( +
+ + + {isEditing + ? ( +
+ +
+ ) : ( + <> + + {title.trim()} + + + + + )} + +
+
+
+
+
+ ); +}; diff --git a/src/Components/helper.tsx b/src/Components/helper.tsx new file mode 100644 index 0000000000..1fb9a3be14 --- /dev/null +++ b/src/Components/helper.tsx @@ -0,0 +1,17 @@ +import { Todo } from '../types/Todo'; +import { ForComletedTodo } from '../types/enumFilter'; + +export const filterTodos = ( + todos: Todo[], condition: ForComletedTodo, +): Todo[] => { + return todos.filter(({ completed }) => { + switch (condition) { + case ForComletedTodo.Active: + return !completed; + case ForComletedTodo.Completed: + return completed; + default: + return 1; + } + }); +}; diff --git a/src/api/todos.ts b/src/api/todos.ts new file mode 100644 index 0000000000..2ecbf1f0e1 --- /dev/null +++ b/src/api/todos.ts @@ -0,0 +1,30 @@ +import { Todo } from '../types/Todo'; +import { client } from '../utils/fetchClient'; + +export const USER_ID = 11511; + +export const getTodos = () => { + return client.get(`/todos?userId=${USER_ID}`); +}; + +export const deleteTodo = (todoId: number) => { + return client.delete(`/todos/${todoId}`); +}; + +export const addTodo = (title: string) => { + return client.post('/todos', { + title, + userId: USER_ID, + completed: false, + }); +}; + +export const updateTodo = ({ + id, title, userId, completed, +}: Todo): Promise => { + return client.patch(`/todos/${id}`, { + title, + userId, + completed, + }); +}; diff --git a/src/index.tsx b/src/index.tsx index 7de19e0c70..1b06674f67 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,5 +1,4 @@ import { createRoot } from 'react-dom/client'; - import 'bulma/css/bulma.css'; import '@fortawesome/fontawesome-free/css/all.css'; import './styles/index.scss'; diff --git a/src/styles/todo.scss b/src/styles/todo.scss index c7f93ff6b9..fc99714ef2 100644 --- a/src/styles/todo.scss +++ b/src/styles/todo.scss @@ -8,7 +8,7 @@ font-size: 24px; line-height: 1.4em; border-bottom: 1px solid #ededed; - + &:last-child { border-bottom: 0; } @@ -30,7 +30,7 @@ &__title { padding: 12px 15px; - + word-break: break-all; transition: color 0.4s; } @@ -56,7 +56,7 @@ border: 0; background: none; cursor: pointer; - + transform: translateY(-2px); opacity: 0; transition: color 0.2s ease-out; @@ -65,7 +65,7 @@ color: #af5b5e; } } - + &:hover &__remove { opacity: 1; } @@ -73,13 +73,13 @@ &__title-field { width: 100%; padding: 11px 14px; - + font-size: inherit; line-height: inherit; font-family: inherit; font-weight: inherit; color: inherit; - + border: 1px solid #999; box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2); @@ -92,58 +92,11 @@ .overlay { position: absolute; - top: 0; left: 0; right: 0; - height: 58px; + bottom: 0; + top: 0; opacity: 0.5; } } - -.item-enter { - max-height: 0; -} - -.item-enter-active { - overflow: hidden; - max-height: 58px; - transition: max-height 0.3s ease-in-out; -} - -.item-exit { - max-height: 58px; -} - -.item-exit-active { - overflow: hidden; - max-height: 0; - transition: max-height 0.3s ease-in-out; -} - -.temp-item-enter { - max-height: 0; -} - -.temp-item-enter-active { - overflow: hidden; - max-height: 58px; - transition: max-height 0.3s ease-in-out; -} - -.temp-item-exit { - max-height: 58px; -} - -.temp-item-exit-active { - transform: translateY(-58px); - max-height: 0; - opacity: 0; - transition: 0.3s ease-in-out; - transition-property: opacity, max-height, transform; -} - -.has-error .temp-item-exit-active { - transform: translateY(0); - overflow: hidden; -} diff --git a/src/styles/todoapp.scss b/src/styles/todoapp.scss index 9095f1847f..9a14a730e2 100644 --- a/src/styles/todoapp.scss +++ b/src/styles/todoapp.scss @@ -121,7 +121,6 @@ appearance: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; - transition: opacity 0.3s; &:hover { text-decoration: underline; @@ -130,7 +129,6 @@ &:active { text-decoration: none; } - &:disabled { visibility: hidden; } 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/types/enumFilter.ts b/src/types/enumFilter.ts new file mode 100644 index 0000000000..0f493f3baf --- /dev/null +++ b/src/types/enumFilter.ts @@ -0,0 +1,5 @@ +export enum ForComletedTodo { + All = '', + Active = 'active', + Completed = 'completed', +} diff --git a/src/utils/fetchClient.ts b/src/utils/fetchClient.ts new file mode 100644 index 0000000000..ca588ab63a --- /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', + }; + } + + // we wait for testing purpose to see loaders + 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'), +};