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 #1021

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

Develop #1021

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://Nazarin565.github.io/react_todo-app/) and add it to the PR description.
151 changes: 9 additions & 142 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,156 +1,23 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { TodoList } from './components/TodoList';
import { Header } from './components/Header';
import { Footer } from './components/Footer';
import { useGlobalState } from './Store';

export const App: React.FC = () => {
const { todos } = useGlobalState();

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 && <TodoList />}

{/* 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 && <Footer />}
</div>
</div>
);
Expand Down
125 changes: 125 additions & 0 deletions src/Store.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import React, { useEffect, useReducer } from 'react';
import { SelectedFilter } from './types/SelectedFilter';
import { State } from './types/State';
import { Action } from './types/Action';
import { loadFromLocalStorage } from './utils/LocaleStorage';

const initialState: State = {
todos: [],
query: '',
filter: SelectedFilter.ALL,
editingTodoId: null,
currentTitle: '',
};

function reducer(state: State, action: Action): State {
switch (action.type) {
case 'toogleAllChecked':
const checked = state.todos.every(todo => todo.completed);

return {
...state,
todos: [...state.todos.map(todo => ({ ...todo, completed: !checked }))],
};

case 'addTodo':
return {
...state,
todos: [...state.todos, action.payload],
};

case 'setQuery':
return {
...state,
query: action.payload,
};

case 'deleteTodo':
return {
...state,
todos: [...state.todos.filter(todo => todo.id !== action.payload)],
};

case 'massDelete':
return {
...state,
todos: [
...state.todos.filter(todo => !action.payload.includes(todo.id)),
],
};

case 'changeCheckbox':
return {
...state,
todos: [
...state.todos.map(todo =>
todo.id === action.payload
? { ...todo, completed: !todo.completed }
: todo,
),
],
};

case 'updateTodo':
return {
...state,
todos: [
...state.todos.map(todo => {
return todo.id === action.payload.id
? { ...todo, title: action.payload.title }
: todo;
}),
],
};

case 'setCurrentTitle':
return {
...state,
currentTitle: action.payload,
};

case 'setEditingTodoId':
return {
...state,
editingTodoId: action.payload,
};

case 'setFilter':
return {
...state,
filter: action.payload,
};
}
}

export const StateContext = React.createContext<State>(initialState);
export const DispatchContext = React.createContext<React.Dispatch<Action>>(
() => {},
);

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

export const GlobalStateProvider: React.FC<Props> = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState, () => ({
todos: loadFromLocalStorage('todos'),
query: '',
filter: SelectedFilter.ALL,
editingTodoId: null,
currentTitle: '',
}));

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

return (
<DispatchContext.Provider value={dispatch}>
<StateContext.Provider value={state}>{children}</StateContext.Provider>
</DispatchContext.Provider>
);
};

export const useGlobalState = () => React.useContext(StateContext);
export const useGlobalDispatch = () => React.useContext(DispatchContext);
72 changes: 72 additions & 0 deletions src/components/EditForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { useEffect, useRef } from 'react';
import { useGlobalDispatch, useGlobalState } from '../Store';
import { Todo } from '../types/Todo';

type Props = {
newTodo: Todo;
};

export const EditForm: React.FC<Props> = ({
newTodo: { id, title, completed },
}) => {
const { currentTitle, editingTodoId } = useGlobalState();
const dispatch = useGlobalDispatch();

const editRef = useRef<HTMLInputElement>(null);

useEffect(() => {
if (editRef.current && editingTodoId) {
editRef.current.focus();
}
}, [editRef, editingTodoId]);

const handleUpdateTitle = (newTodo: Todo) => {
const trimmedTitle = currentTitle.trim();

if (!trimmedTitle) {
dispatch({ type: 'deleteTodo', payload: newTodo.id });
} else {
dispatch({
type: 'updateTodo',
payload: { ...newTodo, title: trimmedTitle },
});
}

dispatch({ type: 'setEditingTodoId', payload: null });
};

const handleUpdateTitleSubmit = (event: React.FormEvent, newTodo: Todo) => {
event.preventDefault();
handleUpdateTitle(newTodo);
};

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) =>
dispatch({ type: 'setCurrentTitle', payload: event.target.value });

const handleKeyUp = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Escape') {
dispatch({ type: 'setCurrentTitle', payload: title });
dispatch({ type: 'setEditingTodoId', payload: null });
}
};

return (
<form
onSubmit={event =>
handleUpdateTitleSubmit(event, { id, title, completed })
}
>
<input
ref={editRef}
data-cy="TodoTitleField"
type="text"
className="todo__title-field"
placeholder="Empty todo will be deleted"
value={currentTitle}
onBlur={() => handleUpdateTitle({ id, title, completed })}
onChange={handleChange}
onKeyUp={handleKeyUp}
/>
</form>
);
};
28 changes: 28 additions & 0 deletions src/components/FilterOption.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import cn from 'classnames';
import { FilteredOptions } from '../types/FilteredOptions';
import { useGlobalDispatch, useGlobalState } from '../Store';

type Props = {
option: FilteredOptions;
};

export const FilterOptions: React.FC<Props> = ({
option: { type, href, data },
}) => {
const { filter } = useGlobalState();
const dispatch = useGlobalDispatch();

return (
<a
href={href}
className={cn('filter__link', {
selected: type === filter,
})}
data-cy={data}
key={type}
onClick={() => dispatch({ type: 'setFilter', payload: type })}
>
{type}
</a>
);
};
Loading
Loading