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

add-todo-form #2912

Open
wants to merge 2 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
71 changes: 21 additions & 50 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,61 +1,32 @@
import './App.scss';

// import usersFromServer from './api/users';
// import todosFromServer from './api/todos';
import { useState } from 'react';
import usersFromServer from './api/users';
import todosFromServer from './api/todos';
import { getUserById } from './utils';
import { TodoList } from './components/TodoList/TodoList';
import { NewTodoForm } from './components/NewTodoForm';

const todoRoster = todosFromServer.map(todo => ({
...todo,
user: getUserById(usersFromServer, todo.userId),
}));

export const App = () => {
const [todos, setTodos] = useState(todoRoster);

return (
<div className="App">
<h1>Add todo form</h1>

<form action="/api/todos" method="POST">
<div className="field">
<input type="text" data-cy="titleInput" />
<span className="error">Please enter a title</span>
</div>

<div className="field">
<select data-cy="userSelect">
<option value="0" disabled>
Choose a user
</option>
</select>

<span className="error">Please choose a user</span>
</div>

<button type="submit" data-cy="submitButton">
Add
</button>
</form>

<section className="TodoList">
<article data-id="1" className="TodoInfo TodoInfo--completed">
<h2 className="TodoInfo__title">delectus aut autem</h2>

<a className="UserInfo" href="mailto:[email protected]">
Leanne Graham
</a>
</article>

<article data-id="15" className="TodoInfo TodoInfo--completed">
<h2 className="TodoInfo__title">delectus aut autem</h2>

<a className="UserInfo" href="mailto:[email protected]">
Leanne Graham
</a>
</article>

<article data-id="2" className="TodoInfo">
<h2 className="TodoInfo__title">
quis ut nam facilis et officia qui
</h2>
<NewTodoForm
todos={todos}
users={usersFromServer}
handleAdd={newTodo => {
setTodos(prevTodos => [...prevTodos, newTodo]);
}}
/>

<a className="UserInfo" href="mailto:[email protected]">
Patricia Lebsack
</a>
</article>
</section>
<TodoList todos={todos} />
</div>
);
};
101 changes: 101 additions & 0 deletions src/components/NewTodoForm/NewTodoForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import React, { useState } from 'react';
import { Todo, User } from '../../types';
import { createNewId, getUserById, removeInvalidCharacters } from '../../utils';

type Props = {
todos: Todo[];
users: User[];
handleAdd: (todo: Todo) => void;
};

export const NewTodoForm: React.FC<Props> = ({ todos, users, handleAdd }) => {
const [title, setTitle] = useState('');
const [hasTitleInputError, setHasTitleInputError] = useState(false);
const [userId, setUserId] = useState(0);
const [hasUserSelectError, setHasUserSelectError] = useState(false);

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

if (!title) {
setHasTitleInputError(true);
}

if (!userId) {
setHasUserSelectError(true);
}

if (title && userId) {
setTitle('');
setUserId(0);
handleAdd({
id: createNewId(todos),
title: removeInvalidCharacters(title),
completed: false,
userId,
user: getUserById(users, userId),
});
}
}

function handleTitleInputChange(event: React.ChangeEvent<HTMLInputElement>) {
setTitle(event.target.value);
setHasTitleInputError(false);
}

function handleUserSelect(event: React.ChangeEvent<HTMLSelectElement>) {
setUserId(Number(event.target.value));
setHasUserSelectError(false);
}

return (
<form action="/api/todos" method="POST" onSubmit={handleSubmit}>
<div className="field">
<label>
{`Title: `}
<input
type="text"
name="title"
placeholder="Enter a title"
value={title}
onChange={handleTitleInputChange}
data-cy="titleInput"
/>
</label>
{hasTitleInputError && (
<span className="error">Please enter a title</span>
)}
</div>

<div className="field">
<label>
{`User: `}
<select
name="user"
required
value={userId}
onChange={handleUserSelect}
data-cy="userSelect"
>
<option value="0" disabled>
Choose a user
</option>
{users.map(user => (
<option value={user.id} key={user.id}>
{user.name}
</option>
))}
</select>
</label>

{hasUserSelectError && (
<span className="error">Please choose a user</span>
)}
</div>

<button type="submit" data-cy="submitButton">
Add
</button>
</form>
);
};
1 change: 1 addition & 0 deletions src/components/NewTodoForm/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './NewTodoForm';
21 changes: 20 additions & 1 deletion src/components/TodoInfo/TodoInfo.tsx
Original file line number Diff line number Diff line change
@@ -1 +1,20 @@
export const TodoInfo = () => {};
import React from 'react';
import classNames from 'classnames';
import { Todo } from '../../types';
import { UserInfo } from '../UserInfo';

type Props = {
todo: Todo;
};

export const TodoInfo: React.FC<Props> = ({ todo }) => (
<article
data-id={todo.id}
className={classNames('TodoInfo', {
'TodoInfo--completed': todo.completed,
})}
>
<h2 className="TodoInfo__title">{todo.title}</h2>
{todo.user && <UserInfo user={todo.user} />}
</article>
);
16 changes: 15 additions & 1 deletion src/components/TodoList/TodoList.tsx
Original file line number Diff line number Diff line change
@@ -1 +1,15 @@
export const TodoList = () => {};
import React from 'react';
import { Todo } from '../../types';
import { TodoInfo } from '../TodoInfo';

type Props = {
todos: Todo[];
};

export const TodoList: React.FC<Props> = ({ todos }) => (
<section className="TodoList">
{todos.map(todo => (
<TodoInfo todo={todo} key={todo.id} />
))}
</section>
);
13 changes: 12 additions & 1 deletion src/components/UserInfo/UserInfo.tsx
Original file line number Diff line number Diff line change
@@ -1 +1,12 @@
export const UserInfo = () => {};
import React from 'react';
import { User } from '../../types';

type Props = {
user: User;
};

export const UserInfo: React.FC<Props> = ({ user }) => (
<a className="UserInfo" href={`mailto:${user.email}`}>
{user.name}
</a>
);
9 changes: 9 additions & 0 deletions src/types/Todo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { User } from './User';

export interface Todo {
id: number;
title: string;
completed: boolean;
userId: number;
user: User | null;
}
6 changes: 6 additions & 0 deletions src/types/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface User {
id: number;
name: string;
username: string;
email: string;
}
2 changes: 2 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './Todo';
export * from './User';
9 changes: 9 additions & 0 deletions src/utils/createNewId.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Todo } from '../types';

export function createNewId(todos: Todo[]) {
const maxId = todos.reduce((acc: number, todo: Todo) => {
return Math.max(todo.id, acc);
}, 0);

return maxId + 1;
}
5 changes: 5 additions & 0 deletions src/utils/getUserById.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { User } from '../types';

export function getUserById(users: User[], userId: number) {
return users.find(user => user.id === userId) || null;
}
3 changes: 3 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './createNewId';
export * from './getUserById';
export * from './removeInvalidCharacters';
18 changes: 18 additions & 0 deletions src/utils/removeInvalidCharacters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const enAbc = 'abcdefghijklmnopqrstuvwxyz';
const uaAbc = 'абвгґдеєжзиіїйклмнопрстуфхцчшщьюя';
const digits = '123456789';
const symbols = " '`";
const allowedCharacters = enAbc + uaAbc + digits + symbols;

export function removeInvalidCharacters(str: string): string {
const trimmedStr = str.trim();
let validStr = '';

for (let i = 0; i < trimmedStr.length; i++) {
if (allowedCharacters.includes(trimmedStr[i].toLowerCase())) {
validStr += trimmedStr[i];
}
}

return validStr;
}
Loading