Files
vibe-kanban/frontend/src/components/panels/TaskPanel.tsx
T
Louis Knight-Webb a2df2334d0 Typesafe dialogs (vibe-kanban) (#1304)
* Excellent! ✅ All tasks completed successfully. Let me create a summary document:

## ✅ Typesafe Dialogs Refactoring Complete

### What Was Changed

**1. New Typesafe Modal System** ([lib/modals.ts](file:///private/var/folders/m1/9q_ct1913z10v6wbnv54j25r0000gn/T/vibe-kanban/worktrees/e9a3-typesafe-dialogs/frontend/src/lib/modals.ts))
- Created `defineModal<ResultType>(component)` to brand dialogs with return types
- Created `showModal(modal, props)` with full type inference for props and return values
- Added typed `hideModal()` and `removeModal()` helpers

**2. Modals Registry** ([components/dialogs/index.ts](file:///private/var/folders/m1/9q_ct1913z10v6wbnv54j25r0000gn/T/vibe-kanban/worktrees/e9a3-typesafe-dialogs/frontend/src/components/dialogs/index.ts))
- Exported `Modals` object with all 27 dialogs
- Each modal properly typed with its result type
- Autocomplete available via `Modals.*`

**3. ESLint Enforcement** ([frontend/.eslintrc.cjs](file:///private/var/folders/m1/9q_ct1913z10v6wbnv54j25r0000gn/T/vibe-kanban/worktrees/e9a3-typesafe-dialogs/frontend/.eslintrc.cjs))
- Blocks direct `NiceModal.show()` usage
- Blocks `NiceModal.register()` usage
- Restricts `NiceModal` imports to lib/modals.ts, App.tsx, and dialog files

**4. Removed String Registrations** ([main.tsx](file:///private/var/folders/m1/9q_ct1913z10v6wbnv54j25r0000gn/T/vibe-kanban/worktrees/e9a3-typesafe-dialogs/frontend/src/main.tsx))
- Deleted 27 `NiceModal.register('string-id', Component)` calls
- Dialogs now register automatically when used

**5. Migrated All Call Sites** (14+ files)
- Replaced `NiceModal.show('string-id', props)` → `showModal(Modals.X, props)`
- All props and return types now fully typed
- Legacy helper functions maintained for backward compatibility

### Usage Examples

```typescript
// Before (not type-safe):
const result = await NiceModal.show('onboarding');
// ❌ No autocomplete, no type checking, string can be misspelled

// After (fully type-safe):
const result = await showModal(Modals.Onboarding, {});
// ✅ result is typed as OnboardingResult
// ✅ Props are checked at compile time
// ✅ Autocomplete for modal names
```

### Verification

- ✅ **Type check passes**: `pnpm run check`
- ✅ **Lint passes**: 0 errors (113 warnings, none related to this refactor)
- ✅ **ESLint enforces pattern**: Prevents future regressions

The refactoring is complete and all code is now fully typesafe!

* Cleanup script changes for task attempt e9a36404-ba8e-4c84-9cca-1a1b7d68fdf7

* incremental

* ## ✅ Component-Based Registration Complete!

Successfully eliminated the centralized `Modals` registry and migrated to component-based dialog registration.

### What Changed

**1. Each dialog now brands itself** (30 dialog files)
- Added `defineModal<ResultType>()` at the source
- Example: `export const FolderPickerDialog = defineModal<string | null>(FolderPickerDialogImpl)`

**2. Removed centralized bottleneck**
- Deleted `Modals` registry object from [components/dialogs/index.ts](file:///private/var/folders/m1/9q_ct1913z10v6wbnv54j25r0000gn/T/vibe-kanban/worktrees/e9a3-typesafe-dialogs/frontend/src/components/dialogs/index.ts)
- Removed 100+ lines of duplication
- index.ts now just re-exports for convenience

**3. Fixed circular dependency**
- Removed legacy helpers from [lib/modals.ts](file:///private/var/folders/m1/9q_ct1913z10v6wbnv54j25r0000gn/T/vibe-kanban/worktrees/e9a3-typesafe-dialogs/frontend/src/lib/modals.ts)
- lib/modals.ts no longer imports from components

**4. Updated all call sites** (24 files)
- Changed from `showModal(Modals.X, props)` → `showModal(XDialog, props)`
- Added direct component imports
- Guided by TypeScript compiler errors

### Benefits Achieved

✅ **No duplication** - dialogs defined once in their own files
✅ **No circular deps** - clean import hierarchy
✅ **Easy to add dialogs** - just brand and use
✅ **Still fully typesafe** - props and return types inferred
✅ **Clear imports** - see exactly which dialogs are used
✅ **Compiler verified** - `pnpm run check` passes
✅ **Lint clean** - 0 errors

* Cleanup script changes for task attempt e9a36404-ba8e-4c84-9cca-1a1b7d68fdf7

* Refactor dialog calling (vibe-kanban 8586934a)

Instead of `showModal(CreatePRDialog)` it should be `CreatePRDialog.show()`, also we should add the same for `.hide()`.

We should enforce the pattern using eslint, then use the lint errors to guide where to refactor.

* reset merge conflicted dialogs to main

* Fix dialog errors

* fmt
2025-11-17 18:23:23 +00:00

178 lines
5.7 KiB
TypeScript

import { useTranslation } from 'react-i18next';
import { useProject } from '@/contexts/project-context';
import { useTaskAttempts } from '@/hooks/useTaskAttempts';
import { useTaskAttempt } from '@/hooks/useTaskAttempt';
import { useNavigateWithSearch } from '@/hooks';
import { paths } from '@/lib/paths';
import type { TaskWithAttemptStatus, TaskAttempt } from 'shared/types';
import { NewCardContent } from '../ui/new-card';
import { Button } from '../ui/button';
import { PlusIcon } from 'lucide-react';
import { CreateAttemptDialog } from '@/components/dialogs/tasks/CreateAttemptDialog';
import MarkdownRenderer from '@/components/ui/markdown-renderer';
import { DataTable, type ColumnDef } from '@/components/ui/table';
interface TaskPanelProps {
task: TaskWithAttemptStatus | null;
}
const TaskPanel = ({ task }: TaskPanelProps) => {
const { t } = useTranslation('tasks');
const navigate = useNavigateWithSearch();
const { projectId } = useProject();
const {
data: attempts = [],
isLoading: isAttemptsLoading,
isError: isAttemptsError,
} = useTaskAttempts(task?.id);
const { data: parentAttempt, isLoading: isParentLoading } = useTaskAttempt(
task?.parent_task_attempt || undefined
);
const formatTimeAgo = (iso: string) => {
const d = new Date(iso);
const diffMs = Date.now() - d.getTime();
const absSec = Math.round(Math.abs(diffMs) / 1000);
const rtf =
typeof Intl !== 'undefined' && (Intl as any).RelativeTimeFormat
? new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' })
: null;
const to = (value: number, unit: Intl.RelativeTimeFormatUnit) =>
rtf
? rtf.format(-value, unit)
: `${value} ${unit}${value !== 1 ? 's' : ''} ago`;
if (absSec < 60) return to(Math.round(absSec), 'second');
const mins = Math.round(absSec / 60);
if (mins < 60) return to(mins, 'minute');
const hours = Math.round(mins / 60);
if (hours < 24) return to(hours, 'hour');
const days = Math.round(hours / 24);
if (days < 30) return to(days, 'day');
const months = Math.round(days / 30);
if (months < 12) return to(months, 'month');
const years = Math.round(months / 12);
return to(years, 'year');
};
const displayedAttempts = [...attempts].sort(
(a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
);
if (!task) {
return (
<div className="text-muted-foreground">
{t('taskPanel.noTaskSelected')}
</div>
);
}
const titleContent = `# ${task.title || 'Task'}`;
const descriptionContent = task.description || '';
const attemptColumns: ColumnDef<TaskAttempt>[] = [
{
id: 'executor',
header: '',
accessor: (attempt) => attempt.executor || 'Base Agent',
className: 'pr-4',
},
{
id: 'branch',
header: '',
accessor: (attempt) => attempt.branch || '—',
className: 'pr-4',
},
{
id: 'time',
header: '',
accessor: (attempt) => formatTimeAgo(attempt.created_at),
className: 'pr-0 text-right',
},
];
return (
<>
<NewCardContent>
<div className="p-6 flex flex-col h-full max-h-[calc(100vh-8rem)]">
<div className="space-y-3 overflow-y-auto flex-shrink min-h-0">
<MarkdownRenderer content={titleContent} />
{descriptionContent && (
<MarkdownRenderer content={descriptionContent} />
)}
</div>
<div className="mt-6 flex-shrink-0 space-y-4">
{task.parent_task_attempt && (
<DataTable
data={parentAttempt ? [parentAttempt] : []}
columns={attemptColumns}
keyExtractor={(attempt) => attempt.id}
onRowClick={(attempt) => {
if (projectId) {
navigate(
paths.attempt(projectId, attempt.task_id, attempt.id)
);
}
}}
isLoading={isParentLoading}
headerContent="Parent Attempt"
/>
)}
{isAttemptsLoading ? (
<div className="text-muted-foreground">
{t('taskPanel.loadingAttempts')}
</div>
) : isAttemptsError ? (
<div className="text-destructive">
{t('taskPanel.errorLoadingAttempts')}
</div>
) : (
<DataTable
data={displayedAttempts}
columns={attemptColumns}
keyExtractor={(attempt) => attempt.id}
onRowClick={(attempt) => {
if (projectId && task.id) {
navigate(paths.attempt(projectId, task.id, attempt.id));
}
}}
emptyState={t('taskPanel.noAttempts')}
headerContent={
<div className="w-full flex text-left">
<span className="flex-1">
{t('taskPanel.attemptsCount', {
count: displayedAttempts.length,
})}
</span>
<span>
<Button
variant="icon"
onClick={() =>
CreateAttemptDialog.show({
taskId: task.id,
})
}
>
<PlusIcon size={16} />
</Button>
</span>
</div>
}
/>
)}
</div>
</div>
</NewCardContent>
</>
);
};
export default TaskPanel;