diff --git a/README.md b/README.md index 08003f4..f8ef4f5 100644 --- a/README.md +++ b/README.md @@ -109,9 +109,10 @@ src/ - [x] Initial setup (folder structure, routing, styles solution, linting/formatting, error boundary, tests, CI) - [x] Dashboard UI (static): sidebar with mobile drawer, header, toolbar, five status columns, task cards - [x] API connection — fetch tasks into their status columns, with loading skeleton, failure alert + retry, and empty state -- [ ] Create task -- [ ] Update task -- [ ] Delete task +- [x] Create task — the + buttons open a Figma-matched modal (full-screen page on mobile, floating panel on desktop) with custom estimate/assignee/tag menus and per-breakpoint date pickers; createTask + cache invalidation + error handling +- [x] Update task — Edit via the card/list options menu, reusing the shared TaskForm with all six required editable fields (name, due date, position, status, tags, estimate) plus assignee; success/failure notifications +- [x] Delete task — 'Delete Task?' confirmation via the options menu, deleteTask by id, success/failure notifications +- [x] View toggle & My Task — grid/list layouts on both views (list = the mockup's grouped table with due-date row indicators); My Task filters to tasks assigned to the logged-in user via the profile query - [ ] Search & filter - [ ] User settings page @@ -123,6 +124,11 @@ src/ - **Generated GraphQL code is committed on purpose.** `src/graphql/generated/` (output of `npm run codegen`) is checked into git so CI can typecheck and build without holding the API token. Regenerate after changing any query/mutation; never edit by hand. - **Quality gates are CI-enforced, not hook-enforced.** There are deliberately no git hooks (husky/lint-staged): CI runs format check, lint, typecheck, tests, and build on every PR, and the same scripts run locally on demand. Hooks can be added later if commit-time enforcement proves necessary. +- **Tag labels derive from the API enum.** The mockups show sample tag texts that contradict each other across surfaces (the same tag renders "IOS APP" on cards but "IOS" in the tag menu, "ANDROID" on cards but "Android App" in the menu). Since the API's TaskTag enum is the real domain, labels derive from the enum values (IOS, ANDROID, REACT, NODE JS, RAILS) and are identical everywhere. +- **List group-header hover icons are omitted.** One mockup group header shows +/… icons; they have no behavior behind them (non-working UI, same principle as the bell). +- **List rows have an actions column the mockup lacks.** The requirement ties update/delete to the options icon, and a list-only user would otherwise have no way to reach them — requirements outrank mockups, so each row ends with the same options menu the cards use. +- **List-view row borders follow the due date.** The mockup's task table shows rows with identical dates but different left-border colors — an inconsistency the team acknowledged in Slack ("we use to have those in real projects"). Per the team's guidance that the border is a due-date indicator, the rule implemented is: overdue = red (primary), due within two days = amber (tertiary), later = green (secondary). +- **The header bell is THE notification system.** Mutation successes and failures are recorded to a notification center the bell opens (unread dot, ten-entry history, marked read on open); failures additionally surface as inline alerts in the dialog that caused them, so errors are impossible to miss. Transient toasts were built first and deliberately removed — two presentations of the same event stream duplicated a function; the bell is the one the Figma shows. The panel's own design has no mockup, so it reuses the app's menu anatomy. The card metric icons below stay omitted because their data provably does not exist in the schema — the bell's does. - **Card attachment/fork/comment icons are omitted.** The Figma shows those metrics on task cards, but the API's Task type exposes no fields for them. Per mentor guidance not to expose non-working UI, the icons are removed until the schema provides the data; the SVGs live in git history for easy reintroduction. - **Node 24 is a hard requirement** — `.npmrc` sets `engine-strict=true`, so `npm install` fails fast on older Node instead of warning. - **A11y deviation from the design, flagged and recommended per mentor guidance:** the Figma's active-tab red (`primary-4`, `#da584b`) on the dark surface measures ≈3.5:1 below WCAG AA's 4.5:1 for 15px text. Following the design team's process (flag + recommend), the active label uses `primary-3` (`#e27d73`) one step up the design system's own red scale measuring ≈4.7:1 (≈4.5:1 worst-case over the 5% gradient wash). The indicator bar stays `primary-4` (non-text graphic, 3:1 rule, passes). The active state is also conveyed non-visually via `aria-current="page"`. diff --git a/src/app/router.test.tsx b/src/app/router.test.tsx index 7be1d1c..b8baa6f 100644 --- a/src/app/router.test.tsx +++ b/src/app/router.test.tsx @@ -4,7 +4,9 @@ import userEvent from '@testing-library/user-event' import { createMemoryRouter, RouterProvider } from 'react-router' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { routes } from '@/app/router' -import { makeFixtureTasks, tasksRequestMock } from '@/test/fixtures' +import { NotificationsProvider } from '@/components/ui/notifications' +import { makeFixtureProfile, makeFixtureTasks, tasksRequestMock } from '@/test/fixtures' +import { ProfileDocument } from '@/features/tasks/queries' vi.mock('@/lib/graphql-client', () => ({ graphqlClient: { request: vi.fn() }, @@ -14,7 +16,11 @@ beforeEach(() => { vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(new Date('2026-08-06T12:00:00Z')) tasksRequestMock().mockReset() - tasksRequestMock().mockResolvedValue({ tasks: makeFixtureTasks() }) + tasksRequestMock().mockImplementation((document: unknown) => + document === ProfileDocument + ? Promise.resolve({ profile: makeFixtureProfile() }) + : Promise.resolve({ tasks: makeFixtureTasks() }), + ) }) afterEach(() => { @@ -30,7 +36,9 @@ function renderAt(path: string) { const router = createMemoryRouter(routes, { initialEntries: [path] }) return render( - + + + , ) } @@ -98,17 +106,17 @@ describe('dashboard main content', () => { ) if (!card) throw new Error('expected the Twitter card to render inside an
') const scoped = within(card) - expect(scoped.getByText(/8 pts/i)).toBeInTheDocument() + expect(scoped.getByText(/8 points/i)).toBeInTheDocument() expect(scoped.getByText(/yesterday/i)).toBeInTheDocument() expect(scoped.getByText('REACT')).toBeInTheDocument() expect(scoped.getByRole('img', { name: /unassigned/i })).toBeInTheDocument() - expect(scoped.getByRole('img', { name: /task options/i })).toBeInTheDocument() + expect(scoped.getByRole('button', { name: /task options/i })).toBeInTheDocument() }) it('renders the toolbar view icons and the add-task affordance', () => { renderAt('/') - expect(screen.getByRole('img', { name: /grid view/i })).toBeInTheDocument() - expect(screen.getByRole('img', { name: /list view/i })).toBeInTheDocument() + expect(screen.getByRole('button', { name: /grid view/i })).toBeInTheDocument() + expect(screen.getByRole('button', { name: /list view/i })).toBeInTheDocument() expect(screen.getAllByRole('button', { name: /add task/i }).length).toBeGreaterThan(0) }) diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsx index 16eb692..8bdac3b 100644 --- a/src/components/layout/Header.tsx +++ b/src/components/layout/Header.tsx @@ -1,6 +1,7 @@ import { useState } from 'react' import avatarUrl from '@/assets/avatar.png' -import { BellIcon, SearchIcon } from '@/components/ui/icons' +import { SearchIcon } from '@/components/ui/icons' +import { NotificationsBell } from '@/components/layout/NotificationsBell' interface HeaderProps { sidebarOpen: boolean @@ -34,10 +35,10 @@ export function Header({ sidebarOpen, onOpenSidebar }: HeaderProps) { />
- +
- + Profile
diff --git a/src/components/layout/NotificationsBell.tsx b/src/components/layout/NotificationsBell.tsx new file mode 100644 index 0000000..080bd02 --- /dev/null +++ b/src/components/layout/NotificationsBell.tsx @@ -0,0 +1,68 @@ +import { useState } from 'react' +import { BellIcon } from '@/components/ui/icons' +import { useNotifications } from '@/components/ui/notifications-context' + +export function NotificationsBell() { + const { notifications, markAllRead } = useNotifications() + const [open, setOpen] = useState(false) + const hasUnread = notifications.some((item) => !item.read) + + const toggle = () => { + if (!open) markAllRead() + setOpen((current) => !current) + } + + return ( +
{ + if (event.key === 'Escape') setOpen(false) + }} + > + + {open && ( + <> +
+ ) +} diff --git a/src/components/ui/notifications-context.ts b/src/components/ui/notifications-context.ts new file mode 100644 index 0000000..af631ea --- /dev/null +++ b/src/components/ui/notifications-context.ts @@ -0,0 +1,38 @@ +import { createContext, useContext } from 'react' + +export interface AppNotification { + id: number + message: string + tone: 'success' | 'error' + read: boolean +} + +export type Notify = (message: string, tone: AppNotification['tone']) => void + +export interface NotificationsContextValue { + notify: Notify + notifications: AppNotification[] + markAllRead: () => void +} + +export const NotificationsContext = createContext(null) + +function useNotificationsContext(): NotificationsContextValue { + const value = useContext(NotificationsContext) + if (value === null) { + throw new Error('Notification hooks require a NotificationsProvider above — check main.tsx') + } + return value +} + +export function useNotify(): Notify { + return useNotificationsContext().notify +} + +export function useNotifications(): Pick< + NotificationsContextValue, + 'notifications' | 'markAllRead' +> { + const { notifications, markAllRead } = useNotificationsContext() + return { notifications, markAllRead } +} diff --git a/src/components/ui/notifications.tsx b/src/components/ui/notifications.tsx new file mode 100644 index 0000000..b955c01 --- /dev/null +++ b/src/components/ui/notifications.tsx @@ -0,0 +1,33 @@ +import { useCallback, useMemo, useRef, useState, type ReactNode } from 'react' +import { + NotificationsContext, + type AppNotification, + type Notify, + type NotificationsContextValue, +} from '@/components/ui/notifications-context' + +export function NotificationsProvider({ children }: { children: ReactNode }) { + const [notifications, setNotifications] = useState([]) + const nextId = useRef(0) + + const notify = useCallback((message, tone) => { + const id = nextId.current + nextId.current += 1 + setNotifications((current) => [{ id, message, tone, read: false }, ...current].slice(0, 10)) + }, []) + + const markAllRead = useCallback(() => { + setNotifications((current) => + current.some((item) => !item.read) + ? current.map((item) => (item.read ? item : { ...item, read: true })) + : current, + ) + }, []) + + const value = useMemo( + () => ({ notify, notifications, markAllRead }), + [notify, notifications, markAllRead], + ) + + return {children} +} diff --git a/src/components/ui/use-dialog-focus.ts b/src/components/ui/use-dialog-focus.ts new file mode 100644 index 0000000..66126d0 --- /dev/null +++ b/src/components/ui/use-dialog-focus.ts @@ -0,0 +1,41 @@ +import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react' + +export function useDialogFocus(onEscape: () => void) { + const containerRef = useRef(null) + const [opener] = useState(() => document.activeElement) + + useEffect(() => { + return () => { + if (opener instanceof HTMLElement) opener.focus() + } + }, [opener]) + + useEffect(() => { + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') onEscape() + } + window.addEventListener('keydown', onKeyDown) + return () => { + window.removeEventListener('keydown', onKeyDown) + } + }, [onEscape]) + + const trapFocus = (event: ReactKeyboardEvent) => { + if (event.key !== 'Tab' || containerRef.current === null) return + const focusables = [...containerRef.current.querySelectorAll('button, input')] + .filter((el) => el.tabIndex !== -1 && !el.hasAttribute('disabled')) + .filter((el) => el.getClientRects().length > 0) + const first = focusables.at(0) + const last = focusables.at(-1) + if (first === undefined || last === undefined) return + if (event.shiftKey && document.activeElement === first) { + event.preventDefault() + last.focus() + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault() + first.focus() + } + } + + return { containerRef, trapFocus } +} diff --git a/src/features/tasks/CreateTaskModal.tsx b/src/features/tasks/CreateTaskModal.tsx index bcfb703..8fe0314 100644 --- a/src/features/tasks/CreateTaskModal.tsx +++ b/src/features/tasks/CreateTaskModal.tsx @@ -1,399 +1,55 @@ -import { useEffect, useRef, useState } from 'react' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import avatarUrl from '@/assets/avatar.png' +import { useMutation, useQueryClient } from '@tanstack/react-query' import { graphqlClient } from '@/lib/graphql-client' -import { CreateTaskDocument, UsersDocument } from '@/features/tasks/queries' -import { avatarSrc, POINTS, TAG_META } from '@/features/tasks/task-display' -import { DatePicker, DatePickerDialog } from '@/features/tasks/DatePicker' -import { - CalendarIcon, - CheckboxBlankIcon, - CheckboxCheckedIcon, - CloseIcon, - EstimateIcon, - LabelIcon, - UserIcon, -} from '@/features/tasks/icons' -import type { CreateTaskInput, PointEstimate, TaskTag } from '@/graphql/generated/graphql' - -const ESTIMATES: PointEstimate[] = ['ZERO', 'ONE', 'TWO', 'FOUR', 'EIGHT'] -const ALL_TAGS = Object.keys(TAG_META) as TaskTag[] - -type MenuName = 'estimate' | 'assignee' | 'label' | 'date' | null - -const formatDue = (iso: string) => { - const date = new Date(`${iso}T12:00:00`) - const month = date.toLocaleDateString('en-US', { month: 'short' }) - return `${month}. ${String(date.getDate())} ${String(date.getFullYear())}` -} +import { CreateTaskDocument } from '@/features/tasks/queries' +import { dueDateToIso } from '@/features/tasks/task-display' +import { TaskForm } from '@/features/tasks/TaskForm' +import { useNotify } from '@/components/ui/notifications-context' +import type { CreateTaskInput } from '@/graphql/generated/graphql' export function CreateTaskModal({ onClose }: { onClose: () => void }) { - const [name, setName] = useState('') - const [estimate, setEstimate] = useState(null) - const [assigneeId, setAssigneeId] = useState(null) - const [tags, setTags] = useState([]) - const [dueDate, setDueDate] = useState('') - const [openMenu, setOpenMenu] = useState(null) - const [showValidation, setShowValidation] = useState(false) const queryClient = useQueryClient() - - const users = useQuery({ - queryKey: ['users'], - queryFn: () => graphqlClient.request(UsersDocument), - }) + const notify = useNotify() const createTask = useMutation({ mutationFn: (input: CreateTaskInput) => graphqlClient.request(CreateTaskDocument, { input }), onSuccess: () => { void queryClient.invalidateQueries({ queryKey: ['tasks'] }) + notify('Task created.', 'success') onClose() }, + onError: () => { + notify('The task could not be created.', 'error') + }, }) - const containerRef = useRef(null) - const [opener] = useState(() => document.activeElement) - const isPending = createTask.isPending - - const dismiss = () => { - if (!isPending) onClose() - } - - useEffect(() => { - const onKeyDown = (event: KeyboardEvent) => { - if (event.key === 'Escape' && !isPending) onClose() - } - window.addEventListener('keydown', onKeyDown) - return () => { - window.removeEventListener('keydown', onKeyDown) - } - }, [onClose, isPending]) - - useEffect(() => { - return () => { - if (opener instanceof HTMLElement) opener.focus() - } - }, [opener]) - - const trapFocus = (event: React.KeyboardEvent) => { - if (event.key !== 'Tab' || containerRef.current === null) return - const focusables = [...containerRef.current.querySelectorAll('button, input')] - .filter((el) => el.tabIndex !== -1 && !el.hasAttribute('disabled')) - .filter((el) => el.getClientRects().length > 0) - const first = focusables.at(0) - const last = focusables.at(-1) - if (first === undefined || last === undefined) return - if (event.shiftKey && document.activeElement === first) { - event.preventDefault() - last.focus() - } else if (!event.shiftKey && document.activeElement === last) { - event.preventDefault() - first.focus() - } - } - - const selectedAssignee = users.data?.users.find((user) => user.id === assigneeId) - const canSubmit = name.trim().length > 0 && estimate !== null && dueDate !== '' - - const submit = () => { - if (createTask.isPending) return - if (!canSubmit) { - setShowValidation(true) - return - } - createTask.mutate({ - name: name.trim(), - pointEstimate: estimate, - dueDate: new Date(`${dueDate}T12:00:00Z`).toISOString(), - status: 'BACKLOG', - tags, - assigneeId, - }) - } - - const toggleMenu = (menu: MenuName) => { - setOpenMenu((current) => (current === menu ? null : menu)) - } - - const toggleTag = (tag: TaskTag) => { - setTags((current) => - current.includes(tag) ? current.filter((item) => item !== tag) : [...current, tag], - ) - } - return ( -
- - -
- { - setName(event.target.value) - }} - className="w-full bg-transparent text-body-xl font-semibold text-neutral-1 placeholder:text-neutral-2" - /> -
-
- - {openMenu === 'estimate' && ( -
- - Estimate - - {ESTIMATES.map((option) => ( - - ))} -
- )} -
-
- - {openMenu === 'label' && ( -
- - Tag Title - - {ALL_TAGS.map((tag) => ( - - ))} -
- )} -
-
- - {openMenu === 'assignee' && ( -
- - Assign To... - - {(users.data?.users ?? []).map((user) => ( - - ))} -
- )} -
-
- - {openMenu === 'date' && ( - <> -
- { - setDueDate(iso) - setOpenMenu(null) - }} - /> -
-
- { - setOpenMenu(null) - }} - onConfirm={(iso) => { - setDueDate(iso) - setOpenMenu(null) - }} - /> -
- - )} -
-
- {(createTask.isError || (showValidation && !canSubmit)) && ( -
- {canSubmit - ? 'The task could not be created. Check your connection and try again.' - : 'An estimate and a due date are required to create the task.'} -
- )} -
- - -
- - + { + createTask.mutate({ + name: values.name.trim(), + pointEstimate: values.estimate, + dueDate: dueDateToIso(values.dueDate), + status: values.status, + tags: values.tags, + assigneeId: values.assigneeId, + }) + }} + onClose={onClose} + /> ) } diff --git a/src/features/tasks/Dashboard.tsx b/src/features/tasks/Dashboard.tsx index c84f96c..7623990 100644 --- a/src/features/tasks/Dashboard.tsx +++ b/src/features/tasks/Dashboard.tsx @@ -1,12 +1,15 @@ +import { useState } from 'react' import { Toolbar } from '@/features/tasks/Toolbar' import { TasksView } from '@/features/tasks/TasksView' +import type { BoardLayout } from '@/features/tasks/types' export function Dashboard() { + const [layout, setLayout] = useState('grid') return (

Dashboard

- - + +
) } diff --git a/src/features/tasks/DatePicker.tsx b/src/features/tasks/DatePicker.tsx index ad1bf67..737a7f6 100644 --- a/src/features/tasks/DatePicker.tsx +++ b/src/features/tasks/DatePicker.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react' +import { useState, type ComponentType } from 'react' import { ChevronLeftIcon, ChevronRightIcon, @@ -6,14 +6,31 @@ import { ChevronsRightIcon, ChevronThinRightIcon, } from '@/features/tasks/icons' +import type { IconProps } from '@/components/ui/icons' const WEEKDAYS = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] +const DIALOG_WEEKDAYS = ['S', 'M', 'T', 'W', 'T', 'F', 'S'] const toIso = (date: Date) => `${String(date.getFullYear())}-${String(date.getMonth() + 1).padStart(2, '0')}-${String( date.getDate(), ).padStart(2, '0')}` +function useMonthView(value: string) { + const today = new Date() + const initial = value === '' ? today : new Date(`${value}T12:00:00`) + const [viewYear, setViewYear] = useState(initial.getFullYear()) + const [viewMonth, setViewMonth] = useState(initial.getMonth()) + + const moveView = (deltaMonths: number) => { + const next = new Date(viewYear, viewMonth + deltaMonths, 1) + setViewYear(next.getFullYear()) + setViewMonth(next.getMonth()) + } + + return { today, initial, viewYear, viewMonth, moveView } +} + const dayTone = (selected: boolean, isToday: boolean, inMonth: boolean) => { if (selected) return 'bg-primary-4 text-neutral-1' if (isToday) return 'border border-primary-4 text-neutral-1' @@ -25,17 +42,33 @@ interface DatePickerProps { onSelect: (iso: string) => void } -export function DatePicker({ value, onSelect }: DatePickerProps) { - const today = new Date() - const initial = value === '' ? today : new Date(`${value}T12:00:00`) - const [viewYear, setViewYear] = useState(initial.getFullYear()) - const [viewMonth, setViewMonth] = useState(initial.getMonth()) +function NavButton({ + label, + delta, + Icon, + onNav, +}: { + label: string + delta: number + Icon: ComponentType + onNav: (delta: number) => void +}) { + return ( + + ) +} - const moveView = (deltaMonths: number) => { - const next = new Date(viewYear, viewMonth + deltaMonths, 1) - setViewYear(next.getFullYear()) - setViewMonth(next.getMonth()) - } +export function DatePicker({ value, onSelect }: DatePickerProps) { + const { today, viewYear, viewMonth, moveView } = useMonthView(value) const monthLabel = new Date(viewYear, viewMonth, 1).toLocaleDateString('en-US', { month: 'short', @@ -55,49 +88,13 @@ export function DatePicker({ value, onSelect }: DatePickerProps) { >
- - + +
{monthLabel}
- - + +
@@ -151,8 +148,6 @@ export function DatePicker({ value, onSelect }: DatePickerProps) { ) } -const DIALOG_WEEKDAYS = ['S', 'M', 'T', 'W', 'T', 'F', 'S'] - const dialogDayTone = (selected: boolean, isToday: boolean) => { if (selected) return 'bg-primary-4' if (isToday) return 'border-2 border-primary-3' @@ -166,17 +161,8 @@ interface DatePickerDialogProps { } export function DatePickerDialog({ value, onCancel, onConfirm }: DatePickerDialogProps) { - const today = new Date() - const initial = value === '' ? today : new Date(`${value}T12:00:00`) + const { today, initial, viewYear, viewMonth, moveView } = useMonthView(value) const [pending, setPending] = useState(toIso(initial)) - const [viewYear, setViewYear] = useState(initial.getFullYear()) - const [viewMonth, setViewMonth] = useState(initial.getMonth()) - - const moveView = (deltaMonths: number) => { - const next = new Date(viewYear, viewMonth + deltaMonths, 1) - setViewYear(next.getFullYear()) - setViewMonth(next.getMonth()) - } const pendingDate = new Date(`${pending}T12:00:00`) const headline = pendingDate.toLocaleDateString('en-US', { @@ -194,18 +180,14 @@ export function DatePickerDialog({ value, onCancel, onConfirm }: DatePickerDialo const todayIso = toIso(today) return ( -
+
{pendingDate.getFullYear()} {headline}
-
+
+ +
+
+
+ ) +} diff --git a/src/features/tasks/EditTaskModal.tsx b/src/features/tasks/EditTaskModal.tsx new file mode 100644 index 0000000..9458827 --- /dev/null +++ b/src/features/tasks/EditTaskModal.tsx @@ -0,0 +1,60 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { graphqlClient } from '@/lib/graphql-client' +import { UpdateTaskDocument } from '@/features/tasks/queries' +import { dueDateToIso } from '@/features/tasks/task-display' +import { TaskForm } from '@/features/tasks/TaskForm' +import { useNotify } from '@/components/ui/notifications-context' +import type { ApiTask } from '@/features/tasks/types' +import type { UpdateTaskInput } from '@/graphql/generated/graphql' + +export function EditTaskModal({ task, onClose }: { task: ApiTask; onClose: () => void }) { + const queryClient = useQueryClient() + const notify = useNotify() + + const updateTask = useMutation({ + mutationFn: (input: UpdateTaskInput) => graphqlClient.request(UpdateTaskDocument, { input }), + onSuccess: () => { + void queryClient.invalidateQueries({ queryKey: ['tasks'] }) + notify('Task updated.', 'success') + onClose() + }, + onError: () => { + notify('The task could not be updated.', 'error') + }, + }) + + return ( + { + updateTask.mutate({ + id: task.id, + name: values.name.trim(), + pointEstimate: values.estimate, + dueDate: dueDateToIso(values.dueDate), + status: values.status, + tags: values.tags, + assigneeId: values.assigneeId, + position: Number(values.position), + }) + }} + onClose={onClose} + /> + ) +} diff --git a/src/features/tasks/MyTask.tsx b/src/features/tasks/MyTask.tsx index 6776a7e..4fa7e55 100644 --- a/src/features/tasks/MyTask.tsx +++ b/src/features/tasks/MyTask.tsx @@ -1,12 +1,39 @@ +import { useState } from 'react' +import { useQuery } from '@tanstack/react-query' +import { graphqlClient } from '@/lib/graphql-client' +import { ProfileDocument } from '@/features/tasks/queries' +import { QueryErrorAlert } from '@/features/tasks/QueryErrorAlert' import { Toolbar } from '@/features/tasks/Toolbar' import { TasksView } from '@/features/tasks/TasksView' +import type { BoardLayout } from '@/features/tasks/types' export function MyTask() { + const [layout, setLayout] = useState('list') + const profile = useQuery({ + queryKey: ['profile'], + queryFn: () => graphqlClient.request(ProfileDocument), + }) + return (

My Task

- - + + {profile.isPending && ( +

+ Loading your profile… +

+ )} + {profile.isError && ( + { + void profile.refetch() + }} + /> + )} + {profile.data !== undefined && ( + + )}
) } diff --git a/src/features/tasks/QueryErrorAlert.tsx b/src/features/tasks/QueryErrorAlert.tsx new file mode 100644 index 0000000..5db6b57 --- /dev/null +++ b/src/features/tasks/QueryErrorAlert.tsx @@ -0,0 +1,17 @@ +export function QueryErrorAlert({ message, onRetry }: { message: string; onRetry: () => void }) { + return ( +
+

{message}

+ +
+ ) +} diff --git a/src/features/tasks/TaskActions.tsx b/src/features/tasks/TaskActions.tsx new file mode 100644 index 0000000..85b4353 --- /dev/null +++ b/src/features/tasks/TaskActions.tsx @@ -0,0 +1,86 @@ +import { useRef, useState } from 'react' +import { DotsIcon, EditIcon, TrashIcon } from '@/features/tasks/icons' +import { EditTaskModal } from '@/features/tasks/EditTaskModal' +import { DeleteTaskDialog } from '@/features/tasks/DeleteTaskDialog' +import type { ApiTask } from '@/features/tasks/types' + +export function TaskActions({ task }: { task: ApiTask }) { + const [menuOpen, setMenuOpen] = useState(false) + const [dialog, setDialog] = useState<'edit' | 'delete' | null>(null) + const triggerRef = useRef(null) + + const openDialog = (which: 'edit' | 'delete') => { + setMenuOpen(false) + setDialog(which) + } + + const closeDialog = () => { + setDialog(null) + triggerRef.current?.focus() + } + + return ( +
{ + if (event.key === 'Escape') setMenuOpen(false) + }} + > + + {menuOpen && ( + <> + + +
+ + )} + {dialog === 'edit' && } + {dialog === 'delete' && } +
+ ) +} diff --git a/src/features/tasks/TaskCard.tsx b/src/features/tasks/TaskCard.tsx index 010a5c3..6f24262 100644 --- a/src/features/tasks/TaskCard.tsx +++ b/src/features/tasks/TaskCard.tsx @@ -1,31 +1,25 @@ import avatarUrl from '@/assets/avatar.png' -import { AlarmIcon, DotsIcon } from '@/features/tasks/icons' +import { AlarmIcon } from '@/features/tasks/icons' import { avatarSrc, dueInfo, pointsLabel, TAG_META, - type TagTone, + tagToneClasses, } from '@/features/tasks/task-display' +import { TaskActions } from '@/features/tasks/TaskActions' import type { ApiTask } from '@/features/tasks/types' -const tagToneClasses: Record = { - secondary: 'bg-secondary-4/10 text-secondary-4', - tertiary: 'bg-tertiary-4/10 text-tertiary-4', - neutral: 'bg-neutral-2/10 text-neutral-1', -} - export function TaskCard({ task }: { task: ApiTask }) { const due = dueInfo(task.dueDate) + return (

{task.name}

- - - +
diff --git a/src/features/tasks/TaskForm.tsx b/src/features/tasks/TaskForm.tsx new file mode 100644 index 0000000..03719e5 --- /dev/null +++ b/src/features/tasks/TaskForm.tsx @@ -0,0 +1,469 @@ +import { useState, type ReactNode } from 'react' +import { useQuery } from '@tanstack/react-query' +import avatarUrl from '@/assets/avatar.png' +import { graphqlClient } from '@/lib/graphql-client' +import { UsersDocument } from '@/features/tasks/queries' +import { useDialogFocus } from '@/components/ui/use-dialog-focus' +import { avatarSrc, POINTS, STATUS_COLUMNS, TAG_META } from '@/features/tasks/task-display' +import { DatePicker, DatePickerDialog } from '@/features/tasks/DatePicker' +import { + CalendarIcon, + CheckboxBlankIcon, + CheckboxCheckedIcon, + CloseIcon, + EstimateIcon, + LabelIcon, + UserIcon, +} from '@/features/tasks/icons' +import type { PointEstimate, Status, TaskTag } from '@/graphql/generated/graphql' + +const ESTIMATES = Object.keys(POINTS) as PointEstimate[] +const ALL_TAGS = Object.keys(TAG_META) as TaskTag[] + +type MenuName = 'estimate' | 'assignee' | 'label' | 'status' | 'date' | null + +interface TaskFormValues { + name: string + estimate: PointEstimate | null + assigneeId: string | null + tags: TaskTag[] + dueDate: string + status: Status + position: string +} + +interface TaskFormSubmitValues extends Omit { + estimate: PointEstimate +} + +interface TaskFormProps { + ariaLabel: string + initialValues: TaskFormValues + submitLabel: string + pendingLabel: string + errorMessage: string + showStatus?: boolean + showPosition?: boolean + isPending: boolean + isError: boolean + onSubmit: (values: TaskFormSubmitValues) => void + onClose: () => void +} + +function MenuPanel({ + title, + className, + children, +}: { + title: string + className: string + children: ReactNode +}) { + return ( +
+ + {title} + + {children} +
+ ) +} + +const formatDue = (iso: string) => { + const date = new Date(`${iso}T12:00:00`) + const month = date.toLocaleDateString('en-US', { month: 'short' }) + return `${month}. ${String(date.getDate())} ${String(date.getFullYear())}` +} + +export function TaskForm({ + ariaLabel, + initialValues, + submitLabel, + pendingLabel, + errorMessage, + showStatus = false, + showPosition = false, + isPending, + isError, + onSubmit, + onClose, +}: TaskFormProps) { + const [name, setName] = useState(initialValues.name) + const [estimate, setEstimate] = useState(initialValues.estimate) + const [assigneeId, setAssigneeId] = useState(initialValues.assigneeId) + const [tags, setTags] = useState(initialValues.tags) + const [dueDate, setDueDate] = useState(initialValues.dueDate) + const [status, setStatus] = useState(initialValues.status) + const [position, setPosition] = useState(initialValues.position) + const [openMenu, setOpenMenu] = useState(null) + const [showValidation, setShowValidation] = useState(false) + + const users = useQuery({ + queryKey: ['users'], + queryFn: () => graphqlClient.request(UsersDocument), + }) + + const dismiss = () => { + if (!isPending) onClose() + } + + const { containerRef, trapFocus } = useDialogFocus(() => { + if (openMenu !== null) { + setOpenMenu(null) + return + } + dismiss() + }) + + const selectedAssignee = users.data?.users.find((user) => user.id === assigneeId) + const statusTitle = STATUS_COLUMNS.find((column) => column.status === status)?.title ?? status + const positionNumber = Number(position) + const positionValid = + !showPosition || (position !== '' && Number.isFinite(positionNumber) && positionNumber > 0) + const canSubmit = name.trim().length > 0 && estimate !== null && dueDate !== '' && positionValid + const validationMessage = + estimate !== null && dueDate !== '' && !positionValid + ? 'Position must be a number greater than zero.' + : 'An estimate and a due date are required.' + + const submit = () => { + if (isPending) return + if (!canSubmit) { + setShowValidation(true) + return + } + onSubmit({ name, estimate, assigneeId, tags, dueDate, status, position }) + } + + const toggleMenu = (menu: MenuName) => { + setOpenMenu((current) => (current === menu ? null : menu)) + } + + const toggleTag = (tag: TaskTag) => { + setTags((current) => + current.includes(tag) ? current.filter((item) => item !== tag) : [...current, tag], + ) + } + + return ( +
+ + +
+ { + setName(event.target.value) + }} + className="w-full bg-transparent text-body-xl font-semibold text-neutral-1 placeholder:text-neutral-2" + /> +
+
+ + {openMenu === 'estimate' && ( + + {ESTIMATES.map((option) => ( + + ))} + + )} +
+
+ + {openMenu === 'label' && ( + + {ALL_TAGS.map((tag) => ( + + ))} + + )} +
+
+ + {openMenu === 'assignee' && ( + + {users.isPending && ( +

Loading users…

+ )} + {users.isError && ( +

Could not load users.

+ )} + {(users.data?.users ?? []).map((user) => ( + + ))} +
+ )} +
+ {showStatus && ( +
+ + {openMenu === 'status' && ( + + {STATUS_COLUMNS.map((column) => ( + + ))} + + )} +
+ )} + {showPosition && ( + + )} +
+ + {openMenu === 'date' && ( + <> +
+ { + setDueDate(iso) + setOpenMenu(null) + }} + /> +
+
+ { + setOpenMenu(null) + }} + onConfirm={(iso) => { + setDueDate(iso) + setOpenMenu(null) + }} + /> +
+ + )} +
+
+ {(isError || (showValidation && !canSubmit)) && ( +
+ {canSubmit ? errorMessage : validationMessage} +
+ )} +
+ + +
+
+
+ ) +} diff --git a/src/features/tasks/TaskList.tsx b/src/features/tasks/TaskList.tsx new file mode 100644 index 0000000..2624326 --- /dev/null +++ b/src/features/tasks/TaskList.tsx @@ -0,0 +1,124 @@ +import avatarUrl from '@/assets/avatar.png' +import { CaretDownIcon } from '@/features/tasks/icons' +import { TaskActions } from '@/features/tasks/TaskActions' +import { + avatarSrc, + dueInfo, + POINTS, + TAG_META, + tagToneClasses, + type DueTone, +} from '@/features/tasks/task-display' +import type { ApiTask, BoardColumn } from '@/features/tasks/types' + +const toneBorder: Record = { + primary: 'border-l-primary-4', + tertiary: 'border-l-tertiary-4', + secondary: 'border-l-secondary-4', +} + +const cellBase = 'flex h-14 items-center border border-neutral-3 bg-neutral-4 py-1' +const nameWidth = 'min-w-60 flex-1' +const tagsWidth = 'w-42 shrink-0' +const estimateWidth = 'w-35 shrink-0' +const assigneeWidth = 'w-42 shrink-0' +const dueWidth = 'w-33 shrink-0' +const actionsWidth = 'w-14 shrink-0' + +const HEADERS = [ + { label: '# Task Name', className: `${nameWidth} rounded-l px-4` }, + { label: 'Task Tags', className: `${tagsWidth} pr-4 pl-4` }, + { label: 'Estimate', className: `${estimateWidth} pr-4 pl-4` }, + { label: 'Task Assign Name', className: `${assigneeWidth} pr-4 pl-4` }, + { label: 'Due Date', className: `${dueWidth} pr-4 pl-4` }, + { label: '', className: `${actionsWidth} rounded-r` }, +] + +const titleCase = (label: string) => label.toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase()) + +function TaskRow({ task, index }: { task: ApiTask; index: number }) { + const due = dueInfo(task.dueDate) + const firstTag = task.tags.at(0) + return ( +
+
+ {String(index + 1).padStart(2, '0')} + {task.name} +
+
+ {firstTag !== undefined && ( + + {TAG_META[firstTag].label} + + )} + {task.tags.length > 1 && ( + + +{task.tags.length - 1} + + )} +
+
+ + {String(POINTS[task.pointEstimate])} Points + +
+
+ + + {task.assignee?.fullName ?? 'Unassigned'} + +
+
+ + {titleCase(due.label)} + +
+
+ +
+
+ ) +} + +export function TaskList({ columns }: { columns: BoardColumn[] }) { + return ( +
+
+
+ {HEADERS.map((header, index) => ( +
+ {header.label} +
+ ))} +
+ {columns.map((column) => ( +
+
+ +

+ {column.title}{' '} + + ({String(column.tasks.length).padStart(2, '0')}) + +

+
+ {column.tasks.map((task, index) => ( + + ))} +
+ ))} +
+
+ ) +} diff --git a/src/features/tasks/TasksView.tsx b/src/features/tasks/TasksView.tsx index 431eea1..aa5bc34 100644 --- a/src/features/tasks/TasksView.tsx +++ b/src/features/tasks/TasksView.tsx @@ -1,6 +1,12 @@ +import { useQuery } from '@tanstack/react-query' +import { graphqlClient } from '@/lib/graphql-client' +import { TasksDocument } from '@/features/tasks/queries' import { TaskBoard } from '@/features/tasks/TaskBoard' +import { TaskList } from '@/features/tasks/TaskList' +import { QueryErrorAlert } from '@/features/tasks/QueryErrorAlert' import { groupTasksByStatus } from '@/features/tasks/task-display' -import { useTasks } from '@/features/tasks/useTasks' +import type { BoardLayout } from '@/features/tasks/types' +import type { FilterTaskInput } from '@/graphql/generated/graphql' function TaskBoardSkeleton() { return ( @@ -21,28 +27,27 @@ function TaskBoardSkeleton() { ) } -export function TasksView() { - const { data, isPending, isError, refetch } = useTasks() +interface TasksViewProps { + input?: FilterTaskInput + layout?: BoardLayout +} + +export function TasksView({ input = {}, layout = 'grid' }: TasksViewProps) { + const { data, isPending, isError, refetch } = useQuery({ + queryKey: ['tasks', input], + queryFn: () => graphqlClient.request(TasksDocument, { input }), + }) if (isPending) return if (isError) { return ( -
-

Something went wrong while loading tasks.

- -
+ { + void refetch() + }} + /> ) } @@ -50,5 +55,6 @@ export function TasksView() { return

No tasks found.

} - return + const columns = groupTasksByStatus(data.tasks) + return layout === 'grid' ? : } diff --git a/src/features/tasks/Toolbar.tsx b/src/features/tasks/Toolbar.tsx index ba9bf06..18d7565 100644 --- a/src/features/tasks/Toolbar.tsx +++ b/src/features/tasks/Toolbar.tsx @@ -3,47 +3,62 @@ import { useLocation } from 'react-router' import { GridIcon, ListIcon } from '@/components/ui/icons' import { PlusIcon } from '@/features/tasks/icons' import { CreateTaskModal } from '@/features/tasks/CreateTaskModal' +import type { BoardLayout } from '@/features/tasks/types' -export function Toolbar() { +interface ToolbarProps { + layout: BoardLayout + onLayoutChange: (layout: BoardLayout) => void +} + +export function Toolbar({ layout, onLayoutChange }: ToolbarProps) { const { pathname } = useLocation() const [createOpen, setCreateOpen] = useState(false) const onMyTask = pathname === '/my-task' return (
-
- - Dashboard - - -
-
- - Task - - -
+ {[ + { label: 'Dashboard', active: !onMyTask }, + { label: 'Task', active: onMyTask }, + ].map((tab) => ( +
+ + {tab.label} + + +
+ ))}
- { + onLayoutChange('list') + }} + className={`flex size-10 items-center justify-center rounded-lg ${ + layout === 'list' ? 'border border-primary-4 text-primary-4' : 'text-neutral-1' + }`} > - - - + +