Add task list demo application

This commit is contained in:
Steve Kinney
2024-09-17 15:38:26 -06:00
parent b13029bffc
commit 4971bda81b
40 changed files with 2545 additions and 773 deletions

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Task List</title>
<script src="./src/index.tsx" type="module"></script>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<div id="root"></div>
</body>
</html>

View File

@@ -5,6 +5,9 @@
"main": "index.js",
"type": "module",
"scripts": {
"start": "concurrently \"npm run start:client\" \"npm run start:server\" --names \"client,server\" --kill-others -c blue,green",
"start:client": "vite dev",
"start:server": "node server/index.js",
"test": "vitest"
},
"repository": {
@@ -18,8 +21,20 @@
},
"homepage": "https://github.com/stevekinney/testing-javascript#readme",
"devDependencies": {
"@types/body-parser": "^1.19.5",
"@types/express": "^4.17.21",
"@types/uuid": "^10.0.0",
"@vitejs/plugin-react": "^4.3.1",
"@vitest/ui": "^2.1.1",
"vite": "^5.4.5",
"chalk": "^5.3.0",
"concurrently": "^9.0.1",
"cors": "^2.8.5",
"uuid": "^10.0.0",
"vite": "^5.4.6",
"vitest": "^2.1.1"
},
"dependencies": {
"body-parser": "^1.20.3",
"express": "^4.21.0"
}
}

View File

@@ -0,0 +1,65 @@
import express from 'express';
import bodyParser from 'body-parser';
import chalk from 'chalk';
import {
getTasks,
getTask,
createTask,
updateTask,
deleteTask,
} from './tasks.js';
const app = express();
app.use(bodyParser.json());
app.get('/api/tasks', (req, res) => {
const tasks = getTasks();
res.json(tasks);
});
app.post('/api/tasks', (req, res) => {
const { title } = req.body;
if (!title) {
return res.status(400).json({ message: 'A title is required' });
}
const task = createTask(title);
res.status(201).json(task);
});
app.get('/api/tasks/:id', (req, res) => {
const task = getTask(req.params.id);
if (!task) {
return res.status(404).json({ message: 'Task not found' });
}
res.json(task);
});
app.patch('/api/tasks/:id', (req, res) => {
const { title, completed } = req.body;
const task = updateTask(req.params.id, { title, completed });
if (!task) {
return res.status(404).json({ message: 'Task not found' });
}
res.sendStatus(204);
});
app.delete('/api/tasks/:id', (req, res) => {
const task = deleteTask(req.params.id);
if (!task) {
return res.status(404).json({ message: 'Task not found' });
}
res.status(204).send(); // No content to send back
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(chalk.magenta(`Server is running on port ${chalk.green(PORT)}`));
});

View File

@@ -0,0 +1,65 @@
import { v4 as id } from 'uuid';
/** @typedef {import('../types').Task} Task */
/** @type {Task[]} tasks - An array to store tasks. */
let tasks = [];
/**
* Get all tasks.
* @returns {Task[]} An array of tasks.
*/
export const getTasks = () => tasks;
/**
* Create a new task.
* @param {string} title - The title of the task.
* @returns {Task} The newly created task.
*/
export const createTask = (title) => {
/** @type {Task} */
const task = {
id: id(),
title,
completed: false,
createdAt: new Date(),
lastModified: new Date(),
};
tasks.push(task);
return task;
};
/**
* Find a task by ID.
* @param {string} id - The ID of the task to find.
* @returns {Task | undefined} The found task or undefined if not found.
*/
export const getTask = (id) => tasks.find((task) => task.id === id);
/**
* Update a task by ID.
* @param {string} id - The ID of the task to update.
* @param {Partial<Pick<Task, 'title' | 'description'>>} updates - The updates to apply to the task.
* @returns {Task | undefined} The updated task or undefined if not found.
*/
export const updateTask = (id, updates) => {
const task = getTask(id);
if (!task) return undefined;
Object.assign(task, updates, { lastModified: new Date() });
return task;
};
/**
* Delete a task by ID.
* @param {string} id - The ID of the task to delete.
* @returns {boolean} `true` if the task was deleted, `false` if not found.
*/
export const deleteTask = (id) => {
const index = tasks.findIndex((task) => task.id === id);
if (index === -1) return false;
tasks.splice(index, 1);
return true;
};

View File

@@ -0,0 +1,14 @@
import { CreateTask } from './create-task';
import { TaskProvider } from './task-context';
import { Tasks } from './tasks';
export const Application = () => {
return (
<TaskProvider>
<main className="container max-w-xl my-10 space-y-8">
<CreateTask onSubmit={(title) => console.log(title)} />
<Tasks />
</main>
</TaskProvider>
);
};

View File

