diff --git a/README.md b/README.md index 47a1add059..9fbdc60bca 100644 --- a/README.md +++ b/README.md @@ -47,4 +47,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://AlexLiashenko19.github.io/react_todo-app-with-api/) and add it to the PR description. diff --git a/package-lock.json b/package-lock.json index 19701e8788..511279ae76 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,7 +19,7 @@ }, "devDependencies": { "@cypress/react18": "^2.0.1", - "@mate-academy/scripts": "^1.8.5", + "@mate-academy/scripts": "^1.9.12", "@mate-academy/students-ts-config": "*", "@mate-academy/stylelint-config": "*", "@types/node": "^20.14.10", @@ -1183,10 +1183,11 @@ } }, "node_modules/@mate-academy/scripts": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@mate-academy/scripts/-/scripts-1.8.5.tgz", - "integrity": "sha512-mHRY2FkuoYCf5U0ahIukkaRo5LSZsxrTSgMJheFoyf3VXsTvfM9OfWcZIDIDB521kdPrScHHnRp+JRNjCfUO5A==", + "version": "1.9.12", + "resolved": "https://registry.npmjs.org/@mate-academy/scripts/-/scripts-1.9.12.tgz", + "integrity": "sha512-/OcmxMa34lYLFlGx7Ig926W1U1qjrnXbjFJ2TzUcDaLmED+A5se652NcWwGOidXRuMAOYLPU2jNYBEkKyXrFJA==", "dev": true, + "license": "MIT", "dependencies": { "@octokit/rest": "^17.11.2", "@types/get-port": "^4.2.0", diff --git a/package.json b/package.json index b6062525ab..005692edf7 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ }, "devDependencies": { "@cypress/react18": "^2.0.1", - "@mate-academy/scripts": "^1.8.5", + "@mate-academy/scripts": "^1.9.12", "@mate-academy/students-ts-config": "*", "@mate-academy/stylelint-config": "*", "@types/node": "^20.14.10", diff --git a/src/App.tsx b/src/App.tsx index 81e011f432..26756e6d02 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,26 +1,191 @@ -/* 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 { UserWarning } from './UserWarning'; - -const USER_ID = 0; +import React, { useEffect, useMemo, useRef, useState } from 'react'; +import { Todo } from './types/Todo'; +import * as todoService from './api/todos'; +import { Error } from './components/Error'; +import { TodoList } from './components/TodoList'; +import { FilterStatus } from './types/FilterTypes'; +import { ErrorType } from './types/ErrorTypes'; +import { Footer } from './components/Footer'; +import { Header } from './components/Header'; export const App: React.FC = () => { - if (!USER_ID) { - return ; - } + // #region state + const [todos, setTodos] = useState([]); + const [errorMessage, setErrorMessage] = useState(ErrorType.Empty); + const [filterStatus, setFilterStatus] = useState( + FilterStatus.All, + ); + const [tempTodo, setTempTodo] = useState(null); + const [loadingTodoIds, setLoadingTodoIds] = useState([]); + + const inputAddRef = useRef(null); + // #endregionstate + + // #region lifecycle + const filteredTodos = useMemo( + () => + todos.filter(todo => { + if (filterStatus === FilterStatus.All) { + return true; + } + + return filterStatus === FilterStatus.Completed + ? todo.completed + : !todo.completed; + }), + [todos, filterStatus], + ); + + const todosLeftNum = useMemo( + () => todos.filter(todo => !todo.completed).length, + [todos], + ); + + const todosActiveNum = useMemo( + () => todos.filter(todo => !todo.completed).length, + [todos], + ); + + const todosCompleted = useMemo( + () => todos.filter(todo => todo.completed).length, + [todos], + ); + + const areAllTodosCompleted = useMemo( + () => todos.every(todo => todo.completed), + [todos], + ); + + const addTodo = async (todoTitle: string) => { + setTempTodo({ + id: 0, + title: todoTitle, + completed: false, + userId: todoService.USER_ID, + }); + try { + const newTodo = await todoService.createTodos({ + title: todoTitle, + completed: false, + }); + + setTodos(prev => [...prev, newTodo]); + } catch (err) { + setErrorMessage(ErrorType.AddTodo); + inputAddRef?.current?.focus(); + throw err; + } finally { + setTempTodo(null); + } + }; + + const onRemoveTodo = async (todoId: number) => { + setLoadingTodoIds(prev => [...prev, todoId]); + try { + await todoService.deleteTodo(todoId); + + setTodos(prev => prev.filter(todo => todo.id !== todoId)); + } catch (err) { + setErrorMessage(ErrorType.DeleteTodo); + inputAddRef?.current?.focus(); + throw err; + } finally { + setLoadingTodoIds(prev => prev.filter(id => id !== todoId)); + } + }; + + const onClearCompleted = async () => { + const completedTodos = todos.filter(todo => todo.completed); + + completedTodos.forEach(todo => { + onRemoveTodo(todo.id); + }); + }; + + const updatedTodo = async (todoToUpdate: Todo) => { + setLoadingTodoIds(prev => [...prev, todoToUpdate.id]); + try { + const updateTodo = await todoService.updateTodo(todoToUpdate); + + setTodos(prev => + prev.map(todo => (todo.id === updateTodo.id ? updateTodo : todo)), + ); + } catch (err) { + setErrorMessage(ErrorType.UpdateTodo); + throw err; + } finally { + setLoadingTodoIds(prev => prev.filter(id => id !== todoToUpdate.id)); + } + }; + + const toggleTodo = async () => { + if (todosActiveNum > 0) { + const activeTodos = todos.filter(todo => !todo.completed); + + activeTodos.forEach(todo => { + updatedTodo({ ...todo, completed: true }); + }); + } else { + todos.forEach(todo => { + updatedTodo({ ...todo, completed: false }); + }); + } + }; + + useEffect(() => { + (async () => { + try { + const data = await todoService.getTodos(); + + setTodos(data); + } catch (err) { + setErrorMessage(ErrorType.LoadTodos); + } + })(); + }, []); + + // #endregionlife return ( -
-

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

