diff --git a/README.md b/README.md index c7bfa3dd36..fb226ac965 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://dimkamg21.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..747027a0e5 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,24 +1,318 @@ -/* eslint-disable max-len */ /* eslint-disable jsx-a11y/control-has-associated-label */ -import React from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; +import classNames from 'classnames'; +import { Todo } from './types/Todo'; import { UserWarning } from './UserWarning'; - -const USER_ID = 0; +import { TodoList } from './components/TodoList/TodoList'; +import * as todoService from './api/todos'; +import { USER_ID } from './api/Personal_Id'; +import { Status } from './types/Status'; export const App: React.FC = () => { + const [todos, setTodos] = useState([]); + const [title, setTitle] = useState(''); + const [errorMessage, setErrorMessage] = useState(''); + const [status, setStatus] = useState(Status.All); + const [visible, setVisible] = useState(false); + const [disableInput, setDisableInput] = useState(false); + const [tempoTodo, setTempoTodo] = useState(null); + const [loadingTodoId, setLoadingTodoId] = useState([]); + + const completedTodosCount = todos.reduce((acc, todo) => { + return todo.completed ? acc + 1 : acc; + }, 0); + + const hasCompleted = todos.every(todo => todo.completed); + + const activeTodosCount = todos.length - completedTodosCount; + + const visibleTodos = todos.filter(todo => { + switch (status) { + case Status.Active: + return !todo.completed; + + case Status.Completed: + return todo.completed; + + case Status.All: + default: + return true; + } + }); + + const resetAddTodoState = () => { + setTempoTodo(null); + setTitle(''); + setDisableInput(false); + }; + + const createTempTodo = () => ({ + id: 0, + userId: USER_ID, + title: title.trim(), + completed: false, + }); + + const handleSubmit = (todoTitle: string) => { + const trimmedTitle = todoTitle.trim(); + const tempTodo = createTempTodo(); + + setTempoTodo(tempTodo); + + setDisableInput(true); + + if (!trimmedTitle) { + setErrorMessage("Title can't be empty"); + + return; + } + + setTimeout(() => { + todoService + .addTodos(tempTodo) + .then((newTodo) => setTodos([...todos, newTodo])) + .catch(() => setErrorMessage('Unable to add a todo')) + .finally(() => resetAddTodoState()); + }, 500); + }; + + const deleteTodo = (todoId: number) => { + setLoadingTodoId([todoId]); + + todoService.deletePost(todoId) + .then(() => setTodos([ + ...todos.filter(todo => todo.id !== todoId), + ])) + .catch(() => setErrorMessage('Unable to delete the todo')); + }; + + const handleClearCompletedTodos = useCallback(() => { + const completedTodos = todos.filter(todo => todo.completed); + + const completedTodoIds = completedTodos.map(todo => todo.id); + + setLoadingTodoId(completedTodoIds); + + Promise.all( + completedTodos.map(todo => ( + todoService.deletePost(todo.id) + )), + ) + .then(() => { + setTodos(todos.filter(todo => !todo.completed)); + }) + .catch(() => { + setErrorMessage('Unable to delete completed todos'); + }) + .finally(() => setLoadingTodoId([])); + }, [todos]); + + const toggleTodoStatus = async (todoId: number, completed: boolean) => { + try { + setLoadingTodoId([todoId]); + await todoService.updatePostStatus(todoId, completed); + + setTodos(currentTodos => currentTodos.map( + todo => (todoId === todo.id ? { ...todo, completed } : todo), + )); + } catch { + setErrorMessage('Unable to update a todo'); + } finally { + setLoadingTodoId([]); + } + }; + + const handleToggleTodosAll = async (completed: boolean) => { + const todosIds = todos + .filter(todo => todo.completed !== completed) + .map(todo => todo.id); + + try { + setLoadingTodoId(todosIds); + + const updatedTodos = todos.map(todo => ({ + ...todo, + completed, + })); + + setTodos(updatedTodos); + + await Promise.all( + todos.map(todo => todoService.updatePostStatus(todo.id, completed)), + ); + } catch { + setErrorMessage('Unable to update a todos'); + } finally { + setLoadingTodoId([]); + } + }; + + const handleEditTodo = async (todoId: number, newTitle: string) => { + if (!newTitle) { + setErrorMessage('Title can`t be empty'); + + return; + } + + try { + setLoadingTodoId([todoId]); + const updatedTodo = await todoService.updateTodoTitle(todoId, newTitle); + + setTodos(currentTodos => currentTodos.map( + todo => (todoId === todo.id ? updatedTodo : todo), + )); + } catch { + setErrorMessage('Title can`t be empty'); + } finally { + setLoadingTodoId([]); + } + }; + + useEffect(() => { + if (errorMessage) { + setTimeout(() => { + setErrorMessage(''); + }, 3000); + } + }, [errorMessage]); + + useEffect(() => { + todoService.getTodos() + .then(setTodos) + .catch(() => setErrorMessage('Unable to load a todo')); + + setTimeout(() => { + setVisible(true); // Set to true to trigger the transition + }, 1000); + }, []); + if (!USER_ID) { - return ; + return ( + + ); } return ( -
-

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