@@ -0,0 +1,43 @@
import { useState } from 'react';
import { useTaskContext } from './task-context';
type CreateTaskProps = {
onSubmit: (title: string) => void;
};
export const CreateTask = ({ onSubmit }: CreateTaskProps) => {
const { addTask } = useTaskContext();
const [title, setTitle] = useState('');
return (
<form
method="POST"
action="/api/tasks"
onSubmit={(event) => {
event.preventDefault();
addTask(title);
setTitle('');
}}
>
<div>
<label htmlFor="new-task-title" className="sr-only">
Title
</label>
<div className="flex">
<input
type="text"
name="title"
id="new-task-title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="What do you need to get done?"
required
/>
<button type="submit" disabled={!title}>
Create Task
</button>
</div>
</div>
</form>
);
};

View File

@@ -0,0 +1,15 @@
export const DateTime = ({ date, title }: { date: Date; title: string }) => {
return (
<div className="flex gap-2 text-xs sm:flex-row">
<h3 className="font-semibold sm:after:content-[':'] after:text-gray-900 text-primary-800">
{title}
</h3>
<p>
{date.toLocaleString(undefined, {
dateStyle: 'short',
timeStyle: 'short',
})}
</p>
</div>
);
};

View File

@@ -0,0 +1,9 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { Application } from './application';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<Application />
</StrictMode>,
);

View File

@@ -0,0 +1,131 @@
import {
createContext,
useReducer,
useEffect,
type ReactNode,
useContext,
} from 'react';
import { TasksActions, taskReducer, initialState } from './task-reducer';
import type { Task } from '../types';
interface TaskContextProps {
tasks: Task[];
loading: boolean;
error: string | null;
addTask: (title: string) => void;
updateTask: (id: string, updatedTask: Partial<Task>) => void;
deleteTask: (id: string) => void;
}
const TaskContext = createContext<TaskContextProps | undefined>(undefined);
interface TaskProviderProps {
children: ReactNode;
}
const TaskProvider = ({ children }: TaskProviderProps) => {
const [state, dispatch] = useReducer(taskReducer, initialState);
// Fetch all tasks
const fetchTasks = async () => {
dispatch({ type: TasksActions.SET_LOADING });
try {
const response = await fetch('/api/tasks');
const data = await response.json();
dispatch({ type: TasksActions.FETCH_TASKS, payload: data });
} catch (error) {
dispatch({
type: TasksActions.SET_ERROR,
payload: 'Failed to fetch tasks',
});
}
};
// Add a new task
const addTask = async (title: string) => {
dispatch({ type: TasksActions.SET_LOADING });
try {
const response = await fetch('/api/tasks', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
});
const data = await response.json();
dispatch({ type: TasksActions.ADD_TASK, payload: data });
} catch (error) {
dispatch({ type: TasksActions.SET_ERROR, payload: 'Failed to add task' });
}
};
// Update a task
const updateTask = async (id: string, updatedTask: Partial<Task>) => {
dispatch({ type: TasksActions.SET_LOADING });
try {
const response = await fetch(`/api/tasks/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updatedTask),
});
if (!response.ok) {
throw new Error('Failed to update task');
}
dispatch({
type: TasksActions.UPDATE_TASK,
payload: { id, ...updatedTask },
});
} catch (error) {
dispatch({
type: TasksActions.SET_ERROR,
payload: 'Failed to update task',
});
}
};
// Delete a task
const deleteTask = async (id: string) => {
dispatch({ type: TasksActions.SET_LOADING });
try {
await fetch(`/api/tasks/${id}`, {
method: 'DELETE',
});
dispatch({ type: TasksActions.DELETE_TASK, payload: id });
} catch (error) {
dispatch({
type: TasksActions.SET_ERROR,
payload: 'Failed to delete task',
});
}
};
useEffect(() => {
fetchTasks();
}, []);
return (
<TaskContext.Provider
value={{
tasks: state.tasks,
loading: state.loading,
error: state.error,
addTask,
updateTask,
deleteTask,
}}
>
{children}
</TaskContext.Provider>
);
};
const useTaskContext = () => {
const context = useContext(TaskContext);
if (!context) {
throw new Error('useTaskContext must be used within a TaskProvider');
}
return context;
};
export { TaskContext, TaskProvider, useTaskContext };

View File

@@ -0,0 +1,60 @@
import type { Task } from '../types';
export enum TasksActions {
FETCH_TASKS = 'fetch-tasks',
ADD_TASK = 'add-task',
UPDATE_TASK = 'update-task',
DELETE_TASK = 'delete-task',
SET_LOADING = 'set-loading',
SET_ERROR = 'set-error',
}
export interface TaskState {
tasks: Task[];
loading: boolean;
error: string | null;
}
export interface Action {
type: TasksActions;
payload?: any;
}
export const initialState: TaskState = {
tasks: [],
loading: false,
error: null,
};
export const taskReducer = (state: TaskState, action: Action): TaskState => {
switch (action.type) {
case TasksActions.FETCH_TASKS:
return { ...state, tasks: action.payload, loading: false };
case TasksActions.ADD_TASK:
return {
...state,
tasks: [...state.tasks, action.payload],
loading: false,
};
case TasksActions.UPDATE_TASK:
return {
...state,
tasks: state.tasks.map((task) =>
task.id === action.payload.id ? { ...task, ...action.payload } : task,
),
loading: false,
};
case TasksActions.DELETE_TASK:
return {
...state,
tasks: state.tasks.filter((task) => task.id !== action.payload),
loading: false,
};
case TasksActions.SET_LOADING:
return { ...state, loading: true };
case TasksActions.SET_ERROR:
return { ...state, error: action.payload, loading: false };
default:
return state;
}
};

View File

@@ -0,0 +1,40 @@
import { DateTime } from './date-time';
import { useTaskContext } from './task-context';
type TaskProps = {
task: import('../types').Task;
};
export const Task = ({ task }: TaskProps) => {
const { updateTask, deleteTask } = useTaskContext();
return (
<li className="block p-4 space-y-2 border-t-2 border-x-2 last:border-b-2">
<header className="flex flex-row items-center gap-4">
<label htmlFor={`toggle-${task.id}`} className="sr-only">
Mark Task as {task.completed ? 'Incomplete' : 'Complete'}
</label>
<input
id={`toggle-${task.id}`}
type="checkbox"
className="block w-6 h-6"
checked={task.completed}
onChange={() => updateTask(task.id, { completed: !task.completed })}
/>
<h2 className="w-full font-semibold">{task.title}</h2>
<button
className="py-1 px-1.5 text-xs button-destructive button-ghost"
onClick={() => {
deleteTask(task.id);
}}
>
Delete
</button>
</header>
<div className="flex flex-col md:gap-2 md:flex-row">
<DateTime date={task.createdAt} title="Created" />
<DateTime date={task.lastModified} title="Modified" />
</div>
</li>
);
};

View File

@@ -0,0 +1,16 @@
import { Task } from './task';
import { useTaskContext } from './task-context';
export const Tasks = () => {
const { tasks } = useTaskContext();
return (
<section>
<ul>
{tasks.map((task) => (
<Task key={task.id} task={task} />
))}
</ul>
</section>
);
};

View File

@@ -0,0 +1,53 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
label {
@apply block text-sm font-medium leading-6;
&[for]:has(~ input[required]) {
@apply after:content-['*'] after:text-red-600;
}
}
input[type='text'],
input[type='email'],
input[type='password'] {
@apply text-sm sm:text-base block w-full rounded-md border-0 py-1.5 px-2.5 text-slate-900 shadow-sm ring-1 ring-inset ring-primary-700/20 placeholder:text-slate-400 sm:text-sm sm:leading-6 placeholder:text-primary-600;
@apply focus:ring-2 focus:ring-primary-600 focus:outline-none;
&:has(+ button[type='submit']) {
@apply block w-full rounded-r-none;
}
}
input[type='checkbox'] {
@apply h-4 w-4 rounded border-primary-500 accent-primary-600;
}
button {
@apply button;
input + & {
@apply rounded-l-none -ml-px;
}
&[type='submit'] {
@apply button-primary;
}
}
}
@layer components {
.button {
@apply relative inline-flex items-center justify-center gap-x-1.5 rounded-md px-3 py-2 text-sm font-semibold text-slate-900 ring-1 ring-inset ring-primary-300 hover:bg-slate-50 whitespace-pre disabled:cursor-not-allowed text-sm sm:text-base;
}
.button-primary {
@apply bg-primary-600 text-white cursor-pointer ring-primary-700 transition duration-100 ease-in-out hover:bg-primary-700 active:bg-primary-800 disabled:bg-primary-600/50 disabled:hover:bg-primary-600/50 disabled:active:bg-primary-600/50 disabled:cursor-not-allowed disabled:ring-primary-700/20;
}
.button-destructive {
@apply bg-red-600 text-white cursor-pointer ring-red-700 transition duration-100 ease-in-out hover:bg-red-700 active:bg-red-800 disabled:bg-red-600/50 disabled:hover:bg-red-600/50 disabled:active:bg-red-600/50 disabled:cursor-not-allowed disabled:ring-red-700/20;
&.button-ghost {
@apply bg-transparent text-red-600 ring-red-600 hover:bg-red-600/10;
}
}
}

View File

@@ -0,0 +1,7 @@
export interface Task {
id: string;
title: string;
completed: boolean;
createdAt: Date;
lastModified: Date;
}

View File

@@ -0,0 +1,17 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { css } from 'css-configuration';
export default defineConfig({
plugins: [react()],
css,
server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
secure: false,
},
},
},
});