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

todo app #1053

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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://OMedvid.github.io/react_todo-app/) and add it to the PR description.
164 changes: 21 additions & 143 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,156 +1,34 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useContext, useMemo, useState } from 'react';

import { Header } from './components/Header';
import { Main as TodoList } from './components/todoList';
import { Footer } from './components/Footer';
import { IsActiveTab } from './types';
import { TodosContext } from './Store';
import { filterTodos } from './utils/filterTodos';

export const App: React.FC = () => {
const { todos } = useContext(TodosContext);
const [isActive, setIsActiveTab] = useState(IsActiveTab.All);

Choose a reason for hiding this comment

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

Suggested change
const [isActive, setIsActiveTab] = useState(IsActiveTab.All);
const [activeTab, setActiveTab] = useState(IsActiveTab.All);


const visibleTodos = useMemo(
() => filterTodos(todos, isActive),
[todos, isActive],
);

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

<div className="todoapp__content">
<header className="todoapp__header">
{/* this button should have `active` class only if all todos are completed */}
<button
type="button"
className="todoapp__toggle-all active"
data-cy="ToggleAllButton"
/>

{/* Add a todo on form submit */}
<form>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
/>
</form>
</header>

<section className="todoapp__main" data-cy="TodoList">
{/* This is a completed todo */}
<div data-cy="Todo" className="todo completed">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
checked
/>
</label>

<span data-cy="TodoTitle" className="todo__title">
Completed Todo
</span>

{/* Remove button appears only on hover */}
<button type="button" className="todo__remove" data-cy="TodoDelete">
×
</button>
</div>

{/* This todo is an active todo */}
<div data-cy="Todo" className="todo">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
/>
</label>

<span data-cy="TodoTitle" className="todo__title">
Not Completed Todo
</span>

<button type="button" className="todo__remove" data-cy="TodoDelete">
×
</button>
</div>

{/* This todo is being edited */}
<div data-cy="Todo" className="todo">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
/>
</label>

{/* This form is shown instead of the title and remove button */}
<form>
<input
data-cy="TodoTitleField"
type="text"
className="todo__title-field"
placeholder="Empty todo will be deleted"
value="Todo is being edited now"
/>
</form>
</div>

{/* This todo is in loadind state */}
<div data-cy="Todo" className="todo">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
/>
</label>

<span data-cy="TodoTitle" className="todo__title">
Todo is being saved now
</span>

<button type="button" className="todo__remove" data-cy="TodoDelete">
×
</button>
</div>
</section>

{/* Hide the footer if there are no todos */}
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
3 items left
</span>

{/* Active link should have the 'selected' class */}
<nav className="filter" data-cy="Filter">
<a
href="#/"
className="filter__link selected"
data-cy="FilterLinkAll"
>
All
</a>

<a
href="#/active"
className="filter__link"
data-cy="FilterLinkActive"
>
Active
</a>
<Header />

<a
href="#/completed"
className="filter__link"
data-cy="FilterLinkCompleted"
>
Completed
</a>
</nav>
{todos.length > 0 && <TodoList filteredTodos={visibleTodos} />}

{/* this button should be disabled if there are no completed todos */}
<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
>
Clear completed
</button>
</footer>
{todos.length > 0 && (
<Footer isActive={isActive} setIsActiveTab={setIsActiveTab} />
)}
</div>
</div>
);
Expand Down
42 changes: 42 additions & 0 deletions src/Store.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { createContext, useMemo, useState } from 'react';
import { Todo } from './types';
import React from 'react';

function useLocalStorage(key: string, defaultValue: Todo[]) {
const [todos, setTodos] = useState(() => {
const savedTodos = localStorage.getItem(key);

if (savedTodos === null) {
localStorage.setItem('todos', JSON.stringify(defaultValue));

return JSON.parse(localStorage.getItem('todos') as string);
} else {
return JSON.parse(savedTodos);
}
});

function saveTodos(newTodos: Todo[]) {
setTodos(newTodos);

localStorage.setItem(key, JSON.stringify(newTodos));
}

return [todos, saveTodos] as const;
}

export const TodosContext = createContext({
todos: [],
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setTodos: (_newTodos: Todo[]) => {},
});

export const TodosProvider = ({ children }: { children: React.ReactNode }) => {
const [todos, setTodos] = useLocalStorage('todos', []);

// eslint-disable-next-line react-hooks/exhaustive-deps
const value = useMemo(() => ({ todos, setTodos }), [todos]);

return (
<TodosContext.Provider value={value}>{children}</TodosContext.Provider>
);
};
15 changes: 15 additions & 0 deletions 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>
);
58 changes: 58 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import React, { useContext } from 'react';
import classNames from 'classnames';
import { PropsFooter, Todo, IsActiveTab } from '../types';
import { TodosContext } from '../Store';

export const Footer: React.FC<PropsFooter> = ({ isActive, setIsActiveTab }) => {
const { todos, setTodos } = useContext(TodosContext);

function handleClearCompleted() {
const newList = todos.filter((todo: Todo) => !todo.completed);

setTodos(newList);
}

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

const tabs = Object.values(IsActiveTab);

return (
// {/* Hide the footer if there are no todos */}
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{`${activeTodos.length} items left`}
</span>

{/* Active link should have the 'selected' class */}
<nav className="filter" data-cy="Filter">
{tabs.map(tab => (
<a
key={tab}
href={`#/${tab.toLowerCase()}`}
className={classNames('filter__link', {
selected: isActive === tab,
})}
data-cy={`FilterLink${tab}`}
onClick={() => {
setIsActiveTab(tab);
}}
>
{tab}
</a>
))}
</nav>

{/* this button should be disabled if there are no completed todos */}
<button
disabled={completedTodos ? false : true}
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={handleClearCompleted}
>
Clear completed
</button>
</footer>
);
};
64 changes: 64 additions & 0 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import React, { useContext, useState } from 'react';
import classNames from 'classnames';
import { Todo } from '../types';
import { TodosContext } from '../Store';

export const Header: React.FC = () => {
const [query, setQuery] = useState('');
const { todos, setTodos } = useContext(TodosContext);

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

if (query) {
setTodos([
...todos,
{ id: `${+new Date()}`, title: query.trim(), completed: false },
]);
}

setQuery('');
}

const isAllCompleted = todos.every((todo: Todo) => todo.completed === true);

function handleToggle(completed: boolean) {
const newList = todos.map((todo: Todo) => {
return { ...todo, completed: !completed };
});

setTodos(newList);
}

return (
<header className="todoapp__header">
{/* this button should have `active` class only if all todos are completed */}
{todos.length > 0 && (
<button
defaultChecked={isAllCompleted ? true : false}
type="button"
className={classNames('todoapp__toggle-all', {
active: isAllCompleted,
})}
data-cy="ToggleAllButton"
onClick={() => handleToggle(isAllCompleted)}
/>
)}

{/* Add a todo on form submit */}
<form onSubmit={event => handleSubmit(event)}>
<input
ref={input => input && input.focus()}
value={query}
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
onChange={event => {
setQuery(event.target.value.trimStart());
}}
/>
</form>
</header>
);
};
Loading
Loading