diff --git a/README.md b/README.md index 47a1add059..159c0b2b1b 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://Dima2702.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..0dbc74a8e1 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": "^2.1.3", "@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": "2.1.3", + "resolved": "https://registry.npmjs.org/@mate-academy/scripts/-/scripts-2.1.3.tgz", + "integrity": "sha512-a07wHTj/1QUK2Aac5zHad+sGw4rIvcNl5lJmJpAD7OxeSbnCdyI6RXUHwXhjF5MaVo9YHrJ0xVahyERS2IIyBQ==", "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..6d0f20adcc 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": "^2.1.3", "@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..9afdbf623f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,26 +1,293 @@ -/* 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, useRef, useState } from 'react'; +import cn from 'classnames'; import { UserWarning } from './UserWarning'; +import { + getTodoError, + todosService, + TodosServiceError, + USER_ID, +} from './api/todos'; +import { Todo } from './types/Todo'; +import { TodoItem } from './components/TodoItem'; +import { ErrorNotification } from './components/ErrorNotification'; +import { useErrorMessage } from './hooks/useErrorMessage'; +import { StatusFilter, TodoStatus } from './components/StatusFilter'; +import { getSortedTodos } from './utils/getSortedTodos'; +import { AddTodoForm, AddTodoFormData } from './components/AddTodoForm'; +import { TodoCreate } from './types/TodoCreate'; +import { TodoUpdate } from './types/TodoUpdate'; -const USER_ID = 0; +function getFilteredTodos(todos: Todo[], { status }: { status: TodoStatus }) { + let filteredTodos = todos; + + if (status !== TodoStatus.All) { + filteredTodos = filteredTodos.filter(todo => { + switch (status) { + case TodoStatus.Completed: + return todo.completed; + + case TodoStatus.Active: + return !todo.completed; + + default: + throw new Error('Massing case in getFilteredTodos status filter'); + } + }); + } + + return filteredTodos; +} export const App: React.FC = () => { + const [todos, setTodos] = useState([]); + const [loadingTodoIds, setLoadingTodoIds] = useState([]); + const [tempTodo, setTempTodo] = useState(null); + const [statusFilter, setStatusFilter] = useState(TodoStatus.All); + const newTodoTitleRef = useRef(null); + + const { errorMessage, resetErrorMessage, setErrorMessage } = + useErrorMessage(); + + const { completed: completedTodos, active: activeTodos } = + getSortedTodos(todos); + + const handleAddToLoading = useCallback((todoId: number) => { + setLoadingTodoIds(current => [...current, todoId]); + }, []); + + const handleRemoveFromLoading = useCallback((todoId: number) => { + setLoadingTodoIds(current => current.filter(id => id !== todoId)); + }, []); + + const handleDeleteTodo = useCallback( + (todoId: number) => { + handleAddToLoading(todoId); + + todosService + .delete(todoId) + .then(() => { + setTodos(current => current.filter(todo => todo.id !== todoId)); + }) + .catch(() => { + setErrorMessage(getTodoError(TodosServiceError.UnableToDeleteTodo)); + }) + .finally(() => { + handleRemoveFromLoading(todoId); + + newTodoTitleRef.current?.focus(); + }); + }, + [ + newTodoTitleRef, + handleAddToLoading, + handleRemoveFromLoading, + setErrorMessage, + ], + ); + + const handleClearCompleted = useCallback(() => { + completedTodos.forEach(todo => { + handleDeleteTodo(todo.id); + }); + }, [completedTodos, handleDeleteTodo]); + + const handleCreateTodo = useCallback( + ( + values: AddTodoFormData, + { + onSuccess, + onError, + }: { + onSuccess?: (createdTodo: Todo) => void; + onError?: () => void; + } = {}, + ) => { + if (newTodoTitleRef.current) { + newTodoTitleRef.current.disabled = true; + } + + const createTodoDto: TodoCreate = { + title: values.title, + userId: USER_ID, + completed: false, + }; + + setTempTodo({ + id: 0, + ...createTodoDto, + }); + + todosService + .create(createTodoDto) + .then(createdTodo => { + onSuccess?.(createdTodo); + setTodos(current => [...current, createdTodo]); + }) + .catch(() => { + setErrorMessage(getTodoError(TodosServiceError.UnableToAddTodo)); + + onError?.(); + }) + .finally(() => { + setTempTodo(null); + if (newTodoTitleRef.current) { + newTodoTitleRef.current.disabled = false; + } + + newTodoTitleRef.current?.focus(); + }); + }, + [newTodoTitleRef, setErrorMessage], + ); + + const handleUpdateTodo = useCallback( + ( + todoId: number, + data: TodoUpdate, + { + onSuccess, + onError, + }: { onSuccess?: (updatedTodo: Todo) => void; onError?: () => void } = {}, + ) => { + handleAddToLoading(todoId); + todosService + .update(todoId, data) + .then(updatedTodo => { + setTodos(current => + current.map(todo => { + return todo.id === updatedTodo.id ? updatedTodo : todo; + }), + ); + + onSuccess?.(updatedTodo); + }) + .catch(() => { + setErrorMessage(getTodoError(TodosServiceError.UnableToUpdateTodo)); + + onError?.(); + }) + .finally(() => { + handleRemoveFromLoading(todoId); + }); + }, + [handleAddToLoading, handleRemoveFromLoading, setErrorMessage], + ); + + const handleBulkToggleStatus = useCallback(() => { + if (activeTodos.length !== 0) { + activeTodos.forEach(({ id, ...todo }) => { + handleUpdateTodo(id, { + title: todo.title, + userId: todo.userId, + completed: !todo.completed, + }); + }); + + return; + } + + todos.forEach(({ id, ...todo }) => { + handleUpdateTodo(id, { + title: todo.title, + userId: todo.userId, + completed: !todo.completed, + }); + }); + }, [todos, activeTodos, handleUpdateTodo]); + + useEffect(() => { + todosService + .list() + .then(todosFromServer => setTodos(todosFromServer)) + .catch(() => { + setErrorMessage(getTodoError(TodosServiceError.UnableToLoadTodos)); + }) + .finally(); + }, [setErrorMessage]); + + const filteredTodos = getFilteredTodos(todos, { status: statusFilter }); + + const showTodosAndFooter = todos.length > 0; + const showToggleButton = todos.length > 0; + const showClearCompletedButton = completedTodos.length > 0; + const activeTodosAmount = activeTodos.length; + const shouldToggleButtonBeActive = completedTodos.length === todos.length; + if (!USER_ID) { return ; } return ( -
-

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

