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

Develop #1073

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Develop #1073

Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@ Implement a simple [TODO app](https://mate-academy.github.io/react_todo-app/) th
- Implement a solution following the [React task guidelines](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).
- Open another terminal and run tests with `npm test` to ensure your solution is correct.
- Replace `<your_account>` with your GitHub username in the [DEMO LINK](https://<your_account>.github.io/react_todo-app/) and add it to the PR description.
- Replace `<your_account>` with your GitHub username in the [DEMO LINK](https://GGLUTT.github.io/react_todo-app/) and add it to the PR description.
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,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",
Expand Down
28 changes: 28 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Todo } from '../src/types/Todo';
import { client } from '../src/utils/fetchClient';

export const USER_ID = 1011;

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

export const addTodo = ({
title,
completed,
userId,
}: Omit<Todo, 'id'> & { userId: number }) => {
return client.post<Todo>('/todos', {
title,
completed,
userId,
});
};

export const deleteTodo = (todoId: number) => {
return client.delete(`/todos/${todoId}`);
};

export const updateTodo = (todo: Todo) => {
return client.patch<Todo>(`/todos/${todo.id}`, todo);
};
17 changes: 9 additions & 8 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { createRoot } from 'react-dom/client';

import './styles/index.css';
import './styles/todo-list.css';
import './styles/filters.css';

import 'bulma/css/bulma.css';
import '@fortawesome/fontawesome-free/css/all.css';
import './styles/index.scss';
import { App } from './App';
import { TodoProvider } from './src/components/context/TodoContext';

const container = document.getElementById('root') as HTMLDivElement;

createRoot(container).render(<App />);
createRoot(document.getElementById('root') as HTMLDivElement).render(
<TodoProvider>
<App />
</TodoProvider>,
);
4 changes: 4 additions & 0 deletions src/src/App.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
html {
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;

}
56 changes: 56 additions & 0 deletions src/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import React, { useEffect, useRef } from 'react';
import { Filter } from './types/Filter';
import { TodoList } from './components/TodoList/TodoList';
import { Header } from './components/Header/Header';
import { Footer } from './components/Footer/Footer';
import { ErrorNotification } from './components/Error/ErrorNotify';
import { TodoItem } from './components/TodoItem/TodoItem';
import { useTodoContext } from './components/context/TodoContext';

export const App: React.FC = () => {
const { state } = useTodoContext();
const { todos, filter, tempTodo } = state;
const textField = useRef<HTMLInputElement>(null);

const completedTodos = todos.filter(todo => todo.completed);
const activeTodos = todos.filter(todo => !todo.completed);

const filteredTodos = () => {
switch (filter) {
case Filter.Completed:
return completedTodos;
case Filter.Active:
return activeTodos;
default:
return todos;
}
};

useEffect(() => {
if (textField.current) {
textField.current.focus();
}
}, [todos.length]);

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

<div className="todoapp__content">
<Header completedTodos={completedTodos} textField={textField} />

<section className="todoapp__main" data-cy="TodoList">
<TodoList todos={filteredTodos()} />

{tempTodo && <TodoItem todo={tempTodo} isLoading={true} />}
</section>

{todos.length > 0 && (
<Footer activeTodos={activeTodos} completedTodos={completedTodos} />
)}
</div>

<ErrorNotification />
</div>
);
};
15 changes: 15 additions & 0 deletions src/src/UserWarning.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React from 'react';

export const UserWarning: React.FC = () => (
<section className="section">
<p className="box is-size-3">
Please get your <b> userId </b>{' '}
<a href="https://mate-academy.github.io/react_student-registration">
here
</a>{' '}
and save it in the app <pre>const USER_ID = ...</pre>
All requests to the API must be sent with this
<b> userId.</b>
</p>
</section>
);
42 changes: 42 additions & 0 deletions src/src/components/Error/ErrorNotify.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React, { useEffect } from 'react';
import classNames from 'classnames';
import { useTodoContext } from '../context/TodoContext';

export const ErrorNotification: React.FC = () => {
const { state, dispatch } = useTodoContext();
const { errorText } = state;

useEffect(() => {
if (errorText) {
const timer = setTimeout(() => {
dispatch({ type: 'SET_ERROR', payload: null });
}, 3000);

return () => clearTimeout(timer);
}

return () => {};
}, [errorText, dispatch]);

if (!errorText) {
return null;
}

return (
<div
data-cy="ErrorNotification"
className={classNames(
'notification is-danger is-light has-text-weight-normal',
{ hidden: errorText },
)}
>
<button
onClick={() => dispatch({ type: 'SET_ERROR', payload: null })}
data-cy="HideErrorButton"
type="button"
className="delete"
/>
{errorText}
</div>
);
};
75 changes: 75 additions & 0 deletions src/src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import React from 'react';
import classNames from 'classnames';
import { Filter } from '../../types/Filter';
import { Error } from '../../types/Error';
import { useTodoContext } from '../context/TodoContext';
import { Todo } from '../../types/Todo';

type Props = {
activeTodos: Todo[];
completedTodos: Todo[];
};

export const Footer: React.FC<Props> = ({ activeTodos, completedTodos }) => {
const { state, dispatch } = useTodoContext();
const { filter } = state;

const handleClearCompleted = async () => {
const completedIds = completedTodos.map(todo => todo.id);

dispatch({ type: 'SET_DELETING_IDS', payload: completedIds });

try {
dispatch({ type: 'CLEAR_COMPLETED' });
} catch {
dispatch({
type: 'SET_ERROR',
payload: Error.unableToDelete,
});
setTimeout(() => {
dispatch({ type: 'SET_ERROR', payload: null });
}, 3000);
} finally {
dispatch({ type: 'SET_DELETING_IDS', payload: [] });
}
};

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeTodos.length} items left
</span>

<nav className="filter" data-cy="Filter">
{Object.values(Filter).map(filterOption => (
<a
key={filterOption}
href={`#/${filterOption.toLowerCase()}`}
onClick={() =>
dispatch({
type: 'SET_FILTER',
payload: filterOption,
})
}
className={classNames('filter__link', {
selected: filter === filterOption,
})}
data-cy={`FilterLink${filterOption}`}
>
{filterOption}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={handleClearCompleted}
disabled={completedTodos.length === 0}
>
Clear completed
</button>
</footer>
);
};
89 changes: 89 additions & 0 deletions src/src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import React from 'react';
import classNames from 'classnames';
import { Todo } from '../../types/Todo';
import { Error } from '../../types/Error';
import { useTodoContext } from '../context/TodoContext';

type Props = {
completedTodos: Todo[];
textField: React.RefObject<HTMLInputElement>;
};

export const Header: React.FC<Props> = ({ completedTodos, textField }) => {
const { state, dispatch } = useTodoContext();
const { todos, query, isLoading } = state;

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

if (!query.trim()) {
dispatch({ type: 'SET_ERROR', payload: Error.titleShouldNotBeEmpty });
setTimeout(() => {
dispatch({ type: 'SET_ERROR', payload: null });
}, 3000);

return;
}

const newTodo: Todo = {
id: Date.now(),
title: query.trim(),
completed: false,
};

dispatch({ type: 'SET_LOADING', payload: true });
dispatch({ type: 'SET_TEMP_TODO', payload: newTodo });

try {
dispatch({ type: 'ADD_TODO', payload: newTodo });
dispatch({ type: 'SET_QUERY', payload: '' });
} catch (error) {
dispatch({ type: 'SET_ERROR', payload: Error.unableToAdd });
setTimeout(() => {
dispatch({ type: 'SET_ERROR', payload: null });
}, 3000);
} finally {
dispatch({ type: 'SET_LOADING', payload: false });
dispatch({ type: 'SET_TEMP_TODO', payload: null });
}
};

const handleToggleAll = () => {
const areAllCompleted = todos.every(todo => todo.completed);

dispatch({ type: 'TOGGLE_ALL', payload: !areAllCompleted });
};

return (
<header className="todoapp__header">
{todos.length > 0 && (
<button
type="button"
className={classNames('todoapp__toggle-all', {
active: todos.length === completedTodos.length,
})}
data-cy="ToggleAllButton"
onClick={handleToggleAll}
/>
)}

<form onSubmit={handleSubmit}>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
ref={textField}
value={query}
onChange={e =>
dispatch({
type: 'SET_QUERY',
payload: e.target.value,
})
}
disabled={isLoading}
/>
</form>
</header>
);
};
3 changes: 3 additions & 0 deletions src/src/components/Header/header.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
header{
background-color: azure;
}
Loading
Loading