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

solution 0.01 #1090

Open
wants to merge 1 commit 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://StanislavKapytsia.github.io/react_todo-app/) and add it to the PR description.
162 changes: 17 additions & 145 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,156 +1,28 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useContext, useState } from 'react';
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { TodosContext } from './GlobalData/TodosDeveloper';
import { Filter } from './types/Filter';

export const App: React.FC = () => {
const { todos } = useContext(TodosContext);
const [filter, setFilter] = useState<Filter>(Filter.All);

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>

<a
href="#/completed"
className="filter__link"
data-cy="FilterLinkCompleted"
>
Completed
</a>
</nav>

{/* 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>
<Header />

{todos.length > 0 && (
<>
<TodoList filter={filter} />
<Footer filter={filter} setFilter={setFilter} />
</>
)}
</div>
</div>
);
Expand Down
48 changes: 48 additions & 0 deletions src/GlobalData/TodosDeveloper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Todo } from '../types/Todo';
import { InitialState } from '../types/InitialState';
import { InputRefs } from '../types/InputRefs';

const initialState: InitialState = {
todos: [],
setTodos: () => {},
};

export const TodosContext = React.createContext(initialState);

export const InputsFocusContext = React.createContext<InputRefs | null>(null);

type Props = {
children: React.ReactNode;
};

export const TodosDeveloper: React.FC<Props> = ({ children }) => {
const [todos, setTodos] = useState<Todo[]>(() => {
const savedTodos = localStorage.getItem('todos');

return savedTodos ? JSON.parse(savedTodos) : [];
});

const inputRef1 = useRef<HTMLInputElement | null>(null);
const inputRef2 = useRef<HTMLInputElement | null>(null);

useEffect(() => {
localStorage.setItem('todos', JSON.stringify(todos));
}, [todos]);

const value = useMemo(
() => ({
todos,
setTodos,
}),
[todos],
);

return (
<TodosContext.Provider value={value}>
<InputsFocusContext.Provider value={{ inputRef1, inputRef2 }}>
{children}
</InputsFocusContext.Provider>
</TodosContext.Provider>
);
};
96 changes: 96 additions & 0 deletions src/components/EditTodo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import React, { useContext, useEffect, useRef, useState } from 'react';
import { InputsFocusContext, TodosContext } from '../GlobalData/TodosDeveloper';
import { Todo } from '../types/Todo';
import { deleteTodo } from './Todo';

interface Props {
todo: Todo;
setEditing: React.Dispatch<React.SetStateAction<boolean>>;
}

export const EditTodo: React.FC<Props> = ({ todo, setEditing }) => {
const [value, setValue] = useState(todo.title);

const { setTodos } = useContext(TodosContext);
const prevValue = useRef<string | null>(null);

const inputRefs = useContext(InputsFocusContext);

const handleCancel = () => {
if (prevValue.current) {
setValue(prevValue.current);
} else {
setValue(todo.title);
}

setEditing(false);
};

useEffect(() => {
prevValue.current = value;
}, [value]);

useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
handleCancel();
}
};

document.addEventListener('keydown', handleKeyDown);

return () => {
document.removeEventListener('keydown', handleKeyDown);
};
});

useEffect(() => {
if (inputRefs?.inputRef2?.current) {
inputRefs?.inputRef2?.current.focus();
}
}, [inputRefs]);

const updateContentTodo = (content: Todo) => {
setTodos(currentTodos =>
currentTodos.map(item =>
item.id === content.id && item.title !== value
? { ...item, title: value.trim() }
: item,
),
);
};

const handleOnSubmit = (e?: React.FormEvent<HTMLFormElement>) => {
if (e) {
e.preventDefault();
}

if (value.trim().length === 0) {
deleteTodo(todo, setTodos);
setEditing(false);

return;
}

updateContentTodo(todo);
setEditing(false);
};

return (
<form onSubmit={handleOnSubmit}>
<input
ref={inputRefs && inputRefs.inputRef2}
data-cy="TodoTitleField"
type="text"
className="todo__title-field"
placeholder="Empty todo will be deleted"
value={value}
onChange={e => setValue(e.target.value)}
onBlur={() => {
handleOnSubmit();
setEditing(false);
}}
/>
</form>
);
};
56 changes: 56 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import React, { useContext } from 'react';
import { TodosContext } from '../GlobalData/TodosDeveloper';
import { Filter } from '../types/Filter';
import classNames from 'classnames';
import { deleteTodo } from './Todo';

interface Props {
filter: string;
setFilter: React.Dispatch<React.SetStateAction<Filter>>;
}

export const Footer: React.FC<Props> = ({ filter, setFilter }) => {
const { todos, setTodos } = useContext(TodosContext);

const handleDeleteTodo = () => {
todos.forEach(todo => {
if (todo.completed) {
deleteTodo(todo, setTodos);
}
});
};

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{`${todos.filter(todo => !todo.completed).length} items left`}
</span>

<nav className="filter" data-cy="Filter">
{(Object.values(Filter) as Filter[]).map(way => (
<a
key={way}
href="#/"
className={classNames('filter__link', { selected: filter === way })}
data-cy={`FilterLink${way}`}
onClick={() => {
setFilter(way);
}}
>
{way}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={todos.every(todo => !todo.completed)}
onClick={handleDeleteTodo}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading