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

Open
wants to merge 12 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 @@ -41,4 +41,4 @@ Implement the ability to edit a todo title on double click:

- Implement a solution following the [React task guideline](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).
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://<your_account>.github.io/react_todo-app-with-api/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://JOWISSA.github.io/react_todo-app-with-api/) and add it to the PR description.
39,672 changes: 23,614 additions & 16,058 deletions package-lock.json

Large diffs are not rendered by default.

132 changes: 132 additions & 0 deletions public/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
import React, { useMemo, useState } from 'react';

import { TodoList } from './Components/TodoList';
import { Footer } from './Components/Footer';

import { useLocalStorage } from './utils/useLocalStorage';

import { FilterType } from './types/FilterType';

export const App: React.FC = () => {
const [filterBy, setFilterBy] = useState<FilterType>(FilterType.ALL);
const [inputQuery, setInputQuery] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [todos, setTodos] = useLocalStorage('todos', []);

const addNewTodo = async () => {
if (!inputQuery.trim()) {
return;
}

try {
setIsLoading(true);

const newTodo = {
id: +new Date(),
title: inputQuery.trim(),
completed: false,
};

const updatedTodos = [...todos, newTodo];

setTodos(updatedTodos);

setInputQuery('');
} finally {
setIsLoading(false);
}
};

const handleFormSubmit = (e: React.FormEvent) => {
e.preventDefault();
addNewTodo();
};

const handleTodoDelete = (todoId: number) => {
const updatedTodos = todos.filter((todo) => todo.id !== todoId);

setTodos(updatedTodos);
};

const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputQuery(e.target.value);
};

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

const updatedTodos = todos.map(todo => ({
...todo,
completed: !areAllCompleted,
}));

setTodos(updatedTodos);
};

const visibleTodos = useMemo(() => {
switch (filterBy) {
case FilterType.ACTIVE:
return todos.filter((todo) => !todo.completed);
case FilterType.COMPLETED:
return todos.filter((todo) => todo.completed);
default:
return todos;
}
}, [filterBy, todos]);

const deleteAllCompletedTodos = () => {
const updatedTodos = todos.filter((todo) => !todo.completed);

setTodos(updatedTodos);
};

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

<div className="todoapp__content">
<header className="todoapp__header">
<button
type="button"
className="todoapp__toggle-all active"
onClick={handleToggleAll}
/>
<form onSubmit={handleFormSubmit}>
<input
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={inputQuery}
onChange={handleInputChange}
/>
</form>
</header>

{todos.length > 0 && (
<>
<TodoList
todos={visibleTodos}
onDelete={handleTodoDelete}
setTodos={setTodos}
/>

<Footer
filterBy={filterBy}
setFilterBy={setFilterBy}
todos={visibleTodos}
onDelete={deleteAllCompletedTodos}
/>
</>
)}
</div>

{isLoading && (
<div className="loader-overlay">
<div className="loader" />
</div>
)}

</div>
);
};
63 changes: 63 additions & 0 deletions public/src/Components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import classNames from 'classnames';
import React from 'react';
import { Todo } from '../types/Todo';
import { FilterType } from '../types/FilterType';

type Props = {
filterBy: FilterType,
setFilterBy: (value: FilterType) => void,
todos: Todo[],
onDelete: (id: number) => void,
};

const filterOptions = Object.values(FilterType);

export const Footer: React.FC<Props> = React.memo(({
filterBy,
setFilterBy,
todos,
onDelete,
}) => {
const itemsLeftLength = todos.filter((todo) => !todo.completed).length;

const deleteAllCompletedTodos = async () => {
const completedTodoIds = todos.filter(todo => todo.completed);
const idCompletesTodoId = completedTodoIds.map(todo => todo.id);

await Promise.all(idCompletesTodoId.map(id => onDelete(id)));
};

return (
<footer className="todoapp__footer">
<span className="todo-count">
{`${itemsLeftLength} items left`}
</span>

<nav className="filter">
{filterOptions.map((option) => {
return (
<a
key={option}
href={`#/${option}`}
className={classNames(
'filter__link',
{ selected: filterBy === option },
)}
onClick={() => setFilterBy(option)}
>
{option}
</a>
);
})}
</nav>

<button
type="button"
className="todoapp__clear-completed"
onClick={deleteAllCompletedTodos}
>
Clear completed
</button>
</footer>
);
});
123 changes: 123 additions & 0 deletions public/src/Components/TodoList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/* eslint-disable react/no-unused-prop-types */
import React, { useState, useEffect } from 'react';
import classNames from 'classnames';
import { Todo } from '../types/Todo';

