diff --git a/README.md b/README.md index 47a1add059..c91c47d1bd 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://antonnimachuk.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..5a940b477e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,26 +1,235 @@ -/* eslint-disable max-len */ -/* eslint-disable jsx-a11y/control-has-associated-label */ -import React from 'react'; +import React, { useState, useEffect, useRef } from 'react'; import { UserWarning } from './UserWarning'; - -const USER_ID = 0; +import * as clientMethods from './api/todos'; +import type { Todo } from './types/Todo'; +import { NewTodoForm } from './components/NewTodoForm'; +import { TodoList } from './components/TodoList'; +import { ErrorType } from './types/ErrorType'; +import { FilterType } from './types/FilterType'; +import { TodoItem } from './components/TodoItem'; +import classNames from 'classnames'; export const App: React.FC = () => { - if (!USER_ID) { + const [todos, setTodos] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(ErrorType.None); + const [selectedFilterLink, setSelectedFilterLink] = useState(FilterType.All); + const [tempTodo, setTempTodo] = useState(null); + const [loadingIds, setLoadingIds] = useState([]); + + const inputFocusRef = useRef(null); + + const completedTodos = todos.filter(todo => todo.completed); + const activeTodos = todos.filter(todo => !todo.completed); + const allTodosCompleted = + todos.length > 0 && todos.every(todo => todo.completed); + + const filterLinks = [ + { + label: 'All', + value: FilterType.All, + href: '#/', + dataCy: 'FilterLinkAll', + }, + { + label: 'Active', + value: FilterType.Active, + href: '#/active', + dataCy: 'FilterLinkActive', + }, + { + label: 'Completed', + value: FilterType.Completed, + href: '#/completed', + dataCy: 'FilterLinkCompleted', + }, + ]; + + const handleAddTodo = (newTodo: Todo): void => { + setTodos([...todos, newTodo]); + }; + + const handleDelete = async (deleteId: number) => { + setLoadingIds(current => [...current, deleteId]); + + try { + await clientMethods.deleteTodo(deleteId); + setTodos(current => current.filter(todo => todo.id !== deleteId)); + } catch (err) { + setError(ErrorType.Delete); + throw err; + } finally { + setLoadingIds(current => current.filter(id => id !== deleteId)); + inputFocusRef.current?.focus(); + } + }; + + const handleClearCompleted = () => { + Promise.all(completedTodos.map(todo => handleDelete(todo.id))).catch( + () => {}, + ); + }; + + const handleUpdate = async (id: number, todoData: Partial) => { + setLoadingIds(current => [...current, id]); + + try { + await clientMethods.updateTodo(id, todoData); + setTodos(current => + current.map(todo => (todo.id === id ? { ...todo, ...todoData } : todo)), + ); + } catch (err) { + setError(ErrorType.Update); + throw err; + } finally { + setLoadingIds(current => current.filter(item => item !== id)); + } + }; + + const handleToggleAll = () => { + const targetStatus = !allTodosCompleted; + const todosToUpdate = todos.filter(todo => todo.completed !== targetStatus); + + Promise.all( + todosToUpdate.map(todo => + handleUpdate(todo.id, { completed: targetStatus }), + ), + ).catch(() => {}); + }; + + useEffect(() => { + const loadTodos = async () => { + try { + const loadedTodos = await clientMethods.getTodos(); + + setTodos(loadedTodos); + } catch (err) { + setError(ErrorType.Load); + } finally { + setIsLoading(false); + } + }; + + loadTodos(); + }, []); + + useEffect(() => { + if (!error) { + return; + } + + const timer = setTimeout(() => setError(ErrorType.None), 3000); + + return () => clearTimeout(timer); + }, [error]); + + let filteredTodos = todos; + + switch (selectedFilterLink) { + case FilterType.Active: + filteredTodos = todos.filter(todo => !todo.completed); + break; + case FilterType.Completed: + filteredTodos = todos.filter(todo => todo.completed); + break; + default: + filteredTodos = todos; + break; + } + + if (!clientMethods.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 > 0 && ( +
+ +
+ {!isLoading && ( + <> + + {tempTodo && } + + )} +
+ + {todos.length > 0 && ( + + )} +
+ +
+
+
); }; diff --git a/src/api/todos.ts b/src/api/todos.ts new file mode 100644 index 0000000000..6cb35b42a7 --- /dev/null +++ b/src/api/todos.ts @@ -0,0 +1,22 @@ +import { Todo } from '../types/Todo'; +import { client } from '../utils/fetchClient'; + +export const USER_ID = 4133; + +export const getTodos = () => { + return client.get(`/todos?userId=${USER_ID}`); +}; + +export const addTodo = (todoData: Omit): Promise => { + return client.post('/todos', todoData); +}; + +export const deleteTodo = (id: number) => { + return client.delete(`/todos/${id}`); +}; + +export const updateTodo = (id: number, todoData: Partial | undefined) => { + return client.patch(`/todos/${id}`, todoData); +}; + +// Add more methods here diff --git a/src/components/NewTodoForm/NewTodoForm.tsx b/src/components/NewTodoForm/NewTodoForm.tsx new file mode 100644 index 0000000000..50fcbe433e --- /dev/null +++ b/src/components/NewTodoForm/NewTodoForm.tsx @@ -0,0 +1,79 @@ +import React, { useState, useEffect } from 'react'; +import type { Todo } from '../../types/Todo'; +import { ErrorType } from '../../types/ErrorType'; +import * as clientMethods from '../../api/todos'; + +type Props = { + onAdd: (value: Todo) => void; + onError: (message: ErrorType) => void; + setTempTodo: (tempTodo: Todo | null) => void; + inputFocusRef: React.RefObject; +}; + +export const NewTodoForm: React.FC = ({ + onAdd, + onError, + setTempTodo, + inputFocusRef, +}) => { + const [title, setTitle] = useState(''); + const [isSubmiting, setIsSubmiting] = useState(false); + + useEffect(() => { + if (!isSubmiting) { + inputFocusRef.current?.focus(); + } + }, [isSubmiting, inputFocusRef]); + + const handleSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + // 1. Validate + if (!title.trim()) { + onError(ErrorType.EmptyTitle); + + return; + } + + try { + setIsSubmiting(true); + + setTempTodo({ + id: 0, + userId: clientMethods.USER_ID, + title: title.trim(), + completed: false, + }); + + const createdTodo = await clientMethods.addTodo({ + userId: clientMethods.USER_ID, + title: title.trim(), + completed: false, + }); + + onAdd(createdTodo); + onError(ErrorType.None); + setTitle(''); + } catch { + onError(ErrorType.Add); + } finally { + setTempTodo(null); + setIsSubmiting(false); + } + // 2. Clear previous error + }; + + return ( +
+ setTitle(event.target.value)} + disabled={isSubmiting} + ref={inputFocusRef} + /> +
+ ); +}; diff --git a/src/components/NewTodoForm/index.ts b/src/components/NewTodoForm/index.ts new file mode 100644 index 0000000000..e58e9e081e --- /dev/null +++ b/src/components/NewTodoForm/index.ts @@ -0,0 +1 @@ +export * from './NewTodoForm'; diff --git a/src/components/TodoItem/TodoItem.scss b/src/components/TodoItem/TodoItem.scss new file mode 100644 index 0000000000..2932342b00 --- /dev/null +++ b/src/components/TodoItem/TodoItem.scss @@ -0,0 +1 @@ +// TodoItem styles diff --git a/src/components/TodoItem/TodoItem.tsx b/src/components/TodoItem/TodoItem.tsx new file mode 100644 index 0000000000..5f9c469e8f --- /dev/null +++ b/src/components/TodoItem/TodoItem.tsx @@ -0,0 +1,115 @@ +import React, { useState } from 'react'; +import type { Todo } from '../../types/Todo'; + +type Props = { + todo: Todo; + isLoading?: boolean; + onDelete?: (id: number) => Promise; + handleUpdate?: (id: number, todoData: Partial) => Promise; +}; + +export const TodoItem: React.FC = ({ + todo, + isLoading, + onDelete, + handleUpdate, +}) => { + const [isEditing, setIsEditing] = useState(false); + const [inputValue, setInputValue] = useState(todo.title); + + const save = async () => { + const trimmed = inputValue.trim(); + + if (trimmed === todo.title) { + setIsEditing(false); + + return; + } + + try { + if (trimmed === '') { + await onDelete?.(todo.id); + } else { + await handleUpdate?.(todo.id, { title: trimmed }); + setIsEditing(false); + } + } catch { + // On failure keep the form open so the user can retry. + } + }; + + const handleSubmit = (event: React.FormEvent) => { + event.preventDefault(); + save(); + }; + + const handleKeyUp = (event: React.KeyboardEvent) => { + if (event.key === 'Escape') { + setInputValue(todo.title); + setIsEditing(false); + } + }; + + return ( +
+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */} + + + {isEditing ? ( +
+ setInputValue(event.target.value)} + onBlur={save} + onKeyUp={handleKeyUp} + autoFocus + /> +
+ ) : ( + <> + { + setIsEditing(true); + setInputValue(todo.title); + }} + > + {todo.title} + + + + + )} + +
+
+
+
+
+ ); +}; diff --git a/src/components/TodoItem/index.ts b/src/components/TodoItem/index.ts new file mode 100644 index 0000000000..21f4abac39 --- /dev/null +++ b/src/components/TodoItem/index.ts @@ -0,0 +1 @@ +export * from './TodoItem'; diff --git a/src/components/TodoList/TodoList.tsx b/src/components/TodoList/TodoList.tsx new file mode 100644 index 0000000000..e08da61f14 --- /dev/null +++ b/src/components/TodoList/TodoList.tsx @@ -0,0 +1,30 @@ +/* eslint-disable */ + +import { TodoItem } from '../TodoItem'; +import type { Todo } from '../../types/Todo'; + +type Props = { + todos: Todo[]; + onDelete: (id: number) => Promise; + loadingIds: number[]; + handleUpdate?: (id: number, todoData: Partial) => Promise; +}; + +export const TodoList: React.FC = ({ + todos, + onDelete, + loadingIds, + handleUpdate, +}) => ( + <> + {todos.map(todo => ( + + ))} + +); diff --git a/src/components/TodoList/index.ts b/src/components/TodoList/index.ts new file mode 100644 index 0000000000..f239f43459 --- /dev/null +++ b/src/components/TodoList/index.ts @@ -0,0 +1 @@ +export * from './TodoList'; diff --git a/src/components/TodoRoadMap.js b/src/components/TodoRoadMap.js new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/components/ToggleAllButton/ToggleAllButton.tsx b/src/components/ToggleAllButton/ToggleAllButton.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/components/ToggleAllButton/index.js b/src/components/ToggleAllButton/index.js new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/types/ErrorType.ts b/src/types/ErrorType.ts new file mode 100644 index 0000000000..9cd03ed844 --- /dev/null +++ b/src/types/ErrorType.ts @@ -0,0 +1,8 @@ +export enum ErrorType { + None = '', + Load = 'Unable to load todos', + Add = 'Unable to add a todo', + Delete = 'Unable to delete a todo', + Update = 'Unable to update a todo', + EmptyTitle = 'Title should not be empty', +} diff --git a/src/types/FilterType.ts b/src/types/FilterType.ts new file mode 100644 index 0000000000..5b306c57d0 --- /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'), +};