- -

Styles are already copied

-
+
+

todos

+ +
+
+ {todos.length > 0 && ( +
+ + {(todos.length > 0 || tempoTodo) && ( +
+ + + + +
+ )} +
+ +
+
+
); }; diff --git a/src/api/Personal_Id.ts b/src/api/Personal_Id.ts new file mode 100644 index 0000000000..4bc15f04fe --- /dev/null +++ b/src/api/Personal_Id.ts @@ -0,0 +1 @@ +export const USER_ID = 11407; diff --git a/src/api/todos.ts b/src/api/todos.ts new file mode 100644 index 0000000000..04fba03c0f --- /dev/null +++ b/src/api/todos.ts @@ -0,0 +1,25 @@ +import { Todo } from '../types/Todo'; +import { client } from '../utils/fetchClient'; +import { USER_ID } from './Personal_Id'; + +export const getTodos = (): Promise => { + return client.get(`/todos?userId=${USER_ID}`); +}; + +export const addTodos = (todo: Omit) => { + return client.post('/todos', todo); +}; + +export const deletePost = (id: number) => { + return client.delete(`/todos/${id}`); +}; + +export const updatePostStatus = (id: number, completed: boolean) => { + return client.patch(`/todos/${id}`, { completed }); +}; + +export const updateTodoTitle = ( + todoId: number, title: string, +): Promise => { + return client.patch(`/todos/${todoId}`, { title }); +}; diff --git a/src/components/TempoTodoItem/TempoTodoItem.tsx b/src/components/TempoTodoItem/TempoTodoItem.tsx new file mode 100644 index 0000000000..73bb3ddf9c --- /dev/null +++ b/src/components/TempoTodoItem/TempoTodoItem.tsx @@ -0,0 +1,30 @@ +import React from 'react'; +import { Todo } from '../../types/Todo'; + +type Props = { + tempoTodo: Todo; +}; + +export const TempoTodoItem: React.FC = ({ tempoTodo }) => ( +
+ + + {tempoTodo.title} + +
+
+
+
+
+); diff --git a/src/components/TodoItem/TodoItem.tsx b/src/components/TodoItem/TodoItem.tsx new file mode 100644 index 0000000000..7d229b2a7c --- /dev/null +++ b/src/components/TodoItem/TodoItem.tsx @@ -0,0 +1,123 @@ +import React, { useEffect, useRef, useState } from 'react'; +import classNames from 'classnames'; +import { Todo } from '../../types/Todo'; + +type Props = { + todo: Todo, + deleteTodo: (todoId: number) => void, + uptadeTodoStatus: (todoId: number, completed: boolean) => void, + onChangeTodoTitle: (todoId: number, newTitle: string) => void, + loading: boolean, +}; + +export const TodoItem: React.FC = ({ + todo, loading, + deleteTodo, uptadeTodoStatus, onChangeTodoTitle, +}) => { + const { id, completed, title } = todo; + + const [isEditing, setIsEditing] = useState(false); + const [editedTitle, setEditedTitle] = useState(title); + + const titleField = useRef(null); + + const handleDeleteTodo = () => { + deleteTodo(id); + }; + + const titleChanger = (event: React.ChangeEvent) => { + setEditedTitle(event.target.value); + }; + + const handleTodoStatusChange = () => { + uptadeTodoStatus(id, !completed); + }; + + const handleEditTitle = () => { + setIsEditing(true); + + if (!editedTitle) { + handleDeleteTodo(); + } else if (editedTitle === title) { + setIsEditing(false); + } + + onChangeTodoTitle(id, editedTitle); + setIsEditing(false); + }; + + const handleKeyUp = (event: React.KeyboardEvent) => { + if (event.key === 'Enter') { + handleEditTitle(); + } else if (event.key === 'Escape') { + setEditedTitle(title); + setIsEditing(false); + } + }; + + useEffect(() => { + if (isEditing) { + titleField.current?.focus(); + } + }, [isEditing, id]); + + return ( + <> +
+ + + {!isEditing ? ( + <> + setIsEditing(true)} + > + {todo.title} + + + + + ) : ( + + )} + +
+
+
+
+
+ + ); +}; diff --git a/src/components/TodoList/TodoList.tsx b/src/components/TodoList/TodoList.tsx new file mode 100644 index 0000000000..70cee7385a --- /dev/null +++ b/src/components/TodoList/TodoList.tsx @@ -0,0 +1,36 @@ +import { TodoItem } from '../TodoItem/TodoItem'; +import { Todo } from '../../types/Todo'; +import { TempoTodoItem } from '../TempoTodoItem/TempoTodoItem'; + +type Props = { + todos: Todo[], + tempoTodo: Todo | null; + deleteTodo: (todoId: number) => void, + uptadeTodoStatus: (todoId: number, completed: boolean) => void, + loadingTodoId: number[], + onChangeTodoTitle: (todoId: number, newTitle: string) => void, +}; + +export const TodoList: React.FC = ({ + todos, tempoTodo, loadingTodoId, + uptadeTodoStatus, deleteTodo, onChangeTodoTitle, +}) => { + return ( +
+ {todos.map(todo => ( + + ))} + {tempoTodo !== null && ( + + )} +
+ + ); +}; diff --git a/src/styles/todo.scss b/src/styles/todo.scss index fc99714ef2..171dc989ec 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); diff --git a/src/styles/todoapp.scss b/src/styles/todoapp.scss index 836166156b..c400a71018 100644 --- a/src/styles/todoapp.scss +++ b/src/styles/todoapp.scss @@ -1,4 +1,3 @@ - .todoapp { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 24px; @@ -69,7 +68,7 @@ border: none; background: rgba(0, 0, 0, 0.01); - box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03); + box-shadow: inset 0 -2px 1px rgba(0, 0, 0, 0.03); &::placeholder { font-style: italic; @@ -129,5 +128,20 @@ &:active { text-decoration: none; } + + &--hidden { + visibility: hidden; + } + } +} + +.todo-list { + opacity: 0; + transform: translateY(-20px); + transition: opacity 0.5s ease, transform 0.5s ease; + + &.visible { + opacity: 1; + transform: translateY(0); } } diff --git a/src/types/Status.ts b/src/types/Status.ts new file mode 100644 index 0000000000..dc864cc93b --- /dev/null +++ b/src/types/Status.ts @@ -0,0 +1,5 @@ +export enum Status { + 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..42421feae0 --- /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(300) + .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'), +};