- -

Styles are already copied

-
+
+

todos

+
+
+ {/* this button should have `active` class only if all todos are completed */} + {showToggleButton && ( +
+ {showTodosAndFooter && ( + <> +
+ {filteredTodos.map(todo => ( + + ))} + + {tempTodo && } +
+ + {/* Hide the footer if there are no todos */} +
+ + {activeTodosAmount} items left + + + + + +
+ + )} +
+ {/* DON'T use conditional rendering to hide the notification */} + {/* Add the 'hidden' class to hide the message smoothly */} + +
); }; diff --git a/src/api/todos.ts b/src/api/todos.ts new file mode 100644 index 0000000000..018ea79193 --- /dev/null +++ b/src/api/todos.ts @@ -0,0 +1,34 @@ +import { Todo } from '../types/Todo'; +import { TodoCreate } from '../types/TodoCreate'; +import { TodoUpdate } from '../types/TodoUpdate'; +import { client } from '../utils/fetchClient'; + +export const USER_ID = 4252; + +export const todosService = { + list: () => client.get(`/todos?userId=${USER_ID}`), + create: (data: TodoCreate) => client.post('/todos', data), + delete: (todoId: number) => client.delete(`/todos/${todoId}`), + update: (todoId: number, data: TodoUpdate) => + client.patch(`/todos/${todoId}`, data), +}; + +export enum TodosServiceError { + UnableToLoadTodos = 'todos_service_unable_to_load_todos', + TitleShouldNotBeEmpty = 'todos_service_title_should_not_be_empty', + UnableToDeleteTodo = 'todos_service_unable_to_delete_todo', + UnableToAddTodo = 'todos_service_unable_to_add_todo', + UnableToUpdateTodo = 'todos_service_unable_to_update_todo', +} + +const TODOS_ERROR_MESSAGES: Record = { + [TodosServiceError.UnableToLoadTodos]: 'Unable to load todos', + [TodosServiceError.TitleShouldNotBeEmpty]: 'Title should not be empty', + [TodosServiceError.UnableToDeleteTodo]: 'Unable to delete a todo', + [TodosServiceError.UnableToAddTodo]: 'Unable to add a todo', + [TodosServiceError.UnableToUpdateTodo]: 'Unable to update a todo', +}; + +export function getTodoError(errorKey: TodosServiceError): string { + return TODOS_ERROR_MESSAGES[errorKey]; +} diff --git a/src/components/AddTodoForm.tsx b/src/components/AddTodoForm.tsx new file mode 100644 index 0000000000..e98148b9bb --- /dev/null +++ b/src/components/AddTodoForm.tsx @@ -0,0 +1,63 @@ +import { FormEventHandler, forwardRef, useCallback, useState } from 'react'; +import { getTodoError, TodosServiceError } from '../api/todos'; +import { Todo } from '../types/Todo'; + +export type AddTodoFormData = { + title: string; +}; + +type AddTodoFormProps = { + onSubmit: ( + value: AddTodoFormData, + callbacks?: { + onSuccess?: (createdTodo: Todo) => void; + onError?: () => void; + }, + ) => void; + onError: (notification: string) => void; +}; + +export const AddTodoForm = forwardRef( + ({ onSubmit, onError }, ref) => { + const [newTodoTitle, setNewTodoTitle] = useState(''); + const clearTodoTitle = useCallback(() => setNewTodoTitle(''), []); + + const handleSubmit: FormEventHandler = event => { + event.preventDefault(); + + const prepearedNewTodoTitle = newTodoTitle.trim(); + + if (prepearedNewTodoTitle === '') { + onError(getTodoError(TodosServiceError.TitleShouldNotBeEmpty)); + + return; + } + + onSubmit( + { title: prepearedNewTodoTitle }, + { + onSuccess: () => { + clearTodoTitle(); + }, + }, + ); + }; + + return ( +
+ setNewTodoTitle(event.target.value.trimStart())} + /> +
+ ); + }, +); + +AddTodoForm.displayName = 'AddTodoForm'; diff --git a/src/components/ErrorNotification.tsx b/src/components/ErrorNotification.tsx new file mode 100644 index 0000000000..299c4c801b --- /dev/null +++ b/src/components/ErrorNotification.tsx @@ -0,0 +1,30 @@ +import cn from 'classnames'; +type ErrorNotificationProps = { + notification: string; + onClear: () => void; +}; + +export function ErrorNotification({ + notification, + onClear, +}: ErrorNotificationProps) { + const hideNotification = notification === ''; + + return ( +
+
+ ); +} diff --git a/src/components/RenameTodoForm.tsx b/src/components/RenameTodoForm.tsx new file mode 100644 index 0000000000..6bc8b17f9f --- /dev/null +++ b/src/components/RenameTodoForm.tsx @@ -0,0 +1,63 @@ +import { FormEventHandler, useState } from 'react'; + +export type RenameTodoFormProps = { + defaultValue: string; + onSubmit: (value: string) => void; + onClose: () => void; + onDelete: () => void; +}; + +export function RenameTodoForm({ + defaultValue, + onSubmit, + onClose, + onDelete, +}: RenameTodoFormProps) { + const [newTitle, setNewTitle] = useState(defaultValue); + + const handleProcessNewTitle = () => { + const prepearedTitle = newTitle.trim(); + + if (prepearedTitle === defaultValue) { + onClose(); + + return; + } + + if (prepearedTitle === '') { + onDelete(); + + return; + } + + onSubmit(prepearedTitle); + }; + + const handleSubmit: FormEventHandler = event => { + event.preventDefault(); + + handleProcessNewTitle(); + }; + + const handleKeyDown = (event: React.KeyboardEvent) => { + if (event.key === 'Escape') { + onClose(); + } + }; + + return ( +
+ setNewTitle(event.target.value)} + autoFocus + onBlur={handleProcessNewTitle} + onKeyDown={handleKeyDown} + /> +
+ ); +} diff --git a/src/components/StatusFilter.tsx b/src/components/StatusFilter.tsx new file mode 100644 index 0000000000..30e453948f --- /dev/null +++ b/src/components/StatusFilter.tsx @@ -0,0 +1,51 @@ +import cn from 'classnames'; + +export enum TodoStatus { + All = 'all', + Active = 'active', + Completed = 'completed', +} + +type StatusFilterProps = { + value: TodoStatus; + onValueChange: (value: TodoStatus) => void; +}; + +export function StatusFilter({ value, onValueChange }: StatusFilterProps) { + return ( + + ); +} diff --git a/src/components/TodoItem.tsx b/src/components/TodoItem.tsx new file mode 100644 index 0000000000..b84c1af56e --- /dev/null +++ b/src/components/TodoItem.tsx @@ -0,0 +1,132 @@ +/* eslint-disable jsx-a11y/label-has-associated-control */ +import cn from 'classnames'; +import { Todo } from '../types/Todo'; +import { TodoUpdate } from '../types/TodoUpdate'; +import { useCallback, useState } from 'react'; +import { RenameTodoForm } from './RenameTodoForm'; + +type TodoItemProps = { + todo: Todo; + loading: boolean; + onDelete?: (todoId: number) => void; + onUpdate?: ( + todoId: number, + data: TodoUpdate, + callbacks?: { + onSuccess?: (updatedTodo: Todo) => void; + onError?: () => void; + }, + ) => void; +}; + +export function TodoItem({ + todo, + loading = false, + onDelete = () => undefined, + onUpdate = () => undefined, +}: TodoItemProps) { + const [renaming, setRenaming] = useState(false); + + const handleToggleStatus = useCallback( + (completed: boolean) => { + const { id, ...updatedTodo }: Todo = { + ...todo, + completed, + }; + + onUpdate(id, { + title: updatedTodo.title, + completed: updatedTodo.completed, + userId: updatedTodo.userId, + }); + }, + [todo, onUpdate], + ); + + const handleRenameTodo = useCallback( + (title: string) => { + const { id, ...updatedTodo }: Todo = { + ...todo, + title, + }; + + onUpdate( + id, + { + title: updatedTodo.title, + completed: updatedTodo.completed, + userId: updatedTodo.userId, + }, + { + onSuccess: () => { + setRenaming(false); + }, + }, + ); + }, + [todo, onUpdate], + ); + + const handleRemoveButton = () => { + onDelete(todo.id); + }; + + return ( +
+ + + {renaming ? ( + setRenaming(false)} + onDelete={() => onDelete(todo.id)} + /> + ) : ( + <> + { + setRenaming(true); + }} + > + {todo.title} + + + + + )} + +
+
+
+
+
+ ); +} diff --git a/src/hooks/useErrorMessage.ts b/src/hooks/useErrorMessage.ts new file mode 100644 index 0000000000..01b1911034 --- /dev/null +++ b/src/hooks/useErrorMessage.ts @@ -0,0 +1,25 @@ +import { useCallback, useEffect, useState } from 'react'; + +export function useErrorMessage() { + const [errorMessage, setErrorMessage] = useState(''); + + const handleResetErrorMessage = useCallback(() => { + setErrorMessage(''); + }, []); + + useEffect(() => { + const timeoutId = setTimeout(() => { + handleResetErrorMessage(); + }, 3000); + + return () => { + clearTimeout(timeoutId); + }; + }, [errorMessage, handleResetErrorMessage]); + + return { + errorMessage, + resetErrorMessage: handleResetErrorMessage, + setErrorMessage, + }; +} 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/TodoCreate.ts b/src/types/TodoCreate.ts new file mode 100644 index 0000000000..5a6321c696 --- /dev/null +++ b/src/types/TodoCreate.ts @@ -0,0 +1,5 @@ +export type TodoCreate = { + title: string; + userId: number; + completed: boolean; +}; diff --git a/src/types/TodoUpdate.ts b/src/types/TodoUpdate.ts new file mode 100644 index 0000000000..8a8670d5aa --- /dev/null +++ b/src/types/TodoUpdate.ts @@ -0,0 +1,5 @@ +export type TodoUpdate = { + 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/getSortedTodos.ts b/src/utils/getSortedTodos.ts new file mode 100644 index 0000000000..1be5655d46 --- /dev/null +++ b/src/utils/getSortedTodos.ts @@ -0,0 +1,19 @@ +import { Todo } from '../types/Todo'; + +export function getSortedTodos(todos: Todo[]) { + const completed: Todo[] = []; + const active: Todo[] = []; + + for (const todo of todos) { + if (todo.completed) { + completed.push(todo); + } else { + active.push(todo); + } + } + + return { + active: active, + completed: completed, + }; +}