Skip to content
Closed
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
59 changes: 59 additions & 0 deletions implementation-plans/aiadt-11-due-date.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Implementation Plan – AIADT-11 Add Due Date Field to Todos

## Objective

Add optional `dueDate` support to every todo so users can set, view, and update task deadlines. Persist the value in `sessionStorage`, surface it throughout the UI, and maintain backward-compatibility for previously stored data.

## Prerequisites

1. Install UI and date dependencies:
```bash
npm install @mui/x-date-pickers @mui/material @emotion/react @emotion/styled date-fns
```
2. Ensure TypeScript is up-to-date and project builds without errors.

## Step-by-Step Tasks

| # | Task | Files / Modules | Notes |
| --- | ------------------------------------------ | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| 1 | Extend `Todo` type with `dueDate?: string` | `src/types/Todo.ts` | ISO 8601 string (no time component needed). |
| 2 | Update context state & helpers | `src/contexts/TodoContext.tsx`, `hooks/useTodo.tsx` | • Add `dueDate` param to `addTodo`, `editTodo`.<br/>• Default to `undefined` when omitted. |
| 3 | Persist & restore `dueDate` | `src/utils/sessionStorage.ts` | • Include `dueDate` in serialisation.<br/>• Gracefully ignore missing / malformed dates for legacy data. |
| 4 | Wrap app with `LocalizationProvider` | `src/main.tsx` | ```tsx |

<LocalizationProvider dateAdapter={AdapterDateFns}>
<App />
</LocalizationProvider>
```|
|5|Add DatePicker to create / edit flow|`src/components/TodoModal/TodoModal.tsx`|• Import `DatePicker`.<br/>• Local state: `dueDate: Date | null`.<br/>• Convert to ISO on save.<br/>• Allow clearing date (set to `null`).|
|6|Display formatted due date|`src/components/TodoList/TodoItem.tsx`|• If `dueDate` present, show `format(new Date(dueDate), 'PP')`.<br/>• If overdue (`isBefore(new Date(dueDate), today)`), render in `error.main` color.|
|7|Visual tweak for overdue items|`src/components/TodoList/TodoItem.tsx`, CSS|Use MUI palette `error.main` or add a small “Overdue” badge.|
|8|Validation logic|`TodoModal.tsx`|• Reject clearly invalid dates before submit.<br/>• Explicitly allow past dates (per ticket).|
|9|Unit tests|`src/__tests__/*`|• Adjust existing mocks for new property.<br/>• Add tests for: saving/loading `dueDate`, picker renders, overdue styling.|
|10|Docs & cleanup|`README.md`|Brief note on due-date feature & dependencies.|

## Edge Cases & Error Handling

- `dueDate` undefined → treated as “no deadline”.
- Malformed `dueDate` string on load → drop value & log warning via existing toast.
- `sessionStorage` quota exceeded → follow existing toast pattern.

## Acceptance Criteria Mapping

- Creating, editing, and displaying due date aligns with AC.
- Existing todos load unchanged.
- Locale-specific formatting (`PP`).
- Validation prevents impossible dates.
- All unit tests green; coverage ≥ previous baseline.

## Rollback Plan

Revert commit, remove dependency packages, and drop `dueDate` key—legacy data remains compatible.

## Timeline

Ideal effort: 0.5–1 day dev + 0.5 day QA.

---

_Generated automatically — review before execution._
84 changes: 84 additions & 0 deletions src/__tests__/sessionStorage.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import type { Mock } from 'vitest';
import { loadTodos, saveTodos, TODOS_STORAGE_KEY } from '../utils/sessionStorage';
import type { Todo } from '../types/Todo';

// Mock implementation of sessionStorage
const createMockStorage = () => {
let store: Record<string, string> = {};
return {
getItem: vi.fn((key: string) => store[key] ?? null),
setItem: vi.fn((key: string, value: string) => {
store[key] = value;
}),
removeItem: vi.fn((key: string) => {
delete store[key];
}),
clear: vi.fn(() => {
store = {};
}),
} as unknown as Storage;
};

// Sample todo data
const sampleTodos: Todo[] = [
{
id: '1',
title: 'Test',
description: 'Test desc',
completed: false,
createdAt: new Date(),
},
];

describe('sessionStorage utils', () => {
let originalStorage: Storage;

beforeEach(() => {
originalStorage = window.sessionStorage;
Object.defineProperty(window, 'sessionStorage', {
configurable: true,
value: createMockStorage(),
});
});

afterEach(() => {
Object.defineProperty(window, 'sessionStorage', {
configurable: true,
value: originalStorage,
});
});

it('loads todos when valid data exists', () => {
window.sessionStorage.setItem(TODOS_STORAGE_KEY, JSON.stringify(sampleTodos));

const loaded = loadTodos();
expect(loaded).toHaveLength(1);
expect(loaded[0].title).toBe('Test');
});

it('returns empty array and clears storage when data is corrupt', () => {
window.sessionStorage.setItem(TODOS_STORAGE_KEY, 'not-json');

const loaded = loadTodos();
expect(loaded).toEqual([]);
expect(window.sessionStorage.getItem(TODOS_STORAGE_KEY)).toBeNull();
});

it('saves todos successfully', () => {
saveTodos(sampleTodos);
expect(window.sessionStorage.setItem).toHaveBeenCalledWith(
TODOS_STORAGE_KEY,
JSON.stringify(sampleTodos)
);
});

it('throws when quota exceeded', () => {
(window.sessionStorage.setItem as unknown as Mock).mockImplementation(() => {
const error = new DOMException('Quota exceeded', 'QuotaExceededError');
throw error;
});

expect(() => saveTodos(sampleTodos)).toThrowError(DOMException);
});
});
50 changes: 48 additions & 2 deletions src/contexts/TodoContext.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,38 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import type { Todo } from '../types/Todo';
import { v4 as uuidv4 } from 'uuid';
import { TodoContext } from './TodoContextType';
import { loadTodos, saveTodos } from '../utils/sessionStorage';

