-
Notifications
You must be signed in to change notification settings - Fork 98
feat(AIADT-10): persist todos in sessionStorage with graceful error h… #3
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
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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._ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||||||
|
||||||
| (err.name === 'QuotaExceededError' || (err as { code?: number }).code === 22) | |
| (err.name === 'QuotaExceededError' || (err as { code?: number }).code === LEGACY_QUOTA_EXCEEDED_ERROR_CODE) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.