- -

Styles are already copied

-
+
+

todos

+ +
+
+ + {(todos.length > 0 || tempTodo) && ( + <> + +
+ + )} + + {/* Hide the footer if there are no todos */} +
+ + +
); }; diff --git a/src/api/todos.ts b/src/api/todos.ts new file mode 100644 index 0000000000..7ec6f5f6ae --- /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 = 2135; + +export const getTodos = () => { + return client.get(`/todos?userId=${USER_ID}`); +}; + +export const createTodos = (newTodo: Omit) => { + return client.post(`/todos`, { ...newTodo, userId: USER_ID }); +}; + +export const deleteTodo = (id: number) => { + return client.delete(`/todos/${id}`); +}; + +export const updateTodo = ({ id, title, userId, completed }: Todo) => { + return client.patch(`/todos/${id}`, { title, userId, completed }); +}; diff --git a/src/components/Error.tsx b/src/components/Error.tsx new file mode 100644 index 0000000000..782115ee9c --- /dev/null +++ b/src/components/Error.tsx @@ -0,0 +1,44 @@ +import React, { Dispatch, SetStateAction, useEffect } from 'react'; +import { ErrorType } from '../types/ErrorTypes'; +import classNames from 'classnames'; + +type Props = { + error: ErrorType; + setError: Dispatch>; +}; + +export const Error: React.FC = props => { + const { error, setError } = props; + + useEffect(() => { + if (error === ErrorType.Empty) { + return; + } + + const timerId = setTimeout(() => { + setError(ErrorType.Empty); + }, 3000); + + return () => { + clearTimeout(timerId); + }; + }, [error, setError]); + + return ( +
+
+ ); +}; diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx new file mode 100644 index 0000000000..03d26fbec7 --- /dev/null +++ b/src/components/Footer.tsx @@ -0,0 +1,57 @@ +import React, { Dispatch, SetStateAction } from 'react'; +import classNames from 'classnames'; +import { FilterStatus } from '../types/FilterTypes'; + +type Props = { + filterStatus: FilterStatus; + setFilterStatus: Dispatch>; + todosLeft: number; + todosCompleted: number; + onClearCompleted: () => Promise; +}; + +export const Footer: React.FC = props => { + const { + filterStatus, + setFilterStatus, + todosLeft, + todosCompleted, + onClearCompleted, + } = props; + + return ( +
+ + {todosLeft} items left + + + {/* Active link should have the 'selected' class */} + + + {/* this button should be disabled if there are no completed todos */} + +
+ ); +}; diff --git a/src/components/Header.tsx b/src/components/Header.tsx new file mode 100644 index 0000000000..6d2245d8cd --- /dev/null +++ b/src/components/Header.tsx @@ -0,0 +1,77 @@ +import React, { Dispatch, SetStateAction, useEffect, useState } from 'react'; +import { ErrorType } from '../types/ErrorTypes'; +import classNames from 'classnames'; + +type Props = { + onAddTodo: (value: string) => Promise; + setErrorMessage: Dispatch>; + isInputDisabled: boolean; + todosLength: number; + inputRef: React.RefObject | null; + areAllTodosCompleted: boolean; + onToggleAll: () => Promise; +}; + +export const Header: React.FC = ({ + onAddTodo, + setErrorMessage, + isInputDisabled, + todosLength, + inputRef, + onToggleAll, + areAllTodosCompleted, +}) => { + const [inputValue, setInputValue] = useState(''); + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + if (inputValue.trim() === '') { + setErrorMessage(ErrorType.EmptyTitle); + + return; + } + + try { + await onAddTodo(inputValue.trim()); + setInputValue(''); + } catch (err) {} + }; + + useEffect(() => { + inputRef?.current?.focus(); + }, [todosLength, inputRef]); + + useEffect(() => { + if (!isInputDisabled) { + inputRef?.current?.focus(); + } + }, [isInputDisabled, inputRef]); + + return ( +
+ {todosLength !== 0 && ( +
+ ); +}; diff --git a/src/components/TodoItem.tsx b/src/components/TodoItem.tsx new file mode 100644 index 0000000000..f84d082d60 --- /dev/null +++ b/src/components/TodoItem.tsx @@ -0,0 +1,127 @@ +/* eslint-disable jsx-a11y/label-has-associated-control */ +import React, { Dispatch, SetStateAction, useRef, useState } from 'react'; +import { Todo } from '../types/Todo'; +import classNames from 'classnames'; + +type Props = { + todo: Todo; + isLoading?: boolean; + isInEditMode?: boolean; + onRemoveTodo: (todoId: number) => Promise; + updatedTodo: (todo: Todo) => Promise; + setEditedTodoId: Dispatch>; +}; + +export const TodoItem: React.FC = ({ + todo, + isLoading, + isInEditMode, + onRemoveTodo, + updatedTodo, + setEditedTodoId, +}) => { + const [todoTitleValue, setTodoTitleValue] = useState(todo.title); + + const inputRef = useRef(null); + + const onCheckTodo = () => { + const todoToUpdate = { ...todo, completed: !todo.completed }; + + updatedTodo(todoToUpdate); + }; + + const onDoubleClick = () => { + setEditedTodoId(todo.id); + }; + + // eslint-disable-next-line max-len, prettier/prettier + const onBlur = async (event: React.FocusEvent | React.FormEvent, + ) => { + event.preventDefault(); + const normalizedTitle = todoTitleValue.trim(); + + if (todo.title === normalizedTitle) { + setEditedTodoId(null); + + return; + } + + try { + if (normalizedTitle === '') { + await onRemoveTodo(todo.id); + } else { + await updatedTodo({ ...todo, title: normalizedTitle }); + } + + setEditedTodoId(null); + } catch (err) { + inputRef?.current?.focus(); + } + }; + + const onKeyUp = (event: React.KeyboardEvent) => { + if (event.key === 'Escape') { + setEditedTodoId(null); + setTodoTitleValue(todo.title); + } + }; + + return ( +
+ + + {isInEditMode ? ( +
+ setTodoTitleValue(e.target.value)} + onKeyUp={onKeyUp} + ref={inputRef} + /> +
+ ) : ( + <> + + {todo.title} + + + + )} + +
+
+
+
+
+ ); +}; diff --git a/src/components/TodoList.tsx b/src/components/TodoList.tsx new file mode 100644 index 0000000000..6fb6f48dbe --- /dev/null +++ b/src/components/TodoList.tsx @@ -0,0 +1,46 @@ +import React, { useState } from 'react'; +import { Todo } from '../types/Todo'; +import { TodoItem } from './TodoItem'; + +type Props = { + todos: Todo[]; + onRemoveTodo: (id: number) => Promise; + loadingTodoIds: number[]; + updatedTodo: (todo: Todo) => Promise; + tempTodo: Todo | null; +}; + +export const TodoList: React.FC = ({ + todos, + onRemoveTodo, + loadingTodoIds, + updatedTodo, + tempTodo, +}) => { + const [editedTodoId, setEditedTodoId] = useState(null); + + return ( +
+ {todos.map(todo => ( + + ))} + {tempTodo && ( + + )} +
+ ); +}; diff --git a/src/types/ErrorTypes.ts b/src/types/ErrorTypes.ts new file mode 100644 index 0000000000..66f0a8d5ad --- /dev/null +++ b/src/types/ErrorTypes.ts @@ -0,0 +1,8 @@ +export enum ErrorType { + Empty = '', + LoadTodos = 'Unable to load todos', + EmptyTitle = 'Title should not be empty', + AddTodo = 'Unable to add a todo', + DeleteTodo = 'Unable to delete a todo', + UpdateTodo = 'Unable to update a todo', +} diff --git a/src/types/FilterTypes.ts b/src/types/FilterTypes.ts new file mode 100644 index 0000000000..7ca17f289b --- /dev/null +++ b/src/types/FilterTypes.ts @@ -0,0 +1,5 @@ +export enum FilterStatus { + 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'), +}; diff --git a/src/utils/getFilteredTodos.ts b/src/utils/getFilteredTodos.ts new file mode 100644 index 0000000000..bbd1829b9c --- /dev/null +++ b/src/utils/getFilteredTodos.ts @@ -0,0 +1,14 @@ +import { FilterStatus } from '../types/FilterTypes'; +import { Todo } from '../types/Todo'; + +export const getFilteredTodos = (todos: Todo[], status: FilterStatus) => + todos.filter(todo => { + switch (status) { + case FilterStatus.Completed: + return todo.completed; + case FilterStatus.Active: + return !todo.completed; + default: + return true; + } + });