export const TodoProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [todos, setTodos] = useState<Todo[]>([]);
const isTestEnv = typeof process !== 'undefined' && process.env.NODE_ENV === 'test';

// Hydrate initial state from sessionStorage unless in test environment
const [todos, setTodos] = useState<Todo[]>(() => (isTestEnv ? [] : loadTodos()));

// Local toast message state – null when no toast is visible
const [toastMessage, setToastMessage] = useState<string | null>(null);

// Effect: Persist todos to storage on every change
useEffect(() => {
if (isTestEnv) return;

try {
saveTodos(todos);
} catch (err) {
// Handle QuotaExceededError by notifying the user via toast and continue with in-memory state
console.warn('Storage quota exceeded – falling back to in-memory state', err);
setToastMessage('Storage quota exceeded – your latest changes may not be saved.');
}
}, [todos, isTestEnv]);

// Effect: Hide toast automatically after 5 seconds
useEffect(() => {
if (toastMessage) {
const id = setTimeout(() => setToastMessage(null), 5000);
return () => clearTimeout(id);
}
}, [toastMessage]);

const addTodo = (title: string, description: string) => {
const newTodo: Todo = {
Expand Down Expand Up @@ -32,6 +60,24 @@ export const TodoProvider: React.FC<{ children: React.ReactNode }> = ({ children
return (
<TodoContext.Provider value={{ todos, addTodo, editTodo, toggleTodoCompletion, deleteTodo }}>
{children}
{toastMessage && (

Copilot AI Jul 29, 2025

Copy link

Choose a reason for hiding this comment

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

[nitpick] The inline toast component implementation adds UI concerns to the context provider. Consider extracting this to a separate Toast component for better separation of concerns and reusability.

Copilot uses AI. Check for mistakes.
<div
role="alert"
style={{
position: 'fixed',
bottom: '1rem',
right: '1rem',
background: '#333',
color: '#fff',
padding: '0.75rem 1rem',
borderRadius: '4px',
boxShadow: '0 2px 6px rgba(0,0,0,0.2)',
zIndex: 1000,
}}
>
{toastMessage}
</div>
)}
</TodoContext.Provider>
);
};
Expand Down
76 changes: 76 additions & 0 deletions src/utils/sessionStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
export const TODOS_STORAGE_KEY = 'todos';

import type { Todo } from '../types/Todo';

/**
* Validate that a value is an array of (partial) Todo-like objects that contains
* at least the fields we need to restore app state.
*/
export function isValidTodos(value: unknown): value is Todo[] {
if (!Array.isArray(value)) return false;

return value.every(
item =>
item &&
typeof item.id === 'string' &&
typeof item.title === 'string' &&
typeof item.completed === 'boolean'
);
}

/**
* Attempt to read todos from sessionStorage.
*
* If the data is missing, malformed or fails validation, the key will be
* cleared and an empty array is returned so the app can recover gracefully.
*/
export function loadTodos(): Todo[] {
if (typeof window === 'undefined') return [];

try {
const raw = window.sessionStorage.getItem(TODOS_STORAGE_KEY);
if (!raw) return [];

const parsed: unknown = JSON.parse(raw);
if (isValidTodos(parsed)) {
// Ensure Date objects are revived from ISO strings if present
return (parsed as Todo[]).map(todo => ({
...todo,
createdAt: todo.createdAt ? new Date(todo.createdAt) : new Date(),
}));
}
} catch (err) {
// fall-through – we handle below by clearing storage
console.warn('[sessionStorage] Failed to parse stored todos – resetting', err);
}

// If we reach here the data was invalid or corrupt – clear and return empty
try {
window.sessionStorage.removeItem(TODOS_STORAGE_KEY);
} catch {
/* ignore */
}
return [];
}

/**
* Persist todos to sessionStorage.
*
* On QuotaExceededError the caller can decide how to handle (e.g. show toast).
*/
export function saveTodos(todos: Todo[]): void {
if (typeof window === 'undefined') return;

try {
window.sessionStorage.setItem(TODOS_STORAGE_KEY, JSON.stringify(todos));
} catch (err: unknown) {
if (
err instanceof DOMException &&
(err.name === 'QuotaExceededError' || (err as { code?: number }).code === 22)

Copilot AI Jul 29, 2025

Copy link

Choose a reason for hiding this comment

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

The magic number 22 should be documented or replaced with a named constant. This represents the legacy QuotaExceededError code but lacks context for future maintainers.

Suggested change
(err.name === 'QuotaExceededError' || (err as { code?: number }).code === 22)
(err.name === 'QuotaExceededError' || (err as { code?: number }).code === LEGACY_QUOTA_EXCEEDED_ERROR_CODE)

Copilot uses AI. Check for mistakes.
) {
// Re-throw so caller can handle specifically
throw err;
}
console.warn('[sessionStorage] Failed to save todos', err);
}
}