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

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
471 changes: 454 additions & 17 deletions src/App.tsx

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 2148;

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

// Add more methods here

Choose a reason for hiding this comment

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

// Add more methods here

33 changes: 33 additions & 0 deletions src/components/ErrorNotification/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React, { Dispatch, SetStateAction } from 'react';
import cN from 'classnames';
import { Error } from '../../types/Error';

type Props = {
errorMessage: Error | null;
setErrorMessage: Dispatch<SetStateAction<Error | null>>;
};

export const ErrorNotification: React.FC<Props> = ({
errorMessage,
setErrorMessage,
}) => {
return (
<div
data-cy="ErrorNotification"
className={cN('notification is-danger is-light has-text-weight-normal', {
hidden: !errorMessage,
})}
>
<button
onClick={() => setErrorMessage(null)}
data-cy="HideErrorButton"
type="button"
className="delete"
/>
{/* show only one message at a time +++*/}
{errorMessage}
</div>
);
};
1 change: 1 addition & 0 deletions src/components/ErrorNotification/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './ErrorNotification';
125 changes: 125 additions & 0 deletions src/components/TodoItem/TodoItem.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React, {
Dispatch,
SetStateAction,
RefObject,
useState,
useRef,
useEffect,
} from 'react';
import { Todo } from '../../types/Todo';
import cN from 'classnames';

type Props = {
todo: Todo;
isTemp?: boolean;
handleTodoStatusChange?: (id: number) => void;
onDelete?: (id: number) => Promise<void>;
isDeletingTodo?: boolean;
todoToDeleteIds?: number[] | null;
setTodoToDeleteIds?: Dispatch<SetStateAction<number[] | null>>;
addTodoField?: RefObject<HTMLInputElement>;
isUpdatingStatus?: boolean;
statusChangeId?: number | null;
setEditingTodoId?: Dispatch<SetStateAction<number | null>>;
editingTodoId?: number | null;
handleTitleChange?: (newTitle: string) => void;
isUpdatingTitle?: boolean | null;
};

export const TodoItem: React.FC<Props> = ({
todo,
isTemp = false,
handleTodoStatusChange,
onDelete,
isDeletingTodo,
todoToDeleteIds,
setTodoToDeleteIds,
addTodoField,
isUpdatingStatus,
statusChangeId,
setEditingTodoId,
editingTodoId,
handleTitleChange,
isUpdatingTitle,
}) => {
const { title, id, completed } = todo;
const [inputValue, setInputValue] = useState<string>(title);
const editTodoField = useRef<HTMLInputElement>(null);

useEffect(() => {
if (editTodoField.current !== null) {
editTodoField.current.focus();
}
}, [editingTodoId]);

return (
<div key={id} data-cy="Todo" className={cN('todo', { completed })}>
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
checked={completed}
onChange={() => (isTemp ? null : handleTodoStatusChange?.(id))}
/>
</label>
{id === editingTodoId ? (
<form onSubmit={() => handleTitleChange?.(inputValue)}>
<input
onBlur={() => {
handleTitleChange?.(inputValue);
}}
ref={editTodoField}
data-cy="TodoTitleField"
type="text"
className="todo__title-field"
placeholder="Empty todo will be deleted"
value={inputValue}
onChange={event => setInputValue(event.target.value)}
/>
</form>
) : (
<>
<span
onDoubleClick={() => setEditingTodoId?.(id)}
data-cy="TodoTitle"
className="todo__title"
>
{title}
</span>
<button
onClick={() => {
setTodoToDeleteIds?.([id]);
onDelete?.(id).then(() => {
if (addTodoField?.current !== null) {
addTodoField?.current.focus();
}
});
}}
type="button"
className="todo__remove"
data-cy="TodoDelete"
>
×
</button>
</>
)}
{/* isDeletingTodo спробувати прибрати*/}
<div
data-cy="TodoLoader"
className={cN('modal overlay', {
'is-active':
isTemp ||
(isDeletingTodo && todoToDeleteIds?.includes(id)) ||
(isUpdatingStatus && id === statusChangeId) ||
(isUpdatingTitle && id === editingTodoId),
})}
>
<div className="modal-background has-background-white-ter" />
<div className="loader" />
</div>
</div>
);
};
1 change: 1 addition & 0 deletions src/components/TodoItem/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './TodoItem';
7 changes: 7 additions & 0 deletions src/types/Error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export enum Error {
LoadError = 'Unable to load todos',
EmptyTitleError = 'Title should not be empty',
AddError = 'Unable to add a todo',
DeleteError = 'Unable to delete a todo',
UpdateError = 'Unable to update a todo',
}
5 changes: 5 additions & 0 deletions src/types/Filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export enum Filter {
All = 'All',
Completed = 'Completed',
Active = 'Active',
}
6 changes: 6 additions & 0 deletions src/types/Todo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface Todo {
id: number;
userId: number;
title: string;
completed: boolean;
}
46 changes: 46 additions & 0 deletions src/utils/fetchClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
const BASE_URL = 'https://mate.academy/students-api';

// returns a promise resolved after a given delay +
function wait(delay: number) {
return new Promise(resolve => {
setTimeout(resolve, delay);
});
}

// To have autocompletion and avoid mistypes +
type RequestMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE';

function request<T>(
url: string,
method: RequestMethod = 'GET',
data: any = null, // we can send any data to the server +
): Promise<T> {
const options: RequestInit = { method };

if (data) {
// We add body and Content-Type only for the requests with data +
options.body = JSON.stringify(data);
options.headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
}

// DON'T change the delay it is required for tests +
return wait(100)
.then(() => fetch(BASE_URL + url, options))
.then(response => {
if (!response.ok) {
throw new Error();
}

return response.json();
});
}

export const client = {
get: <T>(url: string) => request<T>(url),
post: <T>(url: string, data: any) => request<T>(url, 'POST', data),
patch: <T>(url: string, data: any) => request<T>(url, 'PATCH', data),
delete: (url: string) => request(url, 'DELETE'),
};
Loading