Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solutiion #1511

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 13 additions & 23 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
// /* eslint-disable jsx-a11y/control-has-associated-label */
// /* eslint-disable jsx-a11y/label-has-associated-control */

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}

return (
<section className="section container">
<p className="title is-4">
Copy all you need from the prev task:
<br />
<a href="https://github.com/mate-academy/react_todo-app-add-and-delete#react-todo-app-add-and-delete">
React Todo App - Add and Delete
</a>
</p>
import { USER_ID } from './api/todos';
import { Todos } from './components/Todo/Todos';
import { TodosProvider } from './context/TodoContext';
import { UserWarning } from './UserWarning';

<p className="subtitle">Styles are already copied</p>
</section>
export const App = () =>
!USER_ID ? (
<UserWarning />
) : (
<TodosProvider>
<Todos />
</TodosProvider>
);
};
24 changes: 24 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { TODOS_API_PATH } from '../constants/api';
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 1826;

export const getTodos = () => {
return client.get<Todo[]>(`${TODOS_API_PATH}?userId=${USER_ID}`);
};

export const getTodoById = (id: number) => client.get(`/todos/${id}`);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here we can also use TODOS_API_PATH


export const getAllCompletedTodoByUserId = (id: number) => {
client.get(`${TODOS_API_PATH}?userId=${id}&completed=true`);
};

export const addTodo = ({ title, completed, userId }: Omit<Todo, 'id'>) =>
client.post<Todo>(TODOS_API_PATH, { title, completed, userId });

export const updateTodo = (todo: Todo, id: number): Promise<Todo> =>
client.patch(`${TODOS_API_PATH}/${id}`, todo);

export const deleteTodo = (id: number) =>
client.delete(`${TODOS_API_PATH}/${id}`);
20 changes: 20 additions & 0 deletions src/components/ErrorNotification/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { FC } from 'react';
import { getTodoErrorsMessage } from '../../utils/todos/getTodoErrorsMessage';
import cn from 'classnames';
import { TodoErrors } from '../../utils/enums/TodoErrors';

interface ErrorNotificationProps {
error: TodoErrors | null;
}

export const ErrorNotification: FC<ErrorNotificationProps> = ({ error }) => (
<div
data-cy="ErrorNotification"
className={cn('notification is-danger is-light has-text-weight-normal', {
hidden: !error,
})}
>
<button data-cy="HideErrorButton" type="button" className="delete" />
{error && getTodoErrorsMessage(error)}
</div>
);
61 changes: 61 additions & 0 deletions src/components/Todo/TodoFooter/TodoFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Dispatch, FC, SetStateAction } from 'react';
import cn from 'classnames';

import { Todo } from '../../../types/Todo';
import { TODO_FILTER_OPTIONS } from '../../../constants/TodoFilter';

import { FilterStatuses } from '../../../utils/enums/FilterStatuses';
import {
getInCompletedTodos,
hasCompletedTodos,
} from '../../../utils/todos/getTodos';
import { useDeleteTodo } from '../../../hooks/useDeleteTodo';

interface TodoFooterProps {
todos: Todo[];
setStatus: Dispatch<SetStateAction<FilterStatuses>>;
status: FilterStatuses;
}