type Props = {
onDelete: (id: number) => void;
setTodos: (value: Todo[]) => void;
todos: Todo[];
};

export const TodoList: React.FC<Props> = ({ onDelete, todos, setTodos }) => {
const [editingTodoId, setEditingTodoId] = useState<number | null>(null);
const [newTitle, setNewTitle] = useState('');

useEffect(() => {
const savedTodos = JSON.parse(localStorage.getItem('todos') || '[]');

setTodos(savedTodos);
}, []);

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

const handleStartEditing = (todoId: number, title: string) => {
setEditingTodoId(todoId);
setNewTitle(title);
};

const handleSaveEditing = (todoId: number, title: string) => {
if (!title.trim()) {
onDelete(todoId);
} else {
const updatedTodos = todos.map((todo) => {
if (todo.id === todoId) {
return { ...todo, title };
// eslint-disable-next-line no-else-return
} else {
return todo;
}
});

setTodos(updatedTodos);
setEditingTodoId(null);
setNewTitle('');
}
};

return (
<section className="todoapp__main">
{todos.map(({ id, completed, title }) => {
const isEditing = editingTodoId === id;

return (
<div
key={id}
className={classNames('todo', { completed, editing: isEditing })}
>
<label className="todo__status-label">
<input
type="checkbox"
className="todo__status"
checked={completed}
onChange={() => {
const updatedTodos = todos.map((todo) => {
if (todo.id === id) {
return { ...todo, completed: !completed };
// eslint-disable-next-line no-else-return
} else {
return todo;
}
});

setTodos(updatedTodos);
}}
/>
</label>

{isEditing ? (
<form
onSubmit={(e) => {
e.preventDefault();
handleSaveEditing(id, newTitle);
}}
>
<input
type="text"
className={classNames('todo__edit-input', {
'todo__edit-input--full-width': isEditing,
})}
value={newTitle}
onChange={(e) => setNewTitle(e.target.value)}
onBlur={() => handleSaveEditing(id, newTitle)}
/>
<button type="submit" className="todo__remove">
×
</button>
</form>
) : (
<span
className="todo__title"
onDoubleClick={() => handleStartEditing(id, title)}
>
{title}
</span>
)}

{!isEditing && (
<button
type="button"
className="todo__remove"
onClick={() => onDelete(id)}
>
×
</button>
)}
</div>
);
})}
</section>
);
};
32 changes: 32 additions & 0 deletions public/src/Components/errorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
import React, { useEffect } from 'react';
import cn from 'classnames';
import { Error } from '../types/Error';

interface Props {
error: Error;
onErrorChange: (error: Error) => void,
}

export const Notification: React.FC<Props> = ({ error, onErrorChange }) => {
useEffect(() => {
if (error) {
setTimeout(() => onErrorChange(Error.NONE), 3000);
}
}, [error]);

return (
<div className={cn('notification',
'is-danger is-light has-text-weight-normal', {
hidden: error === Error.NONE,
})}
>
<button
type="button"
className="delete"
onClick={() => onErrorChange(Error.NONE)}
/>
{error}
</div>
);
};
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
6 changes: 5 additions & 1 deletion src/styles/todo.scss → public/src/styles/todo.scss
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
font-size: 24px;
line-height: 1.4em;
border-bottom: 1px solid #ededed;


&.editing .todo__edit-input {
width: 100%;
height: 100%;
}
&:last-child {
border-bottom: 0;
}
Expand Down
File renamed without changes.
10 changes: 10 additions & 0 deletions public/src/types/Error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export enum Error {
NONE = '',
DOWNLOADING = 'An error occurred while executing the request',
NOT_VALIDE_TITLE = 'Title can\'t be empty',
ADD = 'Unable to add a todo',
DELETE = 'Unable to delete a todo',
DELETE_ALL = 'Unable to delete completed todos',
UPDATE = 'Unable to update a todo',
TOGGLE = 'Unable to toggle all todos',
}
5 changes: 5 additions & 0 deletions public/src/types/FilterType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export enum FilterType {
ALL = 'All',
ACTIVE = 'Active',
COMPLETED = 'Completed',
}
5 changes: 5 additions & 0 deletions public/src/types/Todo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface Todo {
id: number;
title: string;
completed: boolean;
}
Loading