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

Todo counter sample project #2

Open
wants to merge 6 commits into
base: main
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
58 changes: 54 additions & 4 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import React from 'react';
import React, {useReducer} from 'react';
import styled from 'styled-components';
import {TodosFooter} from './components/TodosFooter';
import {TodosHeader} from './components/TodosHeader';
import {OnSubmit, TodoInput} from './components/TodoInput';
import {TodoList} from './components/TodoList';
import {Todo} from './types';
import {TodoStatusBar} from './components/TodoStatusBar';
import {OnTodoChange} from './components/TodoItem';

export const AppContainer = styled.div`
display: flex;
Expand All @@ -22,11 +23,29 @@ export interface AppState {

export const App: React.FC = () => {
const [todos, setTodos] = React.useState<Todo[]>([]);
const [congratsVisibility, setCongratsVisibility] = React.useState('none');
type CounterAction = {type: 'ADD'} | {type: 'REMOVE'} | {type: 'INITIAL'};
const [totalDone, dispatchDoneCounter] = useReducer(
(state: number, action: CounterAction): number => {
switch (action.type) {
case 'ADD':
return state + 1;
case 'REMOVE':
return state - 1;
case 'INITIAL':
return todos.filter(todo => todo.done).length;
default:
return 0;
}
},
0
);

React.useEffect(() => {
(async () => {
const response = await fetch('http://localhost:3001/todos');
setTodos(await response.json());
dispatchDoneCounter({type: 'INITIAL'});
})();
}, []);

Expand Down Expand Up @@ -54,15 +73,46 @@ export const App: React.FC = () => {
return '';
};

const updateTodo: OnTodoChange = async (todo: Todo) => {
const response = await fetch(`http://localhost:3001/todos/${todo.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(todo),
});
if (!response.ok) {
window.alert(
`Unexpected error ${response.status}: ${response.statusText}`
);
return todo;
}
let totalDoneCount = todos.filter(todo => todo.done).length;
if (todo.done && totalDoneCount === todos.length) {
setCongratsVisibility('flex');
}
dispatchDoneCounter(todo.done ? {type: 'ADD'} : {type: 'REMOVE'});
return todo;
};

return (
<AppContainer className='App'>
<TodosHeader>
<TodoStatusBar total={todos.length} />
<TodoStatusBar
total={todos.length}
totalDone={totalDone}
// TODO: create a new component for the banner instead of adding in both header and footer
congratsBannerVisibility={congratsVisibility}
/>
</TodosHeader>
<TodoInput onSubmit={createTodo} />
<TodoList todos={todos} />
<TodoList todos={todos} todoChange={updateTodo} />
<TodosFooter>
<TodoStatusBar total={todos.length} />
<TodoStatusBar
total={todos.length}
totalDone={totalDone}
congratsBannerVisibility={'none'}
/>
</TodosFooter>
</AppContainer>
);
Expand Down
26 changes: 20 additions & 6 deletions src/components/TodoItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,31 @@ const TodoCheckbox = styled.input`
margin-right: 8px;
`;

export type OnTodoChange = (todo: Todo) => Promise<Todo>;

export interface TodoItemProps {
todo: Todo;
todoChange: OnTodoChange;
className?: string;
}

const _TodoItem: React.FC<TodoItemProps> = ({todo, className}) => (
<li data-cy='TodoItem' className={className}>
<TodoCheckbox type='checkbox' checked={todo.done} />
<TodoText done={todo.done}>{todo.text}</TodoText>
</li>
);
const _TodoItem: React.FC<TodoItemProps> = ({todo, className, todoChange}) => {
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
todo.done = event.target.checked.valueOf();
todoChange(todo);
};

return (
<li data-cy='TodoItem' className={className}>
<TodoCheckbox
type='checkbox'
checked={todo.done}
onChange={handleChange}
/>
<TodoText done={todo.done}>{todo.text}</TodoText>
</li>
);
};

export const TodoItem = styled(_TodoItem)`
display: flex;
Expand Down
22 changes: 22 additions & 0 deletions src/components/TodoList.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import React from 'react';
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {TodoList} from './TodoList';
import {Todo} from '../types';

test('populates TodoList and assert they are listed by most recent', async () => {
const user = userEvent.setup();

const todos: Todo[] = [
{ id: '1', text: 'First todo', done: false, createdTimestamp: 1000 },
{ id: '2', text: 'Second todo', done: false, createdTimestamp: 2000 }
];

const onChange = jest.fn(async () => todos[0]);

render(<TodoList todos={todos} todoChange={onChange} />);
const items = screen.getAllByRole('listitem');

expect(items[0]).toHaveTextContent("Second todo");
expect(items[1]).toHaveTextContent("First todo");
});
13 changes: 8 additions & 5 deletions src/components/TodoList.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import React from 'react';
import styled from 'styled-components';
import {Todo} from '../types';
import {TodoItem} from './TodoItem';
import {TodoItem, OnTodoChange} from './TodoItem';

export interface TodoListProps {
todos: Array<Todo>;
className?: string;
todoChange: OnTodoChange;
}

const _TodoList: React.FC<TodoListProps> = ({todos, className}) => {
const _TodoList: React.FC<TodoListProps> = ({todos, className, todoChange}) => {
return (
<ul data-cy='TodoList' className={className}>
{todos.map((todo, index) => (
<TodoItem key={index} todo={todo} />
))}
{todos
.sort((t1, t2) => t2.createdTimestamp - t1.createdTimestamp)
.map((todo, index) => (
<TodoItem key={index} todo={todo} todoChange={todoChange} />
))}
</ul>
);
};
Expand Down
21 changes: 19 additions & 2 deletions src/components/TodoStatusBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,34 @@ const InfoBar = styled.div`
justify-content: space-between;
`;

const CongratulationsBanner = styled.div<{isCongratsBannerVisible: string}>`
display: ${props => props.isCongratsBannerVisible || 'none'};
justify-content: center;
`;

export interface TodoStatusBarProps {
className?: string;
total: number;
totalDone: number;
congratsBannerVisibility: string;
}

const _TodoStatusBar: React.FC<TodoStatusBarProps> = ({className, total}) => (
const _TodoStatusBar: React.FC<TodoStatusBarProps> = ({
className,
total,
totalDone,
congratsBannerVisibility,
}) => (
<div data-cy='TodoStatusBar' className={className}>
<InfoBar>
<span>Total: {total}</span>
<span>Done: 0</span>
<span>Done: {totalDone}</span>
</InfoBar>
<CongratulationsBanner isCongratsBannerVisible={congratsBannerVisibility}>
<span>
Congratulations, you're all set! You've done everything on your list.
</span>
</CongratulationsBanner>
</div>
);

Expand Down