export const TodoFooter: FC<TodoFooterProps> = ({
todos,
setStatus,
status,
}) => {
const isCompletedTodoCounter = getInCompletedTodos(todos).length;
const { handleDeleteCompletedTodos } = useDeleteTodo();

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{isCompletedTodoCounter}
{isCompletedTodoCounter === 1 ? ' item ' : ' items '}
left
</span>

<nav className="filter" data-cy="Filter">
{TODO_FILTER_OPTIONS.map(({ value, title, href, id }) => (
<a
href={href}
className={cn('filter__link', { selected: status === value })}
data-cy={`FilterLink${title}`}
key={id}
onClick={() => setStatus(value)}
>
{title}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={!hasCompletedTodos(todos)}
onClick={handleDeleteCompletedTodos}
>
Clear completed
</button>
</footer>
);
};
25 changes: 25 additions & 0 deletions src/components/Todo/TodoForm/TodoForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useContext } from 'react';

import { TodosContext } from '../../../context/TodoContext';
import { useTodoFormManager } from '../../../hooks/useTodoFormManager';

export const TodoForm = () => {
const { inputRef } = useContext(TodosContext);
const { title, handleSubmit, handleChangeTitle, isInputDisabled } =
useTodoFormManager();

return (
<form onSubmit={handleSubmit}>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={title}
ref={inputRef}
disabled={isInputDisabled}
onChange={handleChangeTitle}
/>
</form>
);
};
32 changes: 32 additions & 0 deletions src/components/Todo/TodoHeader/TodoHeader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { FC } from 'react';
import cn from 'classnames';

import { Todo } from '../../../types/Todo';
import { isAllTodosCompleted } from '../../../utils/todos/getTodos';
import { TodoForm } from '../TodoForm/TodoForm';
import { useTodoFormManager } from '../../../hooks/useTodoFormManager';

interface TodoHeaderProps {
todos: Todo[];
}

export const TodoHeader: FC<TodoHeaderProps> = ({ todos }) => {
const { handleToogleAllTodoStatus } = useTodoFormManager();

return (
<header className="todoapp__header">
{!!todos.length && (
<button
type="button"
className={cn('todoapp__toggle-all', {
active: isAllTodosCompleted(todos),
})}
data-cy="ToggleAllButton"
onClick={handleToogleAllTodoStatus}
/>
)}

<TodoForm />
</header>
);
};
98 changes: 98 additions & 0 deletions src/components/Todo/TodoItem/TodoItem.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { FC, FormEvent } from 'react';
import { Todo } from '../../../types/Todo';
import cn from 'classnames';
import { useDeleteTodo } from '../../../hooks/useDeleteTodo';
import { useTodoFormManager } from '../../../hooks/useTodoFormManager';
import { useSelectedTodo } from '../../../hooks/useSelectedTodo';

interface TodoItemProps {
todo: Todo;
isLoading?: boolean;
}

export const TodoItem: FC<TodoItemProps> = ({ todo, isLoading = false }) => {
const { completed, id, title } = todo;
const { isDeleting, handleDeleteTodo } = useDeleteTodo();
const { selectedTodo, setSelectedTodo } = useSelectedTodo();
const {
title: updatingTitle,
isUpdating,
setTitle,
handleUpdateTodo,
} = useTodoFormManager(todo.title);

const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();

if (title == updatingTitle) {
return setSelectedTodo(null);
}

const res = await handleUpdateTodo({ ...todo, title: updatingTitle });

if (res) {
setSelectedTodo(null);
}
};

return (
<div data-cy="Todo" className={cn('todo', { completed })}>
{/* eslint-disable jsx-a11y/label-has-associated-control */}
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
checked={completed}
onChange={() => {
handleUpdateTodo({ ...todo, completed: !todo.completed });
}}
/>
</label>

{selectedTodo ? (
<form onSubmit={handleSubmit} onBlur={handleSubmit}>
<input
data-cy="TodoTitleField"
type="text"
className="todo__title-field"
placeholder="Empty todo will be deleted"
value={updatingTitle}
onChange={e => setTitle(e.target.value)}
autoFocus
/>
</form>
) : (
<span
data-cy="TodoTitle"
className="todo__title"
onDoubleClick={() => {
setSelectedTodo(todo);
}}
>
{title.trim()}
</span>
)}
{!selectedTodo && (
<button
type="button"
className="todo__remove"
data-cy="TodoDelete"
onClick={() => handleDeleteTodo(id)}
>
×
</button>
)}

<div
data-cy="TodoLoader"
className={cn('modal overlay', {
'is-active': isLoading || isDeleting || isUpdating,
})}
>
<div className="modal-background has-background-white-ter" />
<div className="loader" />
</div>
</div>
);
};
25 changes: 25 additions & 0 deletions src/components/Todo/TodoList/TodoList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { FC, useContext } from 'react';
import { Todo } from '../../../types/Todo';
import { TodoItem } from '../TodoItem/TodoItem';
import { TodosContext } from '../../../context/TodoContext';

interface TodoListProps {
todos: Todo[];
}

export const TodoList: FC<TodoListProps> = ({ todos }) => {
const { tempTodo } = useContext(TodosContext);

return (
<>
<section className="todoapp__main" data-cy="TodoList">
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} />
))}
</section>
{tempTodo && (
<TodoItem todo={tempTodo} key={tempTodo.id} isLoading={true} />

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
<TodoItem todo={tempTodo} key={tempTodo.id} isLoading={true} />
<TodoItem todo={tempTodo} key={tempTodo.id} isLoading />

can be a bit simplify

)}
</>
);
};
35 changes: 35 additions & 0 deletions src/components/Todo/Todos.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useContext } from 'react';

import { TodoHeader } from './TodoHeader/TodoHeader';
import { TodoList } from './TodoList/TodoList';
import { TodoFooter } from './TodoFooter/TodoFooter';
import { ErrorNotification } from '../ErrorNotification/ErrorNotification';
import { TodosContext } from '../../context/TodoContext';
import { useTodoFilter } from '../../hooks/useTodoFilter';

export const Todos = () => {
const { todos, error } = useContext(TodosContext);
const { filtredTodos, setTodoStatus, todoStatus } = useTodoFilter(todos);

return (
<div className="todoapp">
<h1 className="todoapp__title">todos</h1>

<div className="todoapp__content">
<TodoHeader todos={todos} />

<TodoList todos={filtredTodos} />

{!!todos.length && (
<TodoFooter
todos={todos}
setStatus={setTodoStatus}
status={todoStatus}
/>
)}
</div>

<ErrorNotification error={error} />
</div>
);
};
12 changes: 12 additions & 0 deletions src/constants/TodoFilter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { FilterStatuses } from '../utils/enums/FilterStatuses';

export const TODO_FILTER_OPTIONS = [
{ value: FilterStatuses.All, title: 'All', href: '#/', id: 1 },
{ value: FilterStatuses.Active, title: 'Active', href: '#/active', id: 2 },
{
value: FilterStatuses.Completed,
title: 'Completed',
href: '#/completed',
id: 3,
},
];
1 change: 1 addition & 0 deletions src/constants/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const TODOS_API_PATH = '/todos';
Loading
Loading