mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 19:34:38 +00:00
feat(agentic kanban): phase 1 not-agentic kanban board (#330)
* feat(kanban): implement AI-native kanban database models, services, and REST APIs * feat(webui): implement team kanban board and task management * style(webui): increase kanban dialog widths and form container * fix(webui): ensure kanban dialogs override sm:max-w-lg base class * style(webui): set edit task dialog max width to 5xl * chore: untrack kanban plan markdown files * feat(webui): update kanban page layout to 2 columns and refine task activity UI * fix(webui): constrain kanban column and board heights for vertical scrolling * feat(kanban): unify task status transition into updateTask API and allow unconstrained human task transitions * fix(webui): add optimistic updates to kanban drag-and-drop to eliminate flash * refactor(webui): remove client-side search box from kanban header * feat(kanban): redesign task dialog comments area and add attachment support * refactor(webui): remove top status action bar from task info dialog * fix(webui): narrow query cache predicate and add defensive guards for kanban drag optimistic update * feat(kanban): add drag-and-drop task reordering with fractional indexing (#331) * feat(kanban): add drag-and-drop task reordering with fractional indexing * fix(kanban): improve card drop zones, snap indicators, and column highlight * fix(kanban): enable card droppables only during active drag * fix(kanban): refine hover styles and drop indicators for column boundaries * fix(kanban): unify bottom drop indicator and fix top indicator clipping * fix(kanban): ensure full column highlight and full coverage drop target * minor change * feat(kanban): allow agent tasks free drag-and-drop and enforce status change permissions (#332) * refactor(kanban): rename task_type_agentic translation keys to task_type_agent * feat(kanban): refactor task type enum to isAgentTask boolean (#333) * refactor(kanban): remove phase 2 agent execution logic and streamline phase 1 kanban * feat(kanban): add notifications and audit logging for kanban (#334) * feat(kanban): redesign config area layout and add parent tasks multi-selector (#335) * feat(webui): redesign kanban task dialog config area * feat(kanban): simplify task dependencies with parent tasks multi-selector * refactor(kanban): remove unused links routes and legacy dependency methods * feat(kanban): connect assets and kanban tasks with many-to-many relationship (#336) * feat(kanban): connect assets and kanban tasks with many-to-many relationship * feat(kanban): improve asset picker layout, infinite scrolling, and breadcrumb icon styling * fix(kanban): ensure asset picker scrollarea is scrollable with min-h-0 and shrink-0 flex styling * fix(kanban): hide recently deleted in folder tree picker and adjust header padding * fix(kanban): use lucide files icon instead of paperclip for linked assets * feat(kanban): improve task deletion, goal sidebar interaction, and card styling (#337) * feat(kanban): improve task deletion, goal sidebar interaction, and card styling * feat(kanban): move agent task badge after priority and update to orange style * feat(kanban): add status Compare-And-Swap (CAS) to prevent drag-and-drop race conditions (#338) * feat(kanban): add status Compare-And-Swap (CAS) to prevent drag-and-drop race conditions * style(kanban): rotate kanban icon 180 degrees in sidebar and top nav * style(kanban): remove rotate-180 from SquareKanban icons * feat(kanban): add unassigned goal record and fix all tasks count (#339) * feat(kanban): add unassigned goal record and fix all tasks count * feat(kanban): toggle task count with three-dot action button on goal card hover * fix(ci): pin bun version to 1.3.14 across CI and Docker (#340) * fix(webui): truncate goal name to max 2 lines in kanban sidebar (#341)
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React from 'react'
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { BreadcrumbNav } from './breadcrumb-nav'
|
||||
|
||||
// Mock tanstack router Link
|
||||
vi.mock('@tanstack/react-router', () => ({
|
||||
Link: ({ children, to, ...props }: { children: React.ReactNode; to: string }) => (
|
||||
<a href={to} {...props}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
useNavigate: () => vi.fn(),
|
||||
useMatch: () => false,
|
||||
}))
|
||||
|
||||
describe('BreadcrumbNav component', () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
const baseProps = {
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
projectName: 'Demo Project',
|
||||
ancestorFolders: [],
|
||||
currentAsset: {
|
||||
id: 'asset-1',
|
||||
name: 'Folder A',
|
||||
type: 'folder' as const,
|
||||
},
|
||||
isRootFolder: false,
|
||||
isRightSidebarCollapsed: false,
|
||||
onRightSidebarToggle: vi.fn(),
|
||||
}
|
||||
|
||||
it('renders SquareKanban task link button for non-root folder', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BreadcrumbNav {...baseProps} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getByTitle(/Linked Tasks|关联任务/i)).toBeDefined()
|
||||
})
|
||||
|
||||
it('hides SquareKanban task link button on project root folder', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BreadcrumbNav {...baseProps} isRootFolder={true} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.queryByTitle(/Linked Tasks|关联任务/i)).toBeNull()
|
||||
})
|
||||
|
||||
it('hides SquareKanban task link button for public share view', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BreadcrumbNav {...baseProps} isPublic={true} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.queryByTitle(/Linked Tasks|关联任务/i)).toBeNull()
|
||||
})
|
||||
|
||||
it('hides SquareKanban task link button on Recently Deleted view', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BreadcrumbNav {...baseProps} currentAsset={{ name: 'Recently Deleted', type: 'folder' }} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.queryByTitle(/Linked Tasks|关联任务/i)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,6 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -30,6 +31,7 @@ import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { AncestorFolder } from '@shumai/dtos'
|
||||
import { Link, useNavigate } from '@tanstack/react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import {
|
||||
Bot,
|
||||
Check,
|
||||
@@ -39,9 +41,11 @@ import {
|
||||
History,
|
||||
LayoutGrid,
|
||||
List,
|
||||
SquareKanban,
|
||||
} from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { ManageVersionsDialog } from './manage-versions-dialog'
|
||||
import { AssetLinkedTasksDialog } from './kanban/asset-linked-tasks-dialog'
|
||||
|
||||
interface BreadcrumbNavProps {
|
||||
teamId: string
|
||||
@@ -49,6 +53,7 @@ interface BreadcrumbNavProps {
|
||||
projectName: string
|
||||
ancestorFolders: AncestorFolder[]
|
||||
currentAsset: {
|
||||
id?: string
|
||||
name?: string
|
||||
type: 'file' | 'folder'
|
||||
version?: number
|
||||
@@ -123,6 +128,33 @@ export function BreadcrumbNav({
|
||||
const navigate = useNavigate()
|
||||
const { canEdit } = usePermissions(projectId)
|
||||
const [isManageVersionsOpen, setIsManageVersionsOpen] = useState(false)
|
||||
const [isLinkedTasksOpen, setIsLinkedTasksOpen] = useState(false)
|
||||
|
||||
const targetAssetId = fileId || currentAsset.id
|
||||
const isRecentlyDeleted = currentAsset.name === 'Recently Deleted'
|
||||
const isCollection = currentAsset.name === 'All Collections'
|
||||
const showKanbanLink =
|
||||
!isPublic &&
|
||||
!isRootFolder &&
|
||||
!isRecentlyDeleted &&
|
||||
!isCollection &&
|
||||
!compareMode &&
|
||||
!!targetAssetId
|
||||
|
||||
const { data: linkedTasksData } = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'assets', targetAssetId, 'tasks'],
|
||||
queryFn: async () => {
|
||||
if (!teamId || !targetAssetId) return { data: [], total: 0 }
|
||||
const res = await client.api.teams[':teamId'].kanban.assets[':assetId'].tasks.$get({
|
||||
param: { teamId, assetId: targetAssetId },
|
||||
})
|
||||
if (!res.ok) return { data: [], total: 0 }
|
||||
return (await res.json()) as { data: Array<{ id: string }>; total: number }
|
||||
},
|
||||
enabled: !!teamId && !!targetAssetId && showKanbanLink,
|
||||
})
|
||||
|
||||
const linkedTaskCount = linkedTasksData?.total ?? linkedTasksData?.data?.length ?? 0
|
||||
|
||||
const isChatbotDisabled = false
|
||||
|
||||
@@ -399,6 +431,33 @@ export function BreadcrumbNav({
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{showKanbanLink && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs gap-1.5 text-muted-foreground hover:text-foreground hover:bg-muted ml-1 cursor-pointer"
|
||||
onClick={() => setIsLinkedTasksOpen(true)}
|
||||
title={m.linked_tasks()}
|
||||
>
|
||||
<SquareKanban className="w-4 h-4" />
|
||||
{linkedTaskCount > 0 && (
|
||||
<span className="inline-flex items-center justify-center px-1.5 py-0.2 text-[10px] font-semibold rounded-full bg-muted-foreground/15 text-foreground">
|
||||
{linkedTaskCount}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{showKanbanLink && isLinkedTasksOpen && targetAssetId && (
|
||||
<AssetLinkedTasksDialog
|
||||
teamId={teamId}
|
||||
assetId={targetAssetId}
|
||||
assetName={currentAsset.name}
|
||||
isOpen={isLinkedTasksOpen}
|
||||
onClose={() => setIsLinkedTasksOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{fileId && versions && versions.length > 0 && (
|
||||
<ManageVersionsDialog
|
||||
open={isManageVersionsOpen}
|
||||
|
||||
@@ -164,8 +164,8 @@ export default function FileSystemManager({
|
||||
currentAsset: isRecentlyDeleted
|
||||
? { name: 'Recently Deleted', type: 'folder' }
|
||||
: isCollection
|
||||
? { name: collection.name, type: 'folder' }
|
||||
: { name: folderInfo?.name, type: 'folder' },
|
||||
? { id: collection.id, name: collection.name, type: 'folder' }
|
||||
: { id: folderInfo?.id || assetId, name: folderInfo?.name, type: 'folder' },
|
||||
isRootFolder: !isRecentlyDeleted && !isCollection && assetId === rootFolderId,
|
||||
onFolderClick: (id: string) => {
|
||||
navigate({
|
||||
|
||||
@@ -73,6 +73,7 @@ interface FolderTreeProps {
|
||||
selectedFolderId?: string
|
||||
hideCollections?: boolean
|
||||
hideShares?: boolean
|
||||
hideRecentlyDeleted?: boolean
|
||||
ancestorFolders?: AncestorFolder[]
|
||||
}
|
||||
|
||||
@@ -86,6 +87,7 @@ export function FolderTree({
|
||||
selectedFolderId,
|
||||
hideCollections,
|
||||
hideShares,
|
||||
hideRecentlyDeleted,
|
||||
ancestorFolders,
|
||||
}: FolderTreeProps) {
|
||||
const navigate = useNavigate()
|
||||
@@ -513,7 +515,7 @@ export function FolderTree({
|
||||
ancestorFolders={ancestorFolders}
|
||||
/>
|
||||
|
||||
{canEdit && (
|
||||
{canEdit && !hideRecentlyDeleted && (
|
||||
<div
|
||||
className={cn(
|
||||
'group flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { KanbanTaskStatus, type KanbanTaskInfo } from '@shumai/dtos'
|
||||
import {
|
||||
getStatusBadgeColor,
|
||||
getStatusLabel,
|
||||
getPriorityBadgeColor,
|
||||
getPriorityLabel,
|
||||
} from './kanban-types'
|
||||
import { EditTaskDialog } from './edit-task-dialog/edit-task-dialog'
|
||||
import { SquareKanban, Plus, X, Search, Loader2, Bot } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
interface AssetLinkedTasksDialogProps {
|
||||
teamId: string
|
||||
assetId: string
|
||||
assetName?: string
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const SELECTABLE_STATUSES: KanbanTaskStatus[] = [
|
||||
KanbanTaskStatus.TODO,
|
||||
KanbanTaskStatus.READY,
|
||||
KanbanTaskStatus.IN_PROGRESS,
|
||||
KanbanTaskStatus.IN_REVIEW,
|
||||
KanbanTaskStatus.DONE,
|
||||
KanbanTaskStatus.BLOCKED,
|
||||
]
|
||||
|
||||
export function AssetLinkedTasksDialog({
|
||||
teamId,
|
||||
assetId,
|
||||
assetName,
|
||||
isOpen,
|
||||
onClose,
|
||||
}: AssetLinkedTasksDialogProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [editingTaskId, setEditingTaskId] = useState<string | null>(null)
|
||||
const [isLinkSelectorOpen, setIsLinkSelectorOpen] = useState(false)
|
||||
const [selectedStatus, setSelectedStatus] = useState<KanbanTaskStatus>(KanbanTaskStatus.TODO)
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
|
||||
// 1. Fetch tasks currently linked to this asset
|
||||
const { data: linkedTasksData, isLoading: isLoadingLinked } = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'assets', assetId, 'tasks'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.assets[':assetId'].tasks.$get({
|
||||
param: { teamId, assetId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch linked tasks')
|
||||
return (await res.json()) as { data: KanbanTaskInfo[]; total: number }
|
||||
},
|
||||
enabled: !!teamId && !!assetId && isOpen,
|
||||
})
|
||||
|
||||
const linkedTasks = linkedTasksData?.data || []
|
||||
const linkedTaskIds = useMemo(() => new Set(linkedTasks.map((t) => t.id)), [linkedTasks])
|
||||
|
||||
// 2. Fetch tasks for link picker
|
||||
const { data: statusTasksData, isLoading: isLoadingStatusTasks } = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'tasks', 'status', selectedStatus],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks.$get({
|
||||
param: { teamId },
|
||||
query: { status: selectedStatus, first: '100' },
|
||||
})
|
||||
if (!res.ok) return { data: [] }
|
||||
return (await res.json()) as { data: KanbanTaskInfo[] }
|
||||
},
|
||||
enabled: !!teamId && isLinkSelectorOpen && isOpen,
|
||||
})
|
||||
|
||||
const availableTasks = statusTasksData?.data || []
|
||||
const filteredAvailableTasks = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
return availableTasks.filter((t) => {
|
||||
if (linkedTaskIds.has(t.id)) return false
|
||||
if (!query) return true
|
||||
return t.title.toLowerCase().includes(query)
|
||||
})
|
||||
}, [availableTasks, linkedTaskIds, searchQuery])
|
||||
|
||||
// 3. Mutations
|
||||
const linkTaskMutation = useMutation({
|
||||
mutationFn: async (taskId: string) => {
|
||||
const res = await client.api.teams[':teamId'].kanban.assets[':assetId'].tasks.$post({
|
||||
param: { teamId, assetId },
|
||||
json: { taskId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to link task')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'kanban', 'assets', assetId, 'tasks'],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'kanban'],
|
||||
})
|
||||
toast.success(m.asset_linked())
|
||||
},
|
||||
})
|
||||
|
||||
const unlinkTaskMutation = useMutation({
|
||||
mutationFn: async (taskId: string) => {
|
||||
const res = await client.api.teams[':teamId'].kanban.assets[':assetId'].tasks[
|
||||
':taskId'
|
||||
].$delete({
|
||||
param: { teamId, assetId, taskId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to unlink task')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'kanban', 'assets', assetId, 'tasks'],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'kanban'],
|
||||
})
|
||||
toast.success(m.asset_unlinked())
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-2xl flex flex-col h-[520px] p-0 overflow-hidden">
|
||||
{/* Header */}
|
||||
<DialogHeader className="p-4 border-b flex flex-row items-center justify-between space-y-0 shrink-0">
|
||||
<div className="flex items-center gap-2 min-w-0 pr-4">
|
||||
<SquareKanban className="w-5 h-5 text-primary shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<DialogTitle className="text-sm font-semibold truncate">
|
||||
{m.linked_tasks()}
|
||||
</DialogTitle>
|
||||
{assetName && (
|
||||
<p className="text-xs text-muted-foreground truncate mt-0.5">{assetName}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Linked Tasks List */}
|
||||
<div className="flex-1 min-h-0 flex flex-col overflow-hidden bg-background">
|
||||
<ScrollArea className="flex-1 min-h-0 p-4 [&>div>div]:block!">
|
||||
{isLoadingLinked ? (
|
||||
<div className="flex items-center justify-center p-12">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : linkedTasks.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center p-12 text-center text-xs text-muted-foreground gap-2">
|
||||
<SquareKanban className="w-8 h-8 opacity-30" />
|
||||
<p>{m.no_linked_tasks()}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{linkedTasks.map((task) => (
|
||||
<div
|
||||
key={task.id}
|
||||
onClick={() => setEditingTaskId(task.id)}
|
||||
className="flex items-center justify-between gap-3 p-2.5 rounded-lg border border-border/60 bg-muted/20 hover:bg-muted/50 cursor-pointer transition-all hover:border-border"
|
||||
>
|
||||
{/* Left: Status, Priority, Title */}
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
{task.isAgentTask && (
|
||||
<span className="p-1 rounded bg-orange-500/15 text-orange-600 dark:text-orange-400 shrink-0">
|
||||
<Bot className="w-3.5 h-3.5" />
|
||||
</span>
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
'text-[10px] px-1.5 py-0.5 rounded border uppercase font-medium shrink-0',
|
||||
getStatusBadgeColor(task.status),
|
||||
)}
|
||||
>
|
||||
{getStatusLabel(task.status)}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'text-[10px] px-1.5 py-0.5 rounded border uppercase font-medium shrink-0',
|
||||
getPriorityBadgeColor(task.priority),
|
||||
)}
|
||||
>
|
||||
{getPriorityLabel(task.priority)}
|
||||
</span>
|
||||
<span className="text-xs font-medium text-foreground truncate flex-1">
|
||||
{task.title}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Right: Assignee & Unlink Button */}
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{task.assignee && (
|
||||
<div
|
||||
className="flex items-center gap-1 text-[11px] text-muted-foreground"
|
||||
title={task.assignee.name}
|
||||
>
|
||||
<Avatar className="w-4 h-4 text-[9px]">
|
||||
<AvatarImage src={task.assignee.image || undefined} />
|
||||
<AvatarFallback>
|
||||
{task.assignee.name.slice(0, 1).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="hidden sm:inline text-[11px] max-w-[70px] truncate">
|
||||
{task.assignee.name}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
unlinkTaskMutation.mutate(task.id)
|
||||
}}
|
||||
title={m.unlink_task()}
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Bottom Action: Link to Task Popover */}
|
||||
<div className="p-3 px-4 border-t bg-muted/10 flex items-center justify-between shrink-0">
|
||||
<Popover open={isLinkSelectorOpen} onOpenChange={setIsLinkSelectorOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="gap-1.5 text-xs h-8">
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
<span>{m.link_to_task()}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-80 sm:w-96 p-0" align="start">
|
||||
{/* Search Bar */}
|
||||
<div className="p-2 border-b">
|
||||
<div className="relative">
|
||||
<Search className="w-3.5 h-3.5 absolute left-2.5 top-2.5 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={m.search_tasks()}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-8 h-8 text-xs bg-muted/30"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Status Tabs */}
|
||||
<div className="flex border-b overflow-x-auto p-1 gap-1 bg-muted/20">
|
||||
{SELECTABLE_STATUSES.map((status) => (
|
||||
<button
|
||||
key={status}
|
||||
type="button"
|
||||
onClick={() => setSelectedStatus(status)}
|
||||
className={cn(
|
||||
'px-2 py-1 text-[11px] font-medium rounded transition-colors whitespace-nowrap',
|
||||
selectedStatus === status
|
||||
? 'bg-background shadow-xs text-foreground font-semibold'
|
||||
: 'text-muted-foreground hover:text-foreground hover:bg-muted/50',
|
||||
)}
|
||||
>
|
||||
{getStatusLabel(status)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Task List */}
|
||||
<ScrollArea className="h-56">
|
||||
{isLoadingStatusTasks ? (
|
||||
<div className="flex items-center justify-center p-6 text-xs text-muted-foreground">
|
||||
<Loader2 className="w-4 h-4 animate-spin mr-1.5" />
|
||||
<span>{m.loading()}</span>
|
||||
</div>
|
||||
) : filteredAvailableTasks.length === 0 ? (
|
||||
<div className="p-6 text-center text-xs text-muted-foreground">
|
||||
{m.no_matching_tasks()}
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-1 space-y-0.5">
|
||||
{filteredAvailableTasks.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
linkTaskMutation.mutate(t.id)
|
||||
setIsLinkSelectorOpen(false)
|
||||
}}
|
||||
className="w-full text-left p-2 rounded hover:bg-muted/60 transition-colors flex items-center justify-between gap-2 text-xs group"
|
||||
>
|
||||
<span className="truncate flex-1 font-medium text-foreground">
|
||||
{t.title}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'text-[10px] px-1.5 py-0.5 rounded border uppercase shrink-0',
|
||||
getStatusBadgeColor(t.status),
|
||||
)}
|
||||
>
|
||||
{getStatusLabel(t.status)}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<Button variant="ghost" size="sm" onClick={onClose} className="text-xs h-8">
|
||||
{m.close()}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Task Edit Dialog when a linked task is clicked */}
|
||||
{editingTaskId && (
|
||||
<EditTaskDialog
|
||||
teamId={teamId}
|
||||
taskId={editingTaskId}
|
||||
isOpen={true}
|
||||
onClose={() => setEditingTaskId(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FolderTree } from '@/ui/components/folder-tree'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type {
|
||||
AssetInfo,
|
||||
AssetInfoPaginatedList,
|
||||
KanbanTaskAssetInfo,
|
||||
ProjectInfo,
|
||||
} from '@shumai/dtos'
|
||||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
|
||||
import { Check, File, Folder, Loader2, Plus } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
|
||||
interface AssetPickerDialogProps {
|
||||
teamId: string
|
||||
initialProjectId?: string | null
|
||||
excludeAssetIds?: string[]
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onConfirm: (selectedAssets: KanbanTaskAssetInfo[]) => void
|
||||
}
|
||||
|
||||
export function AssetPickerDialog({
|
||||
teamId,
|
||||
initialProjectId,
|
||||
excludeAssetIds = [],
|
||||
isOpen,
|
||||
onClose,
|
||||
onConfirm,
|
||||
}: AssetPickerDialogProps) {
|
||||
const [selectedProjectId, setSelectedProjectId] = useState<string>(initialProjectId || '')
|
||||
const [selectedFolder, setSelectedFolder] = useState<AssetInfo | null>(null)
|
||||
const [selectedAssets, setSelectedAssets] = useState<Map<string, KanbanTaskAssetInfo>>(new Map())
|
||||
|
||||
// Fetch all projects in the team
|
||||
const { data: projectsData, isLoading: isLoadingProjects } = useQuery({
|
||||
queryKey: ['teams', teamId, 'projects'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects.$get({
|
||||
param: { teamId },
|
||||
query: { first: '100' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch projects')
|
||||
return (await res.json()) as unknown as { data: ProjectInfo[] }
|
||||
},
|
||||
enabled: !!teamId && isOpen,
|
||||
})
|
||||
|
||||
const projects = projectsData?.data || []
|
||||
const activeProjectId = selectedProjectId || (projects[0]?.id ?? '')
|
||||
const selectedProject = projects.find((p) => p.id === activeProjectId)
|
||||
const activeFolderId = selectedFolder?.id || selectedProject?.rootFolder || ''
|
||||
const isRootFolder = activeFolderId === selectedProject?.rootFolder
|
||||
|
||||
// Fetch subfolders inside active folder with infinite pagination
|
||||
const {
|
||||
data: foldersData,
|
||||
fetchNextPage: fetchNextFolders,
|
||||
hasNextPage: hasNextFolders,
|
||||
isFetchingNextPage: isFetchingNextFolders,
|
||||
isLoading: isLoadingFolders,
|
||||
} = useInfiniteQuery<AssetInfoPaginatedList>({
|
||||
queryKey: ['folders', activeFolderId, 'children', 'folder', 'picker'],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: activeFolderId },
|
||||
query: { assetType: 'folder', after: pageParam as string, first: '20' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch folders')
|
||||
return (await res.json()) as unknown as AssetInfoPaginatedList
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
|
||||
enabled: !!activeFolderId && isOpen,
|
||||
})
|
||||
|
||||
// Fetch files inside active folder with infinite pagination
|
||||
const {
|
||||
data: filesData,
|
||||
fetchNextPage: fetchNextFiles,
|
||||
hasNextPage: hasNextFiles,
|
||||
isFetchingNextPage: isFetchingNextFiles,
|
||||
isLoading: isLoadingFiles,
|
||||
} = useInfiniteQuery<AssetInfoPaginatedList>({
|
||||
queryKey: ['folders', activeFolderId, 'children', 'file', 'picker'],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: activeFolderId },
|
||||
query: { assetType: 'file', after: pageParam as string, first: '20' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch files')
|
||||
return (await res.json()) as unknown as AssetInfoPaginatedList
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
|
||||
enabled: !!activeFolderId && isOpen,
|
||||
})
|
||||
|
||||
const { ref: loadMoreRef, inView } = useInView()
|
||||
|
||||
useEffect(() => {
|
||||
if (inView) {
|
||||
if (hasNextFolders && !isFetchingNextFolders) {
|
||||
fetchNextFolders()
|
||||
} else if (hasNextFiles && !isFetchingNextFiles) {
|
||||
fetchNextFiles()
|
||||
}
|
||||
}
|
||||
}, [
|
||||
inView,
|
||||
hasNextFolders,
|
||||
isFetchingNextFolders,
|
||||
fetchNextFolders,
|
||||
hasNextFiles,
|
||||
isFetchingNextFiles,
|
||||
fetchNextFiles,
|
||||
])
|
||||
|
||||
const isLoadingChildren = (isLoadingFolders && !foldersData) || (isLoadingFiles && !filesData)
|
||||
const isFetchingMore = isFetchingNextFolders || isFetchingNextFiles
|
||||
|
||||
const children = useMemo(() => {
|
||||
const folders = foldersData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||
const files = filesData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||
return [...folders, ...files]
|
||||
}, [foldersData, filesData])
|
||||
|
||||
const toggleSelectAsset = (asset: AssetInfo) => {
|
||||
const next = new Map(selectedAssets)
|
||||
if (next.has(asset.id)) {
|
||||
next.delete(asset.id)
|
||||
} else {
|
||||
const path = selectedProject
|
||||
? `/${[selectedProject.name, ...(asset.ancestorFolders || []).map((a) => a.name)].filter(Boolean).join('/')}`
|
||||
: '/'
|
||||
|
||||
next.set(asset.id, {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
type: asset.type as 'file' | 'folder' | 'root' | 'version_stack',
|
||||
proxyType: asset.proxyType ?? null,
|
||||
thumbnailUrl: asset.preview?.thumbnailUrl ?? null,
|
||||
path,
|
||||
creator: asset.creator
|
||||
? {
|
||||
id: asset.creator.id,
|
||||
name: asset.creator.name,
|
||||
image: asset.creator.image ?? undefined,
|
||||
}
|
||||
: null,
|
||||
sizeByte: asset.sizeByte ?? 0,
|
||||
fileCount: asset.fileCount ?? null,
|
||||
projectId: asset.projectId ?? selectedProject?.id ?? null,
|
||||
createdAt: asset.createdAt ?? new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
setSelectedAssets(next)
|
||||
}
|
||||
|
||||
const toggleSelectCurrentFolder = () => {
|
||||
if (!selectedFolder || isRootFolder) return
|
||||
const next = new Map(selectedAssets)
|
||||
if (next.has(selectedFolder.id)) {
|
||||
next.delete(selectedFolder.id)
|
||||
} else {
|
||||
const path = selectedProject
|
||||
? `/${[selectedProject.name, ...(selectedFolder.ancestorFolders || []).map((a) => a.name)].filter(Boolean).join('/')}`
|
||||
: '/'
|
||||
|
||||
next.set(selectedFolder.id, {
|
||||
id: selectedFolder.id,
|
||||
name: selectedFolder.name,
|
||||
type: 'folder',
|
||||
proxyType: null,
|
||||
thumbnailUrl: null,
|
||||
path,
|
||||
creator: selectedFolder.creator
|
||||
? {
|
||||
id: selectedFolder.creator.id,
|
||||
name: selectedFolder.creator.name,
|
||||
image: selectedFolder.creator.image ?? undefined,
|
||||
}
|
||||
: null,
|
||||
sizeByte: selectedFolder.sizeByte ?? 0,
|
||||
fileCount: selectedFolder.fileCount ?? null,
|
||||
projectId: selectedFolder.projectId ?? selectedProject?.id ?? null,
|
||||
createdAt: selectedFolder.createdAt ?? new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
setSelectedAssets(next)
|
||||
}
|
||||
|
||||
const handleConfirm = () => {
|
||||
onConfirm(Array.from(selectedAssets.values()))
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={isOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onClose()
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-4xl flex flex-col h-[650px] p-0 overflow-hidden gap-1">
|
||||
<DialogHeader className="px-4 py-3 border-b shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<Folder className="w-5 h-5 text-primary" />
|
||||
<DialogTitle>{m.select_assets()}</DialogTitle>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Second Row Toolbar: Project Selector with Hint Text */}
|
||||
<div className="flex items-center gap-2.5 px-4 py-1.5 border-b bg-transparent shrink-0">
|
||||
<span className="text-xs font-medium text-muted-foreground whitespace-nowrap">
|
||||
{m.current_project_label()}:
|
||||
</span>
|
||||
<div className="w-64">
|
||||
<Select
|
||||
value={activeProjectId}
|
||||
onValueChange={(val) => {
|
||||
setSelectedProjectId(val)
|
||||
setSelectedFolder(null)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="h-8 text-xs bg-background">
|
||||
<SelectValue placeholder={m.select_project()} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{projects.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id} className="text-xs">
|
||||
{p.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main 2-Pane Content */}
|
||||
<div className="flex-1 min-h-0 flex overflow-hidden">
|
||||
{/* Left Pane: Folder Tree */}
|
||||
<div className="w-1/3 min-h-0 border-r bg-sidebar/30 flex flex-col overflow-hidden">
|
||||
<ScrollArea className="flex-1 min-h-0 [&>div>div]:block!">
|
||||
{selectedProject && selectedProject.rootFolder ? (
|
||||
<div className="p-2">
|
||||
<FolderTree
|
||||
teamId={teamId}
|
||||
projectId={selectedProject.id}
|
||||
projectName={selectedProject.name}
|
||||
rootFolderId={selectedProject.rootFolder}
|
||||
onSelect={(folder) => setSelectedFolder(folder)}
|
||||
selectedFolderId={activeFolderId}
|
||||
hideCollections
|
||||
hideShares
|
||||
hideRecentlyDeleted
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full p-6 text-xs text-muted-foreground">
|
||||
{isLoadingProjects ? (
|
||||
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
m.no_project_selected()
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Right Pane: Asset List */}
|
||||
<div className="flex-1 min-h-0 flex flex-col overflow-hidden bg-background">
|
||||
{/* Top folder action / status banner */}
|
||||
<div className="p-2.5 px-4 border-b flex items-center justify-between bg-muted/20 shrink-0">
|
||||
<div className="flex items-center gap-2 text-xs font-medium truncate">
|
||||
<Folder className="w-4 h-4 text-muted-foreground shrink-0" />
|
||||
<span className="truncate">
|
||||
{selectedFolder ? selectedFolder.name : selectedProject?.name || ''}
|
||||
</span>
|
||||
{isRootFolder && (
|
||||
<span className="text-[10px] text-muted-foreground/70 bg-muted px-1.5 py-0.5 rounded">
|
||||
Root
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Select Current Folder button (disabled if root folder) */}
|
||||
{!isRootFolder && selectedFolder && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant={selectedAssets.has(selectedFolder.id) ? 'secondary' : 'outline'}
|
||||
className="h-7 text-xs gap-1.5"
|
||||
onClick={toggleSelectCurrentFolder}
|
||||
disabled={excludeAssetIds.includes(selectedFolder.id)}
|
||||
>
|
||||
{selectedAssets.has(selectedFolder.id) ? (
|
||||
<>
|
||||
<Check className="w-3.5 h-3.5 text-primary" />
|
||||
{m.saved()}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
{m.select_current_folder()}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* List of files & folders inside current directory */}
|
||||
<ScrollArea className="flex-1 min-h-0 [&>div>div]:block!">
|
||||
{isLoadingChildren ? (
|
||||
<div className="flex items-center justify-center p-12">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : children.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center p-12 text-center text-xs text-muted-foreground gap-2">
|
||||
<Folder className="w-8 h-8 opacity-30" />
|
||||
<p>{m.no_assets_in_folder()}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-border/40">
|
||||
{children.map((asset) => {
|
||||
const isExcluded = excludeAssetIds.includes(asset.id)
|
||||
const isSelected = selectedAssets.has(asset.id)
|
||||
const isFolder = asset.type === 'folder'
|
||||
|
||||
return (
|
||||
<div
|
||||
key={asset.id}
|
||||
onClick={() => {
|
||||
if (!isExcluded) toggleSelectAsset(asset)
|
||||
}}
|
||||
className={`flex items-center gap-3 px-4 py-2.5 hover:bg-muted/40 cursor-pointer transition-colors ${
|
||||
isSelected ? 'bg-primary/5' : ''
|
||||
} ${isExcluded ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
>
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
disabled={isExcluded}
|
||||
onCheckedChange={() => {
|
||||
if (!isExcluded) toggleSelectAsset(asset)
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
|
||||
{/* Thumbnail / Icon */}
|
||||
<div className="w-9 h-9 rounded bg-muted/60 border shrink-0 flex items-center justify-center overflow-hidden">
|
||||
{asset.preview?.thumbnailUrl ? (
|
||||
<img
|
||||
src={asset.preview.thumbnailUrl}
|
||||
alt={asset.name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : isFolder ? (
|
||||
<Folder className="w-5 h-5 text-primary fill-primary/20" />
|
||||
) : (
|
||||
<File className="w-5 h-5 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Details */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium truncate text-foreground">
|
||||
{asset.name}
|
||||
</p>
|
||||
<p className="text-[11px] text-muted-foreground truncate">
|
||||
{isFolder
|
||||
? `${asset.fileCount ?? 0} items`
|
||||
: formatSize(asset.sizeByte || 0)}
|
||||
{asset.creator?.name ? ` • ${asset.creator.name}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Infinite scroll sentinel & bottom loading spinner */}
|
||||
<div ref={loadMoreRef} className="h-1" />
|
||||
{isFetchingMore && (
|
||||
<div className="flex items-center justify-center p-3">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<DialogFooter className="p-3 px-4 border-t flex items-center justify-between sm:justify-between bg-muted/10 shrink-0">
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{selectedAssets.size > 0 &&
|
||||
m.n_assets_selected({
|
||||
count: selectedAssets.size,
|
||||
})}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" onClick={onClose}>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button size="sm" onClick={handleConfirm} disabled={selectedAssets.size === 0}>
|
||||
{m.add_assets()}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Loader2, Bot } from 'lucide-react'
|
||||
import type { KanbanTaskDetail } from '@shumai/dtos'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { getStatusBadgeColor, getStatusLabel } from '../kanban-types'
|
||||
import { TaskInfoForm } from './task-info-form'
|
||||
import { TaskActivityPane } from './task-activity-pane'
|
||||
|
||||
interface EditTaskDialogProps {
|
||||
teamId: string
|
||||
taskId: string | null
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
canEdit?: boolean
|
||||
}
|
||||
|
||||
export function EditTaskDialog({
|
||||
teamId,
|
||||
taskId,
|
||||
isOpen,
|
||||
onClose,
|
||||
canEdit = true,
|
||||
}: EditTaskDialogProps) {
|
||||
const {
|
||||
data: task,
|
||||
isLoading,
|
||||
error,
|
||||
} = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'task', taskId],
|
||||
queryFn: async () => {
|
||||
if (!taskId) return null
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].$get({
|
||||
param: { teamId, taskId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch task details')
|
||||
return (await res.json()) as KanbanTaskDetail
|
||||
},
|
||||
enabled: !!teamId && !!taskId && isOpen,
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-5xl w-[95vw] h-[88vh] p-0 gap-0 flex flex-col overflow-hidden bg-background">
|
||||
<DialogHeader className="px-5 py-3 border-b border-border/70 flex flex-row items-center justify-between space-y-0 shrink-0 bg-card/80">
|
||||
<div className="flex items-center gap-2 min-w-0 pr-4">
|
||||
{task?.isAgentTask && (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-semibold bg-orange-500/15 text-orange-600 dark:text-orange-400 border border-orange-500/30 shrink-0">
|
||||
<Bot className="w-3.5 h-3.5" />
|
||||
<span>{m.task_type_agent()}</span>
|
||||
</span>
|
||||
)}
|
||||
|
||||
{task?.status && (
|
||||
<span
|
||||
className={cn(
|
||||
'px-2 py-0.5 rounded text-[11px] font-medium border uppercase shrink-0',
|
||||
getStatusBadgeColor(task.status),
|
||||
)}
|
||||
>
|
||||
{getStatusLabel(task.status)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<DialogTitle className="text-sm font-semibold truncate text-foreground">
|
||||
{task?.title || m.edit_task()}
|
||||
</DialogTitle>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* 2-Columns Body: Left 2/3, Right 1/3 */}
|
||||
<div className="flex-1 flex flex-col md:flex-row overflow-hidden">
|
||||
{isLoading ? (
|
||||
<div className="flex-1 flex items-center justify-center p-12">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : error || !task ? (
|
||||
<div className="flex-1 flex items-center justify-center p-12 text-xs text-muted-foreground">
|
||||
{m.file_not_found()}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Left Column (2/3 width) */}
|
||||
<div className="flex-1 md:w-2/3 h-full overflow-hidden flex flex-col">
|
||||
<TaskInfoForm teamId={teamId} task={task} canEdit={canEdit} />
|
||||
</div>
|
||||
|
||||
{/* Right Column (1/3 width) */}
|
||||
<div className="md:w-1/3 h-full overflow-hidden flex flex-col">
|
||||
<TaskActivityPane teamId={teamId} task={task} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useState } from 'react'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { TaskCommentThread } from './task-comment-thread'
|
||||
import { TaskEventTimeline } from './task-event-timeline'
|
||||
import type { KanbanTaskDetail } from '@shumai/dtos'
|
||||
|
||||
interface TaskActivityPaneProps {
|
||||
teamId: string
|
||||
task: KanbanTaskDetail
|
||||
}
|
||||
|
||||
export function TaskActivityPane({ teamId, task }: TaskActivityPaneProps) {
|
||||
const [activeTab, setActiveTab] = useState<'comments' | 'activity'>('comments')
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full bg-sidebar/30 border-l border-border/60 overflow-hidden">
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={(val) => setActiveTab(val as 'comments' | 'activity')}
|
||||
className="flex flex-col h-full"
|
||||
>
|
||||
<div className="px-3 pt-2.5 pb-1 border-b border-border/60 bg-card/50 shrink-0">
|
||||
<TabsList className="w-full grid grid-cols-2 h-8 bg-muted/60">
|
||||
<TabsTrigger value="comments" className="text-xs h-7">
|
||||
<span>{m.comments()}</span>
|
||||
{task.comments.length > 0 && (
|
||||
<span className="text-[10px] font-mono text-muted-foreground ml-1">
|
||||
({task.comments.length})
|
||||
</span>
|
||||
)}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="activity" className="text-xs h-7">
|
||||
<span>{m.activity()}</span>
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<TabsContent
|
||||
value="comments"
|
||||
className="h-full m-0 data-[state=active]:flex data-[state=active]:flex-col"
|
||||
>
|
||||
<TaskCommentThread teamId={teamId} taskId={task.id} initialComments={task.comments} />
|
||||
</TabsContent>
|
||||
<TabsContent value="activity" className="h-full m-0 data-[state=active]:block">
|
||||
<TaskEventTimeline teamId={teamId} taskId={task.id} initialEvents={task.events} />
|
||||
</TabsContent>
|
||||
</div>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import React, { useState } from 'react'
|
||||
import { format } from 'date-fns'
|
||||
import Markdown from 'react-markdown'
|
||||
import { Download, FileText, MoreHorizontal, Trash2 } from 'lucide-react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { toast } from 'sonner'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import type { KanbanAttachmentInfo, KanbanCommentInfo } from '@shumai/dtos'
|
||||
|
||||
interface TaskCommentCardProps {
|
||||
teamId: string
|
||||
taskId: string
|
||||
comment: KanbanCommentInfo
|
||||
currentUserId?: string
|
||||
isOwnerOrAdmin?: boolean
|
||||
onViewAttachment?: (attachment: KanbanAttachmentInfo) => void
|
||||
}
|
||||
|
||||
export function TaskCommentCard({
|
||||
teamId,
|
||||
taskId,
|
||||
comment,
|
||||
currentUserId,
|
||||
isOwnerOrAdmin,
|
||||
onViewAttachment,
|
||||
}: TaskCommentCardProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
|
||||
const canDelete = isOwnerOrAdmin || comment.author.id === currentUserId
|
||||
|
||||
const { mutate: deleteComment, isPending: isDeleting } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].comments[
|
||||
':commentId'
|
||||
].$delete({
|
||||
param: { teamId, taskId, commentId: comment.id },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: m.error() }))
|
||||
throw new Error((err as { message?: string }).message || m.error())
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'kanban', 'tasks', taskId, 'comments'],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'kanban', 'task', taskId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'kanban', 'tasks'],
|
||||
})
|
||||
toast.success('Comment deleted')
|
||||
setIsDeleteDialogOpen(false)
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const authorInitials = (comment.author.name || 'U')
|
||||
.split(' ')
|
||||
.map((n) => n[0])
|
||||
.slice(0, 2)
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
|
||||
return (
|
||||
<div className="relative flex gap-3 p-3 rounded-xl border border-transparent bg-foreground/[0.03] dark:bg-foreground/[0.08] hover:bg-foreground/[0.06] dark:hover:bg-foreground/[0.12] transition-colors group">
|
||||
{/* Left Avatar */}
|
||||
<Avatar className="w-7 h-7 shrink-0 mt-0.5 border border-border">
|
||||
{comment.author.image && (
|
||||
<AvatarImage src={comment.author.image} alt={comment.author.name} />
|
||||
)}
|
||||
<AvatarFallback className="text-[10px] font-medium bg-muted text-muted-foreground">
|
||||
{authorInitials}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 min-w-0 space-y-1.5">
|
||||
{/* Header: Author + Timestamp + Actions */}
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="font-semibold text-xs text-foreground truncate">
|
||||
{comment.author.name}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground shrink-0 font-mono">
|
||||
{format(new Date(comment.createdAt), 'MMM d, h:mm a')}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{canDelete && (
|
||||
<div className="opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="icon-xs" variant="ghost" className="h-5 w-5 text-muted-foreground">
|
||||
<MoreHorizontal className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive cursor-pointer text-xs"
|
||||
onClick={() => setIsDeleteDialogOpen(true)}
|
||||
>
|
||||
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
|
||||
<span>{m.delete()}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Markdown Comment Body */}
|
||||
{comment.body && (
|
||||
<div className="text-xs leading-relaxed prose prose-xs dark:prose-invert max-w-none break-words text-foreground/90 font-sans">
|
||||
<Markdown>{comment.body}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Attachments Section */}
|
||||
{comment.attachments && comment.attachments.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 pt-1.5">
|
||||
{comment.attachments.map((att) => {
|
||||
const isImage = att.proxyType === 'image' || att.contentType?.startsWith('image/')
|
||||
return (
|
||||
<div
|
||||
key={att.id}
|
||||
className="relative group/att rounded-lg border border-border bg-card overflow-hidden transition-all duration-200"
|
||||
>
|
||||
{isImage ? (
|
||||
<div
|
||||
className="w-40 h-28 relative cursor-pointer overflow-hidden bg-muted/40"
|
||||
onClick={() => onViewAttachment?.(att)}
|
||||
>
|
||||
<img
|
||||
src={att.url}
|
||||
alt={att.name}
|
||||
className="w-full h-full object-cover group-hover/att:scale-105 transition-transform duration-200"
|
||||
/>
|
||||
<a
|
||||
href={att.url}
|
||||
download={att.name}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="absolute right-1.5 bottom-1.5 bg-black/60 hover:bg-black/80 text-white p-1 rounded-md opacity-0 group-hover/att:opacity-100 transition-opacity shadow-xs"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
title="Download"
|
||||
>
|
||||
<Download className="w-3.5 h-3.5" />
|
||||
</a>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2.5 p-2.5 max-w-[240px] bg-card hover:bg-muted/40 transition-colors">
|
||||
<FileText className="w-7 h-7 text-primary/80 shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p
|
||||
className="text-xs font-medium text-foreground truncate"
|
||||
title={att.name}
|
||||
>
|
||||
{att.name}
|
||||
</p>
|
||||
<p className="text-[10px] text-muted-foreground font-mono">
|
||||
{formatSize(att.sizeByte)}
|
||||
</p>
|
||||
</div>
|
||||
<a
|
||||
href={att.url}
|
||||
download={att.name}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="p-1 text-muted-foreground hover:text-foreground shrink-0 rounded-md hover:bg-muted transition-colors"
|
||||
title="Download"
|
||||
>
|
||||
<Download className="w-3.5 h-3.5" />
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Delete Confirmation Alert Dialog */}
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{m.delete_comment_confirm()}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{m.delete_comment_description()}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isDeleting}>{m.cancel()}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive hover:bg-destructive/90 text-white"
|
||||
disabled={isDeleting}
|
||||
onClick={() => deleteComment()}
|
||||
>
|
||||
{m.delete()}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
import React, { useState, useRef, useEffect } from 'react'
|
||||
import { Paperclip, ArrowUp, X, Loader2, FileText, Image as ImageIcon } from 'lucide-react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { toast } from 'sonner'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import { useMemberStore, type MemberInfo } from '@/ui/stores/members'
|
||||
import type {
|
||||
KanbanAttachmentPayload,
|
||||
PostAttachmentRequest,
|
||||
PostKanbanAttachmentResponse,
|
||||
} from '@shumai/dtos'
|
||||
|
||||
interface UploadingFile {
|
||||
id: string
|
||||
file: File
|
||||
isUploading: boolean
|
||||
payload?: KanbanAttachmentPayload
|
||||
error?: string
|
||||
}
|
||||
|
||||
interface TaskCommentInputProps {
|
||||
teamId: string
|
||||
onSendMessage: (text: string, attachments?: KanbanAttachmentPayload[]) => Promise<void> | void
|
||||
isSubmitting?: boolean
|
||||
}
|
||||
|
||||
export function TaskCommentInput({ teamId, onSendMessage, isSubmitting }: TaskCommentInputProps) {
|
||||
const [text, setText] = useState('')
|
||||
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([])
|
||||
const [showMentionList, setShowMentionList] = useState(false)
|
||||
const [mentionQuery, setMentionQuery] = useState('')
|
||||
const [highlightedIndex, setHighlightedIndex] = useState(0)
|
||||
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const mentionListRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const { members, fetchMembers } = useMemberStore()
|
||||
|
||||
useEffect(() => {
|
||||
if (teamId) {
|
||||
fetchMembers(teamId, true, true)
|
||||
}
|
||||
}, [teamId, fetchMembers])
|
||||
|
||||
const { mutateAsync: getUploadUrl } = useMutation({
|
||||
mutationFn: async (data: PostAttachmentRequest) => {
|
||||
const res = await client.api.teams[':teamId'].kanban.attachments.$post({
|
||||
param: { teamId },
|
||||
json: data,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to get attachment upload url')
|
||||
return (await res.json()) as PostKanbanAttachmentResponse
|
||||
},
|
||||
})
|
||||
|
||||
// Auto-resize textarea
|
||||
const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const val = e.target.value
|
||||
setText(val)
|
||||
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto'
|
||||
textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 160)}px`
|
||||
}
|
||||
|
||||
// Mention detection
|
||||
const cursorPos = e.target.selectionStart || 0
|
||||
const textBeforeCursor = val.slice(0, cursorPos)
|
||||
const lastAtPos = textBeforeCursor.lastIndexOf('@')
|
||||
|
||||
if (lastAtPos !== -1) {
|
||||
const isStartOfLine = lastAtPos === 0
|
||||
const charBeforeAt = textBeforeCursor[lastAtPos - 1]
|
||||
const hasSpaceBefore = isStartOfLine || /\s/.test(charBeforeAt)
|
||||
|
||||
if (hasSpaceBefore) {
|
||||
const query = textBeforeCursor.slice(lastAtPos + 1)
|
||||
if (!/\s/.test(query)) {
|
||||
setMentionQuery(query)
|
||||
setShowMentionList(true)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setShowMentionList(false)
|
||||
}
|
||||
|
||||
const filteredMembers = members.filter((m) =>
|
||||
m.name?.toLowerCase().includes(mentionQuery.toLowerCase()),
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
setHighlightedIndex(0)
|
||||
}, [mentionQuery, showMentionList])
|
||||
|
||||
const handleSelectMention = (member: MemberInfo) => {
|
||||
if (!textareaRef.current) return
|
||||
const cursorPos = textareaRef.current.selectionStart || 0
|
||||
const textBeforeCursor = text.slice(0, cursorPos)
|
||||
const textAfterCursor = text.slice(cursorPos)
|
||||
const lastAtPos = textBeforeCursor.lastIndexOf('@')
|
||||
|
||||
if (lastAtPos !== -1) {
|
||||
const newText = `${text.slice(0, lastAtPos)}@${member.name} ${textAfterCursor}`
|
||||
setText(newText)
|
||||
setShowMentionList(false)
|
||||
setTimeout(() => {
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.focus()
|
||||
const newCursorPos = lastAtPos + member.name.length + 2
|
||||
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
|
||||
}
|
||||
}, 0)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files || [])
|
||||
if (files.length === 0) return
|
||||
|
||||
const newUploading: UploadingFile[] = files.map((file) => ({
|
||||
id: `${Date.now()}-${file.name}-${Math.random()}`,
|
||||
file,
|
||||
isUploading: true,
|
||||
}))
|
||||
|
||||
setUploadingFiles((prev) => [...prev, ...newUploading])
|
||||
|
||||
for (const uf of newUploading) {
|
||||
try {
|
||||
const res = await getUploadUrl({
|
||||
fileName: uf.file.name,
|
||||
size: uf.file.size,
|
||||
contentType: uf.file.type || 'application/octet-stream',
|
||||
})
|
||||
|
||||
// Direct upload to S3
|
||||
const uploadRes = await fetch(res.uploadUrl, {
|
||||
method: 'PUT',
|
||||
body: uf.file,
|
||||
headers: {
|
||||
'Content-Type': uf.file.type || 'application/octet-stream',
|
||||
},
|
||||
})
|
||||
|
||||
if (!uploadRes.ok) {
|
||||
throw new Error('Failed to upload file to storage')
|
||||
}
|
||||
|
||||
setUploadingFiles((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === uf.id
|
||||
? {
|
||||
...item,
|
||||
isUploading: false,
|
||||
payload: {
|
||||
id: res.id,
|
||||
name: res.name,
|
||||
key: res.key,
|
||||
sizeByte: res.sizeByte,
|
||||
contentType: res.contentType,
|
||||
proxyType: res.proxyType,
|
||||
},
|
||||
}
|
||||
: item,
|
||||
),
|
||||
)
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Upload failed'
|
||||
toast.error(`${uf.file.name}: ${message}`)
|
||||
setUploadingFiles((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === uf.id ? { ...item, isUploading: false, error: message } : item,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const removeFile = (id: string) => {
|
||||
setUploadingFiles((prev) => prev.filter((f) => f.id !== id))
|
||||
}
|
||||
|
||||
const isUploadingAny = uploadingFiles.some((f) => f.isUploading)
|
||||
const successfulAttachments = uploadingFiles
|
||||
.map((f) => f.payload)
|
||||
.filter((p): p is KanbanAttachmentPayload => !!p)
|
||||
|
||||
const canSend = (text.trim().length > 0 || successfulAttachments.length > 0) && !isUploadingAny
|
||||
|
||||
const handleSend = async () => {
|
||||
if (!canSend || isSubmitting) return
|
||||
|
||||
try {
|
||||
await onSendMessage(
|
||||
text.trim(),
|
||||
successfulAttachments.length > 0 ? successfulAttachments : undefined,
|
||||
)
|
||||
setText('')
|
||||
setUploadingFiles([])
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto'
|
||||
}
|
||||
} catch {
|
||||
// Error handled by parent
|
||||
}
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (showMentionList && filteredMembers.length > 0) {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
setHighlightedIndex((prev) => (prev + 1) % filteredMembers.length)
|
||||
return
|
||||
}
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
setHighlightedIndex((prev) => (prev - 1 + filteredMembers.length) % filteredMembers.length)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Enter' || e.key === 'Tab') {
|
||||
e.preventDefault()
|
||||
const selected = filteredMembers[highlightedIndex]
|
||||
if (selected) handleSelectMention(selected)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
setShowMentionList(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault()
|
||||
handleSend()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative flex flex-col w-full border border-border focus-within:border-foreground/40 bg-card rounded-2xl p-2.5 shadow-2xs transition-all">
|
||||
{/* Mention Popup */}
|
||||
{showMentionList && filteredMembers.length > 0 && (
|
||||
<div
|
||||
ref={mentionListRef}
|
||||
className="absolute bottom-full left-0 mb-2 w-64 max-h-48 overflow-y-auto rounded-xl border border-border bg-popover p-1 shadow-lg z-50"
|
||||
>
|
||||
{filteredMembers.map((member, idx) => (
|
||||
<button
|
||||
key={member.id}
|
||||
type="button"
|
||||
onClick={() => handleSelectMention(member)}
|
||||
className={`w-full flex items-center gap-2 px-2.5 py-1.5 rounded-lg text-xs transition-colors text-left ${
|
||||
idx === highlightedIndex
|
||||
? 'bg-primary text-primary-foreground font-medium'
|
||||
: 'hover:bg-muted text-foreground'
|
||||
}`}
|
||||
>
|
||||
<Avatar className="w-5 h-5">
|
||||
{member.image && <AvatarImage src={member.image} />}
|
||||
<AvatarFallback className="text-[9px]">
|
||||
{member.name?.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="truncate">{member.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Uploading / Attached Files Preview */}
|
||||
{uploadingFiles.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5 pb-2 mb-1.5 border-b border-border/50">
|
||||
{uploadingFiles.map((uf) => {
|
||||
const isImage = uf.file.type.startsWith('image/')
|
||||
return (
|
||||
<div
|
||||
key={uf.id}
|
||||
className="flex items-center gap-1.5 pl-2 pr-1.5 py-1 rounded-lg bg-muted/60 border border-border text-xs max-w-[200px]"
|
||||
>
|
||||
{uf.isUploading ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin text-primary shrink-0" />
|
||||
) : isImage ? (
|
||||
<ImageIcon className="w-3.5 h-3.5 text-primary shrink-0" />
|
||||
) : (
|
||||
<FileText className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
|
||||
)}
|
||||
<div className="min-w-0 flex-1 truncate">
|
||||
<span className="truncate block font-medium text-[11px]">{uf.file.name}</span>
|
||||
<span className="text-[9px] text-muted-foreground font-mono">
|
||||
{formatSize(uf.file.size)}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeFile(uf.id)}
|
||||
className="p-0.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted shrink-0"
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Text Area */}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={text}
|
||||
onChange={handleTextChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={m.comment_placeholder()}
|
||||
rows={1}
|
||||
className="w-full min-h-[44px] max-h-[160px] bg-transparent border-0 focus:outline-hidden focus-visible:ring-0 resize-none text-xs text-foreground placeholder:text-muted-foreground/70 p-1 font-sans leading-relaxed"
|
||||
/>
|
||||
|
||||
{/* Footer Controls: Attachment Button + Send Button */}
|
||||
<div className="flex items-center justify-between pt-1 mt-1 border-t border-border/40">
|
||||
<div className="flex items-center gap-1">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="h-7 w-7 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted"
|
||||
title="Attach files"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<Paperclip className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<span className="text-[10px] text-muted-foreground/60 hidden sm:inline pl-1">
|
||||
Cmd+Enter to send
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
onClick={handleSend}
|
||||
disabled={!canSend || isSubmitting}
|
||||
className="h-7 w-7 rounded-full shadow-xs bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-40 transition-all shrink-0"
|
||||
title="Send comment"
|
||||
>
|
||||
{isSubmitting || isUploadingAny ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
<ArrowUp className="w-3.5 h-3.5 stroke-[2.5]" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { toast } from 'sonner'
|
||||
import { Loader2, MessageSquare, X } from 'lucide-react'
|
||||
import { TaskCommentCard } from './task-comment-card'
|
||||
import { TaskCommentInput } from './task-comment-input'
|
||||
import type { KanbanAttachmentInfo, KanbanAttachmentPayload, KanbanCommentInfo } from '@shumai/dtos'
|
||||
|
||||
interface TaskCommentThreadProps {
|
||||
teamId: string
|
||||
taskId: string
|
||||
initialComments?: KanbanCommentInfo[]
|
||||
}
|
||||
|
||||
export function TaskCommentThread({ teamId, taskId, initialComments }: TaskCommentThreadProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [viewingAttachment, setViewingAttachment] = useState<KanbanAttachmentInfo | null>(null)
|
||||
|
||||
// Query Current User Info
|
||||
const { data: me } = useQuery({
|
||||
queryKey: ['teams', teamId, 'me'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].me.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch me')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
const isOwnerOrAdmin = me?.role?.toLowerCase() === 'owner' || me?.role?.toLowerCase() === 'editor'
|
||||
|
||||
// Query Comments
|
||||
const { data: commentsData, isLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'tasks', taskId, 'comments'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].comments.$get({
|
||||
param: { teamId, taskId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch comments')
|
||||
return (await res.json()) as { data: KanbanCommentInfo[] }
|
||||
},
|
||||
initialData: initialComments ? { data: initialComments } : undefined,
|
||||
enabled: !!teamId && !!taskId,
|
||||
refetchInterval: 4000,
|
||||
})
|
||||
|
||||
const comments = commentsData?.data || []
|
||||
|
||||
// Add Comment Mutation
|
||||
const { mutateAsync: addComment, isPending: isAdding } = useMutation({
|
||||
mutationFn: async ({
|
||||
body,
|
||||
attachments,
|
||||
}: {
|
||||
body: string
|
||||
attachments?: KanbanAttachmentPayload[]
|
||||
}) => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].comments.$post({
|
||||
param: { teamId, taskId },
|
||||
json: { body, attachments },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: m.error() }))
|
||||
throw new Error((err as { message?: string }).message || m.error())
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'kanban', 'tasks', taskId, 'comments'],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'kanban', 'task', taskId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'kanban', 'tasks'],
|
||||
})
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const handleSendMessage = async (text: string, attachments?: KanbanAttachmentPayload[]) => {
|
||||
await addComment({ body: text, attachments })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full overflow-hidden bg-background">
|
||||
{/* Lightbox / Full-screen Attachment Viewer */}
|
||||
{viewingAttachment && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 bg-black/90 flex flex-col items-center justify-center p-4 animate-in fade-in duration-150"
|
||||
onClick={() => setViewingAttachment(null)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setViewingAttachment(null)}
|
||||
className="absolute top-4 right-4 text-white/80 hover:text-white bg-white/10 hover:bg-white/20 rounded-full p-2 transition-colors z-50 cursor-pointer"
|
||||
title="Close"
|
||||
>
|
||||
<X className="w-6 h-6" />
|
||||
</button>
|
||||
|
||||
<div className="w-full h-full flex items-center justify-center p-2">
|
||||
<img
|
||||
src={viewingAttachment.url}
|
||||
alt={viewingAttachment.name}
|
||||
className="max-w-full max-h-[85vh] object-contain rounded-lg shadow-2xl"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Comments List */}
|
||||
<ScrollArea className="flex-1 p-3.5">
|
||||
<div className="space-y-3 pr-1 pb-2">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : comments.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-16 text-center text-xs text-muted-foreground/80 space-y-2">
|
||||
<div className="w-10 h-10 rounded-full bg-muted/60 flex items-center justify-center">
|
||||
<MessageSquare className="w-5 h-5 opacity-40" />
|
||||
</div>
|
||||
<p className="font-medium">{m.no_comments_yet()}</p>
|
||||
</div>
|
||||
) : (
|
||||
comments.map((comment) => (
|
||||
<TaskCommentCard
|
||||
key={comment.id}
|
||||
teamId={teamId}
|
||||
taskId={taskId}
|
||||
comment={comment}
|
||||
currentUserId={me?.id}
|
||||
isOwnerOrAdmin={isOwnerOrAdmin}
|
||||
onViewAttachment={(att) => setViewingAttachment(att)}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
{/* Composer Input Box */}
|
||||
<div className="p-3 border-t border-border/60 bg-card/60 shrink-0">
|
||||
<TaskCommentInput
|
||||
teamId={teamId}
|
||||
onSendMessage={handleSendMessage}
|
||||
isSubmitting={isAdding}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { KanbanTaskEventType, type KanbanEventInfo } from '@shumai/dtos'
|
||||
import { getStatusLabel } from '../kanban-types'
|
||||
import { format } from 'date-fns'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
|
||||
interface TaskEventTimelineProps {
|
||||
teamId: string
|
||||
taskId: string
|
||||
initialEvents?: KanbanEventInfo[]
|
||||
}
|
||||
|
||||
function getEventDescription(event: KanbanEventInfo): string {
|
||||
const data = event.data || {}
|
||||
switch (event.type) {
|
||||
case KanbanTaskEventType.CREATED:
|
||||
return 'Created task'
|
||||
case KanbanTaskEventType.STATUS_CHANGED:
|
||||
return `Changed status from ${event.fromStatus ? getStatusLabel(event.fromStatus) : 'None'} to ${event.toStatus ? getStatusLabel(event.toStatus) : 'None'}`
|
||||
case KanbanTaskEventType.ASSIGNED:
|
||||
return 'Assigned task'
|
||||
case KanbanTaskEventType.UNASSIGNED:
|
||||
return 'Unassigned task'
|
||||
case KanbanTaskEventType.PRIORITY_CHANGED:
|
||||
return `Changed priority to ${String(data.to || '')}`
|
||||
case KanbanTaskEventType.GOAL_CHANGED:
|
||||
return 'Updated goal association'
|
||||
case KanbanTaskEventType.DEPENDENCY_ADDED:
|
||||
return 'Added prerequisite dependency'
|
||||
case KanbanTaskEventType.DEPENDENCY_REMOVED:
|
||||
return 'Removed prerequisite dependency'
|
||||
case KanbanTaskEventType.CHANGES_REQUESTED:
|
||||
return `Requested changes: "${String(data.reason || '')}"`
|
||||
case KanbanTaskEventType.BLOCKED:
|
||||
return `Task blocked: "${String(data.reason || data.blockReason || '')}"`
|
||||
case KanbanTaskEventType.UNBLOCKED:
|
||||
return 'Task unblocked'
|
||||
case KanbanTaskEventType.COMMENTED:
|
||||
return 'Added a comment'
|
||||
default:
|
||||
return event.type
|
||||
}
|
||||
}
|
||||
|
||||
export function TaskEventTimeline({ teamId, taskId, initialEvents }: TaskEventTimelineProps) {
|
||||
const { data: eventsData, isLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'tasks', taskId, 'events'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].events.$get({
|
||||
param: { teamId, taskId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch events')
|
||||
return (await res.json()) as { data: KanbanEventInfo[] }
|
||||
},
|
||||
initialData: initialEvents ? { data: initialEvents } : undefined,
|
||||
enabled: !!teamId && !!taskId,
|
||||
})
|
||||
|
||||
const events = eventsData?.data || []
|
||||
|
||||
return (
|
||||
<ScrollArea className="h-full p-3">
|
||||
<div className="space-y-4 pr-2">
|
||||
{/* Audit Event Stream */}
|
||||
<div className="space-y-2">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-6">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : events.length === 0 ? (
|
||||
<div className="py-6 text-center text-xs text-muted-foreground">
|
||||
{m.no_activity_yet()}
|
||||
</div>
|
||||
) : (
|
||||
<div className="relative pl-4 space-y-3 before:absolute before:left-1.5 before:top-2 before:bottom-2 before:w-0.5 before:bg-border/60">
|
||||
{events.map((event) => (
|
||||
<div key={event.id} className="relative flex items-start gap-2 text-xs">
|
||||
<div className="absolute -left-4 top-1 w-2.5 h-2.5 rounded-full bg-background border-2 border-primary shrink-0" />
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between gap-1">
|
||||
<span className="font-medium text-foreground truncate">
|
||||
{event.actor?.name || 'System'}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground font-mono shrink-0">
|
||||
{format(new Date(event.createdAt), 'MM/dd HH:mm')}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground leading-snug mt-0.5">
|
||||
{getEventDescription(event)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,469 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Textarea } from '@/ui/components/ui/textarea'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { DateTimePicker } from '@/ui/components/datetime-picker'
|
||||
import { toast } from 'sonner'
|
||||
import {
|
||||
KanbanTaskPriority,
|
||||
type KanbanTaskDetail,
|
||||
type KanbanGoalInfo,
|
||||
type AgentInfo,
|
||||
type KanbanTaskAssetInfo,
|
||||
type UpdateKanbanTaskRequest,
|
||||
UNASSIGNED_GOAL_ID,
|
||||
} from '@shumai/dtos'
|
||||
import { getPriorityBadgeColor, getPriorityLabel } from '../kanban-types'
|
||||
import { TaskParentSelector } from '../task-parent-selector'
|
||||
import { TaskRelatedAssets } from '../task-related-assets'
|
||||
import { TaskTargetFolderDialog } from './task-target-folder-dialog'
|
||||
import { Bot, Folder, Target, Loader2 } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
|
||||
interface TaskInfoFormProps {
|
||||
teamId: string
|
||||
task: KanbanTaskDetail
|
||||
canEdit?: boolean
|
||||
}
|
||||
|
||||
export function TaskInfoForm({ teamId, task, canEdit = true }: TaskInfoFormProps) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// Local state for debounced text inputs
|
||||
const [title, setTitle] = useState(task.title)
|
||||
const [description, setDescription] = useState(task.description || '')
|
||||
const [isFolderPickerOpen, setIsFolderPickerOpen] = useState(false)
|
||||
const [targetFolderName, setTargetFolderName] = useState<string | null>(null)
|
||||
|
||||
const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
// Sync with prop changes if task id changed
|
||||
useEffect(() => {
|
||||
setTitle(task.title)
|
||||
setDescription(task.description || '')
|
||||
}, [task.id, task.title, task.description])
|
||||
|
||||
// Queries for selectors
|
||||
const { data: members = [] } = useQuery({
|
||||
queryKey: ['teams', teamId, 'members', 'human'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].members.$get({
|
||||
param: { teamId },
|
||||
query: { includeAgents: 'false' },
|
||||
})
|
||||
if (!res.ok) return []
|
||||
const data = await res.json()
|
||||
return Array.isArray(data) ? data : []
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
const { data: agents = [] } = useQuery({
|
||||
queryKey: ['teams', teamId, 'agents'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].agents.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) return []
|
||||
return ((await res.json()) as AgentInfo[]) || []
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
const { data: goalsData } = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'goals'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.goals.$get({
|
||||
param: { teamId },
|
||||
query: {},
|
||||
})
|
||||
if (!res.ok) return { data: [] }
|
||||
return (await res.json()) as { data: KanbanGoalInfo[] }
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
const goals = goalsData?.data || []
|
||||
|
||||
// Auto-save update mutation
|
||||
const { mutate: updateTask, isPending: isUpdating } = useMutation({
|
||||
mutationFn: async (patch: UpdateKanbanTaskRequest) => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].$patch({
|
||||
param: { teamId, taskId: task.id },
|
||||
json: patch,
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: m.error() }))
|
||||
throw new Error((err as { message?: string }).message || m.error())
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'task', task.id] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'tasks'] })
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const { mutate: linkAssets } = useMutation({
|
||||
mutationFn: async (newAssets: KanbanTaskAssetInfo[]) => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].assets.$post({
|
||||
param: { teamId, taskId: task.id },
|
||||
json: { assetIds: newAssets.map((a) => a.id) },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to link assets')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'task', task.id] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'tasks'] })
|
||||
toast.success(m.asset_linked())
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const { mutate: unlinkAsset } = useMutation({
|
||||
mutationFn: async (assetId: string) => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].assets[
|
||||
':assetId'
|
||||
].$delete({
|
||||
param: { teamId, taskId: task.id, assetId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to unlink asset')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'task', task.id] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'tasks'] })
|
||||
toast.success(m.asset_unlinked())
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
// Debounced auto-save handler for text fields
|
||||
const handleTextChange = (field: 'title' | 'description', value: string) => {
|
||||
if (field === 'title') setTitle(value)
|
||||
if (field === 'description') setDescription(value)
|
||||
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current)
|
||||
}
|
||||
|
||||
debounceTimerRef.current = setTimeout(() => {
|
||||
if (field === 'title' && value.trim() && value.trim() !== task.title) {
|
||||
updateTask({ title: value.trim() })
|
||||
} else if (field === 'description' && value !== (task.description || '')) {
|
||||
updateTask({ description: value.trim() || null })
|
||||
}
|
||||
}, 600)
|
||||
}
|
||||
|
||||
const isAgentic = task.isAgentTask
|
||||
|
||||
return (
|
||||
<ScrollArea className="h-full p-5">
|
||||
<div className="space-y-6 w-full pr-3">
|
||||
{/* Title Input */}
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label
|
||||
htmlFor="task-title"
|
||||
className="text-xs font-semibold text-muted-foreground uppercase tracking-wider"
|
||||
>
|
||||
{m.task_title()}
|
||||
</Label>
|
||||
{isUpdating && (
|
||||
<span className="flex items-center gap-1 text-[11px] text-muted-foreground animate-pulse">
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
{m.saving()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
id="task-title"
|
||||
value={title}
|
||||
onChange={(e) => handleTextChange('title', e.target.value)}
|
||||
disabled={!canEdit}
|
||||
className="text-base font-semibold h-10 bg-background"
|
||||
placeholder={m.task_title_placeholder()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description Textarea */}
|
||||
<div className="space-y-1.5">
|
||||
<Label
|
||||
htmlFor="task-description"
|
||||
className="text-xs font-semibold text-muted-foreground uppercase tracking-wider"
|
||||
>
|
||||
{m.task_description()}
|
||||
</Label>
|
||||
<Textarea
|
||||
id="task-description"
|
||||
value={description}
|
||||
onChange={(e) => handleTextChange('description', e.target.value)}
|
||||
disabled={!canEdit}
|
||||
rows={5}
|
||||
className="text-xs leading-relaxed bg-background"
|
||||
placeholder={m.task_description_placeholder()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Properties Grid */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 p-4 rounded-lg bg-muted/20 border border-border/60">
|
||||
{/* Row 1: Agent Task Switch (Read-Only) */}
|
||||
<div className="sm:col-span-2 flex items-center justify-between space-x-2 rounded-md border border-border/60 bg-background/50 px-3 py-2 h-14">
|
||||
<div className="space-y-0.5 min-w-0 pr-2">
|
||||
<Label className="text-xs font-medium text-muted-foreground flex items-center gap-1.5">
|
||||
<Bot className="w-3.5 h-3.5 text-orange-500" />
|
||||
<span>{m.task_type_agent()}</span>
|
||||
</Label>
|
||||
<p className="text-[11px] text-muted-foreground/80 line-clamp-1">
|
||||
{m.task_type_agent_desc()}
|
||||
</p>
|
||||
</div>
|
||||
<Switch checked={task.isAgentTask} disabled={true} />
|
||||
</div>
|
||||
|
||||
{/* Row 2: Priority Selector and Goal Selector */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">{m.task_priority()}</Label>
|
||||
<Select
|
||||
value={task.priority}
|
||||
onValueChange={(val) => updateTask({ priority: val as KanbanTaskPriority })}
|
||||
disabled={!canEdit}
|
||||
>
|
||||
<SelectTrigger className="w-full h-8 text-xs bg-background">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.values(KanbanTaskPriority).map((p) => (
|
||||
<SelectItem key={p} value={p}>
|
||||
<span
|
||||
className={cn(
|
||||
'px-1.5 py-0.5 rounded text-[10px] uppercase font-medium',
|
||||
getPriorityBadgeColor(p),
|
||||
)}
|
||||
>
|
||||
{getPriorityLabel(p)}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">{m.goals()}</Label>
|
||||
<Select
|
||||
value={task.goal?.id || 'none'}
|
||||
onValueChange={(val) => updateTask({ goalId: val === 'none' ? null : val })}
|
||||
disabled={!canEdit}
|
||||
>
|
||||
<SelectTrigger className="w-full h-8 text-xs bg-background">
|
||||
<SelectValue placeholder={m.no_folder_selected()} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">
|
||||
<span className="text-muted-foreground italic">None</span>
|
||||
</SelectItem>
|
||||
{goals
|
||||
.filter((g) => g.id !== UNASSIGNED_GOAL_ID)
|
||||
.map((g) => (
|
||||
<SelectItem key={g.id} value={g.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Target className="w-3.5 h-3.5 text-primary" />
|
||||
<span>{g.title}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Row 3: Assignee Selector and Reporter Selector */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">
|
||||
{isAgentic ? m.select_agent() : m.assignee()}
|
||||
</Label>
|
||||
<Select
|
||||
value={task.assignee?.id || 'none'}
|
||||
onValueChange={(val) => updateTask({ assigneeId: val === 'none' ? null : val })}
|
||||
disabled={!canEdit}
|
||||
>
|
||||
<SelectTrigger className="w-full h-8 text-xs bg-background">
|
||||
<SelectValue placeholder={m.unassigned()} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">
|
||||
<span className="text-muted-foreground italic">{m.unassigned()}</span>
|
||||
</SelectItem>
|
||||
{isAgentic
|
||||
? agents.map((a) => (
|
||||
<SelectItem key={a.id} value={a.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Bot className="w-3.5 h-3.5 text-purple-500" />
|
||||
<span>{a.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))
|
||||
: members.map((mItem) => (
|
||||
<SelectItem key={mItem.id} value={mItem.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar size="sm" className="w-4 h-4">
|
||||
<AvatarImage src={mItem.image} />
|
||||
<AvatarFallback className="text-[8px]">
|
||||
{mItem.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{mItem.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">{m.reporter()}</Label>
|
||||
<Select
|
||||
value={task.reporter?.id || 'none'}
|
||||
onValueChange={(val) => updateTask({ reporterId: val === 'none' ? null : val })}
|
||||
disabled={!canEdit}
|
||||
>
|
||||
<SelectTrigger className="w-full h-8 text-xs bg-background">
|
||||
<SelectValue placeholder={m.unassigned()} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">
|
||||
<span className="text-muted-foreground italic">{m.unassigned()}</span>
|
||||
</SelectItem>
|
||||
{members.map((mItem) => (
|
||||
<SelectItem key={mItem.id} value={mItem.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar size="sm" className="w-4 h-4">
|
||||
<AvatarImage src={mItem.image} />
|
||||
<AvatarFallback className="text-[8px]">
|
||||
{mItem.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{mItem.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Row 4: Target Folder Selector (only for agent task) */}
|
||||
{isAgentic && (
|
||||
<div className="sm:col-span-2 space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">
|
||||
{m.target_folder()}
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setIsFolderPickerOpen(true)}
|
||||
disabled={!canEdit}
|
||||
className="w-full justify-start h-8 text-xs bg-background truncate font-normal"
|
||||
>
|
||||
<Folder className="w-3.5 h-3.5 mr-2 text-primary shrink-0" />
|
||||
<span className="truncate">
|
||||
{targetFolderName ||
|
||||
(task.targetFolderId ? 'Selected Folder' : m.select_target_folder())}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Row 5: Start Date and Due Date */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">{m.start_date()}</Label>
|
||||
<DateTimePicker
|
||||
value={task.startDate ? new Date(task.startDate) : undefined}
|
||||
onChange={(date) => updateTask({ startDate: date ? date.toISOString() : null })}
|
||||
disabled={!canEdit}
|
||||
placeholder={m.start_date()}
|
||||
className="h-8 text-xs bg-background"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">{m.due_date()}</Label>
|
||||
<DateTimePicker
|
||||
value={task.dueDate ? new Date(task.dueDate) : undefined}
|
||||
onChange={(date) => updateTask({ dueDate: date ? date.toISOString() : null })}
|
||||
disabled={!canEdit}
|
||||
placeholder={m.due_date()}
|
||||
className="h-8 text-xs bg-background"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Row 6: Parent Tasks */}
|
||||
<div className="sm:col-span-2 space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">{m.parent_tasks()}</Label>
|
||||
<TaskParentSelector
|
||||
teamId={teamId}
|
||||
currentTaskId={task.id}
|
||||
excludeTaskIds={task.dependents.map((d) => d.id)}
|
||||
value={task.dependencies.map((d) => d.id)}
|
||||
knownTasks={[...task.dependencies, ...task.dependents]}
|
||||
onChange={(parentIds) => updateTask({ parentIds })}
|
||||
canEdit={canEdit}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Row 7: Related Assets */}
|
||||
<div className="sm:col-span-2 pt-1">
|
||||
<TaskRelatedAssets
|
||||
teamId={teamId}
|
||||
projectId={task.projectId}
|
||||
assets={task.assets || []}
|
||||
onAddAssets={(newAssets) => linkAssets(newAssets)}
|
||||
onRemoveAsset={(assetId) => unlinkAsset(assetId)}
|
||||
disabled={!canEdit}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Target Folder Dialog */}
|
||||
{isFolderPickerOpen && (
|
||||
<TaskTargetFolderDialog
|
||||
teamId={teamId}
|
||||
currentProjectId={task.projectId}
|
||||
currentTargetFolderId={task.targetFolderId}
|
||||
isOpen={isFolderPickerOpen}
|
||||
onClose={() => setIsFolderPickerOpen(false)}
|
||||
onSelect={(projId, foldId, foldName) => {
|
||||
setTargetFolderName(foldName || 'Selected Folder')
|
||||
updateTask({ projectId: projId, targetFolderId: foldId })
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</ScrollArea>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FolderTree } from '@/ui/components/folder-tree'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { AssetInfo, ProjectInfo } from '@shumai/dtos'
|
||||
import { Loader2, Folder } from 'lucide-react'
|
||||
|
||||
interface TaskTargetFolderDialogProps {
|
||||
teamId: string
|
||||
currentProjectId?: string | null
|
||||
currentTargetFolderId?: string | null
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onSelect: (projectId: string, folderId: string, folderName?: string) => void
|
||||
}
|
||||
|
||||
export function TaskTargetFolderDialog({
|
||||
teamId,
|
||||
currentProjectId,
|
||||
currentTargetFolderId,
|
||||
isOpen,
|
||||
onClose,
|
||||
onSelect,
|
||||
}: TaskTargetFolderDialogProps) {
|
||||
const [selectedProjectId, setSelectedProjectId] = useState<string>(currentProjectId || '')
|
||||
const [selectedFolder, setSelectedFolder] = useState<AssetInfo | null>(null)
|
||||
|
||||
const { data: projectsData, isLoading: isLoadingProjects } = useQuery({
|
||||
queryKey: ['teams', teamId, 'projects'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects.$get({
|
||||
param: { teamId },
|
||||
query: { first: '100' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch projects')
|
||||
return (await res.json()) as unknown as { data: ProjectInfo[] }
|
||||
},
|
||||
enabled: !!teamId && isOpen,
|
||||
})
|
||||
|
||||
const projects = projectsData?.data || []
|
||||
const activeProjectId = selectedProjectId || (projects[0]?.id ?? '')
|
||||
const selectedProject = projects.find((p) => p.id === activeProjectId)
|
||||
|
||||
const handleConfirm = () => {
|
||||
if (!activeProjectId) return
|
||||
const folderId = selectedFolder?.id || selectedProject?.rootFolder
|
||||
if (folderId) {
|
||||
onSelect(activeProjectId, folderId, selectedFolder?.name || selectedProject?.name)
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-2xl flex flex-col h-[580px]">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Folder className="w-5 h-5 text-primary" />
|
||||
<DialogTitle>{m.select_target_folder()}</DialogTitle>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-3 flex-1 overflow-hidden py-2">
|
||||
{/* Project Select */}
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-xs font-medium text-muted-foreground">
|
||||
{m.select_project()}
|
||||
</label>
|
||||
<Select
|
||||
value={activeProjectId}
|
||||
onValueChange={(val) => {
|
||||
setSelectedProjectId(val)
|
||||
setSelectedFolder(null)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="h-9">
|
||||
<SelectValue placeholder={m.select_project()} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{projects.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Folder Tree Scroll Area */}
|
||||
<div className="space-y-1.5 flex-1 flex flex-col overflow-hidden">
|
||||
<label className="text-xs font-medium text-muted-foreground">{m.target_folder()}</label>
|
||||
<div className="border rounded-md flex-1 overflow-hidden bg-sidebar/50">
|
||||
<ScrollArea className="h-full">
|
||||
{selectedProject && selectedProject.rootFolder ? (
|
||||
<FolderTree
|
||||
teamId={teamId}
|
||||
projectId={selectedProject.id}
|
||||
projectName={selectedProject.name}
|
||||
rootFolderId={selectedProject.rootFolder}
|
||||
onSelect={setSelectedFolder}
|
||||
selectedFolderId={
|
||||
selectedFolder?.id || currentTargetFolderId || selectedProject.rootFolder
|
||||
}
|
||||
hideCollections
|
||||
hideShares
|
||||
hideRecentlyDeleted
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full p-6 text-xs text-muted-foreground">
|
||||
{isLoadingProjects ? (
|
||||
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
m.no_project_selected()
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button onClick={handleConfirm} disabled={!activeProjectId}>
|
||||
{m.confirm()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
import { useState } from 'react'
|
||||
import { DragDropProvider, KeyboardSensor, PointerSensor, type DragEndEvent } from '@dnd-kit/react'
|
||||
import { PointerActivationConstraints } from '@dnd-kit/dom'
|
||||
import { useMutation, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { toast } from 'sonner'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { KanbanTaskStatus, type KanbanTaskInfo, type ListKanbanTasksResponse } from '@shumai/dtos'
|
||||
import { KANBAN_STATUS_COLUMNS } from './kanban-types'
|
||||
import { KanbanColumn } from './kanban-column'
|
||||
|
||||
interface KanbanBoardProps {
|
||||
teamId: string
|
||||
selectedGoalId: string | null
|
||||
scope: 'team' | 'my'
|
||||
currentUserId?: string
|
||||
currentUserRole?: string
|
||||
onTaskClick: (task: KanbanTaskInfo) => void
|
||||
onCreateTaskInColumn: (status: KanbanTaskStatus) => void
|
||||
}
|
||||
|
||||
export function KanbanBoard({
|
||||
teamId,
|
||||
selectedGoalId,
|
||||
scope,
|
||||
currentUserId,
|
||||
currentUserRole,
|
||||
onTaskClick,
|
||||
onCreateTaskInColumn,
|
||||
}: KanbanBoardProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [taskToDelete, setTaskToDelete] = useState<KanbanTaskInfo | null>(null)
|
||||
|
||||
const { mutate: deleteTask, isPending: isDeleting } = useMutation({
|
||||
mutationFn: async (taskId: string) => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].$delete({
|
||||
param: { teamId, taskId },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: m.error() }))
|
||||
throw new Error((err as { message?: string }).message || m.error())
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'tasks'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'goals'] })
|
||||
toast.success(m.task_deleted())
|
||||
setTaskToDelete(null)
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
// Unified Update Mutation with Optimistic Updates
|
||||
const { mutate: updateTask } = useMutation({
|
||||
mutationFn: async ({
|
||||
taskId,
|
||||
fromStatus,
|
||||
status,
|
||||
reason,
|
||||
beforeIndex,
|
||||
afterIndex,
|
||||
}: {
|
||||
taskId: string
|
||||
fromStatus?: KanbanTaskStatus
|
||||
status: KanbanTaskStatus
|
||||
reason?: string
|
||||
beforeIndex?: string
|
||||
afterIndex?: string
|
||||
targetTaskId?: string
|
||||
position?: 'before' | 'after'
|
||||
}) => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks[':taskId'].$patch({
|
||||
param: { teamId, taskId },
|
||||
json: { fromStatus, status, reason, beforeIndex, afterIndex },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: m.error() }))
|
||||
throw new Error((err as { message?: string }).message || m.error())
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onMutate: async ({ taskId, status, targetTaskId, position }) => {
|
||||
// Cancel any outgoing refetches so they don't overwrite optimistic update
|
||||
await queryClient.cancelQueries({ queryKey: ['teams', teamId, 'kanban', 'tasks'] })
|
||||
|
||||
// Snapshot previous state
|
||||
const previousQueries = queryClient.getQueriesData({
|
||||
queryKey: ['teams', teamId, 'kanban', 'tasks'],
|
||||
})
|
||||
|
||||
let movedTask: KanbanTaskInfo | null = null
|
||||
|
||||
// Helper to check if a query is a Kanban column infinite query
|
||||
const isColumnQuery = (queryKey: readonly unknown[]) => {
|
||||
return (
|
||||
queryKey[0] === 'teams' &&
|
||||
queryKey[1] === teamId &&
|
||||
queryKey[2] === 'kanban' &&
|
||||
queryKey[3] === 'tasks' &&
|
||||
typeof queryKey[4] === 'object' &&
|
||||
queryKey[4] !== null &&
|
||||
'status' in queryKey[4]
|
||||
)
|
||||
}
|
||||
|
||||
// 1. Remove task from current column in cache and save it
|
||||
queryClient.setQueriesData<InfiniteData<ListKanbanTasksResponse>>(
|
||||
{
|
||||
predicate: (query) => isColumnQuery(query.queryKey),
|
||||
},
|
||||
(oldData) => {
|
||||
if (!oldData || !Array.isArray(oldData.pages)) return oldData
|
||||
|
||||
let found = false
|
||||
const newPages = oldData.pages.map((page) => {
|
||||
if (!page || !Array.isArray(page.data)) return page
|
||||
const task = page.data.find((t) => t.id === taskId)
|
||||
if (task) {
|
||||
movedTask = { ...task, status }
|
||||
found = true
|
||||
return {
|
||||
...page,
|
||||
data: page.data.filter((t) => t.id !== taskId),
|
||||
pageInfo: {
|
||||
...page.pageInfo,
|
||||
total: Math.max(0, (page.pageInfo?.total ?? page.data.length) - 1),
|
||||
},
|
||||
}
|
||||
}
|
||||
return page
|
||||
})
|
||||
|
||||
return found ? { ...oldData, pages: newPages } : oldData
|
||||
},
|
||||
)
|
||||
|
||||
// 2. Insert task into destination column cache at target position
|
||||
if (movedTask) {
|
||||
const taskToAdd = movedTask
|
||||
queryClient.setQueriesData<InfiniteData<ListKanbanTasksResponse>>(
|
||||
{
|
||||
predicate: (query) => {
|
||||
if (!isColumnQuery(query.queryKey)) return false
|
||||
const filter = query.queryKey[4] as { status?: KanbanTaskStatus } | undefined
|
||||
return filter?.status === status
|
||||
},
|
||||
},
|
||||
(oldData) => {
|
||||
if (!oldData || !Array.isArray(oldData.pages)) return oldData
|
||||
|
||||
const allItems = oldData.pages
|
||||
.flatMap((page) => page?.data ?? [])
|
||||
.filter((t) => t.id !== taskId)
|
||||
|
||||
let insertIndex = allItems.length
|
||||
if (targetTaskId) {
|
||||
const idx = allItems.findIndex((t) => t.id === targetTaskId)
|
||||
if (idx !== -1) {
|
||||
insertIndex = position === 'before' ? idx : idx + 1
|
||||
}
|
||||
}
|
||||
|
||||
allItems.splice(insertIndex, 0, taskToAdd)
|
||||
|
||||
let pointer = 0
|
||||
const newPages = oldData.pages.map((page, pageIdx) => {
|
||||
const pageSize = page?.data ? page.data.length : 0
|
||||
const takeSize =
|
||||
pageIdx === 0 && pageSize === 0
|
||||
? 1
|
||||
: pageIdx === oldData.pages.length - 1
|
||||
? allItems.length - pointer
|
||||
: pageSize
|
||||
const pageData = allItems.slice(pointer, pointer + takeSize)
|
||||
pointer += takeSize
|
||||
return {
|
||||
...page,
|
||||
data: pageData,
|
||||
pageInfo: {
|
||||
...page?.pageInfo,
|
||||
total: (page?.pageInfo?.total ?? 0) + 1,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
if (pointer < allItems.length && newPages.length > 0) {
|
||||
const lastPageIndex = newPages.length - 1
|
||||
newPages[lastPageIndex] = {
|
||||
...newPages[lastPageIndex],
|
||||
data: [...(newPages[lastPageIndex]?.data ?? []), ...allItems.slice(pointer)],
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...oldData,
|
||||
pages: newPages,
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return { previousQueries }
|
||||
},
|
||||
onError: (err, _variables, context) => {
|
||||
if (context?.previousQueries) {
|
||||
for (const [queryKey, data] of context.previousQueries) {
|
||||
queryClient.setQueryData(queryKey, data)
|
||||
}
|
||||
}
|
||||
toast.error(err.message)
|
||||
},
|
||||
onSettled: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'tasks'] })
|
||||
},
|
||||
})
|
||||
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
if (event.canceled) return
|
||||
const { source, target } = event.operation
|
||||
if (!source || !target) return
|
||||
|
||||
const sourceData = source.data as { type?: string; task?: KanbanTaskInfo } | undefined
|
||||
if (sourceData?.type !== 'kanban_task' || !sourceData.task) return
|
||||
const task = sourceData.task
|
||||
|
||||
// Check status change permission
|
||||
const isOwner = currentUserRole?.toLowerCase() === 'owner'
|
||||
const isReporter = task.reporter?.id === currentUserId || task.creator?.id === currentUserId
|
||||
const isAssignee = task.assignee?.id === currentUserId
|
||||
if (!isOwner && !isReporter && !isAssignee) {
|
||||
toast.error(m.cannot_change_task_status_permission())
|
||||
return
|
||||
}
|
||||
|
||||
const targetData = target.data as
|
||||
| { type?: 'reorder'; task?: KanbanTaskInfo; position?: 'before' | 'after' }
|
||||
| { type?: 'kanban_column'; status?: KanbanTaskStatus }
|
||||
| undefined
|
||||
|
||||
if (!targetData) return
|
||||
|
||||
if (targetData.type === 'reorder' && targetData.task && targetData.position) {
|
||||
const targetTask = targetData.task
|
||||
const toStatus = targetTask.status
|
||||
|
||||
if (task.id === targetTask.id) return
|
||||
|
||||
const beforeIndex =
|
||||
targetData.position === 'before' ? (targetTask.sortIndex ?? undefined) : undefined
|
||||
const afterIndex =
|
||||
targetData.position === 'after' ? (targetTask.sortIndex ?? undefined) : undefined
|
||||
|
||||
updateTask({
|
||||
taskId: task.id,
|
||||
fromStatus: task.status,
|
||||
status: toStatus,
|
||||
beforeIndex,
|
||||
afterIndex,
|
||||
targetTaskId: targetTask.id,
|
||||
position: targetData.position,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (targetData.type === 'kanban_column' && targetData.status) {
|
||||
const toStatus = targetData.status
|
||||
if (task.status === toStatus) return
|
||||
|
||||
updateTask({ taskId: task.id, fromStatus: task.status, status: toStatus })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DragDropProvider
|
||||
sensors={[
|
||||
PointerSensor.configure({
|
||||
activationConstraints: [new PointerActivationConstraints.Distance({ value: 8 })],
|
||||
}),
|
||||
KeyboardSensor,
|
||||
]}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<div className="flex-1 min-h-0 overflow-x-auto overflow-y-hidden p-4 bg-background/50">
|
||||
<div className="flex gap-4 h-full min-w-max pb-2">
|
||||
{KANBAN_STATUS_COLUMNS.map((status) => (
|
||||
<KanbanColumn
|
||||
key={status}
|
||||
teamId={teamId}
|
||||
status={status}
|
||||
selectedGoalId={selectedGoalId}
|
||||
scope={scope}
|
||||
currentUserId={currentUserId}
|
||||
currentUserRole={currentUserRole}
|
||||
onTaskClick={onTaskClick}
|
||||
onDeleteTask={(task) => setTaskToDelete(task)}
|
||||
onCreateTaskInColumn={onCreateTaskInColumn}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Delete Task Confirmation */}
|
||||
{taskToDelete && (
|
||||
<AlertDialog open={!!taskToDelete} onOpenChange={(open) => !open && setTaskToDelete(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{m.delete_task()}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{m.delete_task_confirm({ title: taskToDelete.title })}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isDeleting}>{m.cancel()}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => deleteTask(taskToDelete.id)}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting && <Loader2 className="w-4 h-4 mr-1.5 animate-spin" />}
|
||||
{m.delete()}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
</DragDropProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
import { useDraggable, useDroppable, useDragOperation } from '@dnd-kit/react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { KanbanTaskStatus, type KanbanTaskInfo } from '@shumai/dtos'
|
||||
import { getPriorityBadgeColor, getPriorityLabel } from './kanban-types'
|
||||
import {
|
||||
Bot,
|
||||
Calendar,
|
||||
Link2,
|
||||
MessageSquare,
|
||||
Files,
|
||||
AlertTriangle,
|
||||
Target,
|
||||
Sparkles,
|
||||
MoreHorizontal,
|
||||
Trash2,
|
||||
} from 'lucide-react'
|
||||
import { format, isPast } from 'date-fns'
|
||||
|
||||
interface KanbanCardProps {
|
||||
task: KanbanTaskInfo
|
||||
onClick: (task: KanbanTaskInfo) => void
|
||||
onDelete?: (task: KanbanTaskInfo) => void
|
||||
disabled?: boolean
|
||||
isFirst?: boolean
|
||||
showBottomIndicator?: boolean
|
||||
currentUserId?: string
|
||||
currentUserRole?: string
|
||||
}
|
||||
|
||||
export function KanbanCard({
|
||||
task,
|
||||
onClick,
|
||||
onDelete,
|
||||
disabled,
|
||||
isFirst,
|
||||
showBottomIndicator,
|
||||
currentUserId,
|
||||
currentUserRole,
|
||||
}: KanbanCardProps) {
|
||||
const { source } = useDragOperation()
|
||||
const isDraggingAny = !!source
|
||||
|
||||
const isOwner = currentUserRole?.toLowerCase() === 'owner'
|
||||
const isCreator = !!currentUserId && task.creator?.id === currentUserId
|
||||
const isReporter = task.reporter?.id === currentUserId || isCreator
|
||||
const isAssignee = task.assignee?.id === currentUserId
|
||||
const canChangeStatus = isOwner || isReporter || isAssignee
|
||||
const canDelete = isCreator || isOwner
|
||||
const isDragDisabled = disabled || !canChangeStatus
|
||||
|
||||
const { ref: setDraggableRef, isDragging } = useDraggable({
|
||||
id: task.id,
|
||||
data: {
|
||||
type: 'kanban_task',
|
||||
task,
|
||||
},
|
||||
disabled: isDragDisabled,
|
||||
})
|
||||
|
||||
const { ref: setTopDroppableRef, isDropTarget: isTopOver } = useDroppable({
|
||||
id: `reorder-before-${task.id}`,
|
||||
data: {
|
||||
type: 'reorder',
|
||||
task,
|
||||
position: 'before',
|
||||
},
|
||||
disabled: isDragging || disabled,
|
||||
})
|
||||
|
||||
const { ref: setBottomDroppableRef, isDropTarget: isBottomOver } = useDroppable({
|
||||
id: `reorder-after-${task.id}`,
|
||||
data: {
|
||||
type: 'reorder',
|
||||
task,
|
||||
position: 'after',
|
||||
},
|
||||
disabled: isDragging || disabled,
|
||||
})
|
||||
|
||||
const isAgentic = task.isAgentTask
|
||||
const isBlocked = task.status === KanbanTaskStatus.BLOCKED
|
||||
const isOverdue = task.dueDate
|
||||
? isPast(new Date(task.dueDate)) && task.status !== KanbanTaskStatus.DONE
|
||||
: false
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
{/* Top 50% Droppable Zone (reorder before this card) */}
|
||||
<div
|
||||
ref={setTopDroppableRef}
|
||||
className={cn(
|
||||
'absolute left-0 right-0 z-20',
|
||||
isFirst ? '-top-6 h-[calc(50%+24px)]' : '-top-1 h-[calc(50%+4px)]',
|
||||
isDraggingAny && !isDragging ? 'pointer-events-auto' : 'pointer-events-none',
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Bottom 50% Droppable Zone (reorder after this card) */}
|
||||
<div
|
||||
ref={setBottomDroppableRef}
|
||||
className={cn(
|
||||
'absolute bottom-0 left-0 right-0 h-1/2 z-20',
|
||||
isDraggingAny && !isDragging ? 'pointer-events-auto' : 'pointer-events-none',
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Top Reorder Drop Indicator Line */}
|
||||
{isTopOver && !isDragging && (
|
||||
<div className="absolute -top-1.5 left-0 right-0 h-[3px] rounded-full bg-primary shadow-[0_0_8px_rgba(var(--primary),0.6)] z-30 pointer-events-none" />
|
||||
)}
|
||||
|
||||
{/* Bottom Reorder Drop Indicator Line */}
|
||||
{(isBottomOver || showBottomIndicator) && !isDragging && (
|
||||
<div className="absolute -bottom-1.5 left-0 right-0 h-[3px] rounded-full bg-primary shadow-[0_0_8px_rgba(var(--primary),0.6)] z-30 pointer-events-none" />
|
||||
)}
|
||||
|
||||
{/* Task Card Body */}
|
||||
<div
|
||||
ref={setDraggableRef}
|
||||
onClick={() => onClick(task)}
|
||||
className={cn(
|
||||
'group relative flex flex-col gap-2 p-3 rounded-lg border text-card-foreground transition-all duration-200 cursor-pointer select-none',
|
||||
isDragging && 'opacity-40 scale-95 shadow-lg ring-2 ring-primary',
|
||||
!isDragging && 'hover:shadow-md',
|
||||
'border-border/80 bg-card hover:border-primary/50 shadow-2xs',
|
||||
// Blocked warning state
|
||||
isBlocked && 'border-red-500/60 bg-red-500/[0.03] ring-1 ring-red-500/20',
|
||||
)}
|
||||
>
|
||||
{/* Top Header Row: Goal Tag & Badges */}
|
||||
<div className="flex items-center justify-between gap-1.5 min-w-0">
|
||||
<div className="flex items-center gap-1.5 min-w-0 flex-1">
|
||||
{/* Priority Badge */}
|
||||
<span
|
||||
className={cn(
|
||||
'px-1.5 py-0.5 rounded text-[10px] font-medium border uppercase tracking-wider shrink-0',
|
||||
getPriorityBadgeColor(task.priority),
|
||||
)}
|
||||
>
|
||||
{getPriorityLabel(task.priority)}
|
||||
</span>
|
||||
|
||||
{/* Task Type Badge (Agent Task only) */}
|
||||
{isAgentic && (
|
||||
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-semibold bg-orange-500/15 text-orange-600 dark:text-orange-400 border border-orange-500/30 shrink-0">
|
||||
<Bot className="w-3 h-3" />
|
||||
<span>{m.task_type_agent()}</span>
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Goal Tag */}
|
||||
{task.goal && (
|
||||
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-muted text-muted-foreground border border-border/70 truncate max-w-[130px]">
|
||||
<Target className="w-2.5 h-2.5 shrink-0" />
|
||||
<span className="truncate">{task.goal.title}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
{/* Three Dot Action Menu (for Task Creator & Team Owner) */}
|
||||
{canDelete && (
|
||||
<div
|
||||
className="opacity-0 group-hover:opacity-100 [&:has([data-state=open])]:opacity-100 focus-within:opacity-100 transition-opacity flex items-center"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="h-5 w-5 p-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<MoreHorizontal className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-32">
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive focus:bg-destructive/10"
|
||||
onClick={() => onDelete?.(task)}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5 mr-2" />
|
||||
{m.delete()}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Task Title */}
|
||||
<h4 className="text-xs font-semibold leading-snug line-clamp-2 text-foreground break-words">
|
||||
{task.title}
|
||||
</h4>
|
||||
|
||||
{/* Blocked Reason Banner */}
|
||||
{isBlocked && (
|
||||
<div className="flex items-start gap-1.5 p-1.5 rounded bg-red-500/10 border border-red-500/20 text-[11px] text-red-600 dark:text-red-400">
|
||||
<AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-0.5" />
|
||||
<span className="line-clamp-2 break-words">
|
||||
{task.latestStatusEvent?.blockReason ||
|
||||
task.latestStatusEvent?.reason ||
|
||||
task.latestStatusEvent?.summary ||
|
||||
m.status_blocked()}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Review Feedback Banner */}
|
||||
{task.status === KanbanTaskStatus.IN_REVIEW && task.latestStatusEvent?.summary && (
|
||||
<div className="flex items-start gap-1.5 p-1.5 rounded bg-purple-500/10 border border-purple-500/20 text-[11px] text-purple-600 dark:text-purple-400">
|
||||
<Sparkles className="w-3.5 h-3.5 shrink-0 mt-0.5" />
|
||||
<span className="line-clamp-2 break-words">{task.latestStatusEvent.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Card Footer: Assignee & Metadata Badges */}
|
||||
<div className="flex items-center justify-between gap-2 pt-1 mt-auto border-t border-border/40 text-[11px] text-muted-foreground">
|
||||
{/* Assignee */}
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
{task.assignee ? (
|
||||
<>
|
||||
{isAgentic ? (
|
||||
<div className="w-5 h-5 rounded-full bg-orange-500/15 border border-orange-500/30 flex items-center justify-center shrink-0">
|
||||
<Bot className="w-3 h-3 text-orange-600 dark:text-orange-400" />
|
||||
</div>
|
||||
) : (
|
||||
<Avatar size="sm" className="w-5 h-5 border border-border">
|
||||
<AvatarImage src={task.assignee.image} />
|
||||
<AvatarFallback className="text-[9px]">
|
||||
{task.assignee.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
)}
|
||||
<span className="truncate text-xs font-medium text-foreground/80 max-w-[90px]">
|
||||
{task.assignee.name}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-[11px] italic text-muted-foreground/60">{m.unassigned()}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right side stats: Due Date, Dependencies, Comments */}
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{/* Due Date */}
|
||||
{task.dueDate && (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center gap-1 text-[10px] font-mono',
|
||||
isOverdue ? 'text-red-500 font-semibold' : 'text-muted-foreground',
|
||||
)}
|
||||
title={format(new Date(task.dueDate), 'yyyy/MM/dd HH:mm')}
|
||||
>
|
||||
<Calendar className="w-3 h-3" />
|
||||
<span>{format(new Date(task.dueDate), 'MM/dd')}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Linked assets count */}
|
||||
{task.assetCount > 0 && (
|
||||
<div
|
||||
className="flex items-center gap-0.5 text-[10px] text-muted-foreground hover:text-foreground"
|
||||
title={m.linked_assets_count({ count: task.assetCount })}
|
||||
>
|
||||
<Files className="w-3 h-3" />
|
||||
<span>{task.assetCount}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Dependencies count */}
|
||||
{task.dependencyCount > 0 && (
|
||||
<div
|
||||
className="flex items-center gap-0.5 text-[10px] text-muted-foreground hover:text-foreground"
|
||||
title={`${task.dependencyCount} dependencies`}
|
||||
>
|
||||
<Link2 className="w-3 h-3" />
|
||||
<span>{task.dependencyCount}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Comments count */}
|
||||
{task.commentCount > 0 && (
|
||||
<div
|
||||
className="flex items-center gap-0.5 text-[10px] text-muted-foreground hover:text-foreground"
|
||||
title={`${task.commentCount} comments`}
|
||||
>
|
||||
<MessageSquare className="w-3 h-3" />
|
||||
<span>{task.commentCount}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { useEffect, useMemo } from 'react'
|
||||
import { useInfiniteQuery } from '@tanstack/react-query'
|
||||
import { useDroppable, useDragOperation } from '@dnd-kit/react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { KanbanTaskStatus, type KanbanTaskInfo, type ListKanbanTasksResponse } from '@shumai/dtos'
|
||||
import { getStatusColor, getStatusLabel } from './kanban-types'
|
||||
import { KanbanCard } from './kanban-card'
|
||||
import { Plus, Loader2 } from 'lucide-react'
|
||||
|
||||
interface KanbanColumnProps {
|
||||
teamId: string
|
||||
status: KanbanTaskStatus
|
||||
selectedGoalId: string | null
|
||||
scope: 'team' | 'my'
|
||||
currentUserId?: string
|
||||
currentUserRole?: string
|
||||
onTaskClick: (task: KanbanTaskInfo) => void
|
||||
onDeleteTask?: (task: KanbanTaskInfo) => void
|
||||
onCreateTaskInColumn: (status: KanbanTaskStatus) => void
|
||||
}
|
||||
|
||||
export function KanbanColumn({
|
||||
teamId,
|
||||
status,
|
||||
selectedGoalId,
|
||||
scope,
|
||||
currentUserId,
|
||||
currentUserRole,
|
||||
onTaskClick,
|
||||
onDeleteTask,
|
||||
onCreateTaskInColumn,
|
||||
}: KanbanColumnProps) {
|
||||
const { ref: setDroppableRef, isDropTarget } = useDroppable({
|
||||
id: status,
|
||||
data: {
|
||||
type: 'kanban_column',
|
||||
status,
|
||||
},
|
||||
})
|
||||
|
||||
const { source, target } = useDragOperation()
|
||||
const isDraggingTask = source?.data?.type === 'kanban_task'
|
||||
const isOverThisColumn =
|
||||
isDraggingTask &&
|
||||
(isDropTarget ||
|
||||
(target?.data?.type === 'kanban_column' && target.data.status === status) ||
|
||||
(target?.data?.type === 'reorder' &&
|
||||
(target.data.task as KanbanTaskInfo | undefined)?.status === status))
|
||||
|
||||
const isOverColumnEmptySpace =
|
||||
isDraggingTask && target?.data?.type === 'kanban_column' && target.data.status === status
|
||||
|
||||
const { ref: loadMoreRef, inView } = useInView({
|
||||
threshold: 0.1,
|
||||
})
|
||||
|
||||
const assigneeId = scope === 'my' ? currentUserId : undefined
|
||||
|
||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } = useInfiniteQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'tasks', { status, goalId: selectedGoalId, assigneeId }],
|
||||
queryFn: async ({ pageParam = '' }) => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks.$get({
|
||||
param: { teamId },
|
||||
query: {
|
||||
status,
|
||||
goalId: selectedGoalId || undefined,
|
||||
assigneeId: assigneeId || undefined,
|
||||
first: '20',
|
||||
after: (pageParam as string) || undefined,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch column tasks')
|
||||
return (await res.json()) as unknown as ListKanbanTasksResponse
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
|
||||
refetchInterval: 5000,
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
|
||||
const allTasks = useMemo(() => {
|
||||
return data?.pages?.flatMap((page) => (Array.isArray(page?.data) ? page.data : [])) || []
|
||||
}, [data])
|
||||
|
||||
const lastVisibleTask = allTasks.filter((t) => t.id !== source?.id).at(-1)
|
||||
const totalCount = data?.pages?.[0]?.pageInfo?.total ?? allTasks.length
|
||||
const statusColor = getStatusColor(status)
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setDroppableRef}
|
||||
className={cn(
|
||||
'flex flex-col h-full max-h-full w-80 md:w-84 shrink-0 rounded-xl bg-card/60 border border-border/70 shadow-xs transition-colors duration-200 overflow-hidden select-none',
|
||||
isOverThisColumn && 'ring-2 ring-primary/60 bg-primary/[0.03] border-primary/40',
|
||||
)}
|
||||
>
|
||||
{/* Column Header */}
|
||||
<div className="h-11 px-3.5 flex items-center justify-between border-b border-border/60 bg-card/80 shrink-0">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<div className={cn('w-2.5 h-2.5 rounded-full shrink-0', statusColor.dot)} />
|
||||
<h3 className="text-xs font-bold tracking-wide uppercase text-foreground/90 truncate">
|
||||
{getStatusLabel(status)}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
<span className="text-[11px] font-mono px-2 py-0.5 rounded-full bg-muted font-medium text-muted-foreground">
|
||||
{totalCount}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Column Task Cards Body */}
|
||||
<ScrollArea className="flex-1 min-h-0 [&>div>div]:block!">
|
||||
<div className="p-2.5 space-y-2.5 min-h-full flex flex-col">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-10">
|
||||
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : allTasks.length === 0 ? (
|
||||
<div className="relative flex flex-col items-center justify-center py-10 px-4 text-center">
|
||||
{isOverColumnEmptySpace && (
|
||||
<div className="absolute top-3 left-3 right-3 h-[3px] rounded-full bg-primary shadow-[0_0_8px_rgba(var(--primary),0.6)] z-30 pointer-events-none" />
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground/70">{m.no_tasks_in_column()}</p>
|
||||
</div>
|
||||
) : (
|
||||
allTasks.map((task, index) => (
|
||||
<KanbanCard
|
||||
key={task.id}
|
||||
task={task}
|
||||
onClick={onTaskClick}
|
||||
onDelete={onDeleteTask}
|
||||
isFirst={index === 0}
|
||||
showBottomIndicator={isOverColumnEmptySpace && task.id === lastVisibleTask?.id}
|
||||
currentUserId={currentUserId}
|
||||
currentUserRole={currentUserRole}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
|
||||
{/* Infinite Scroll Sentinel */}
|
||||
<div ref={loadMoreRef} className="h-2" />
|
||||
{isFetchingNextPage && (
|
||||
<div className="flex justify-center py-2">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
{/* Fixed Column Footer: + Create Task */}
|
||||
<div className="p-2 border-t border-border/50 bg-card/90 shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onCreateTaskInColumn(status)}
|
||||
className="w-full justify-center h-8 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted/80 border border-dashed border-border/80"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5 mr-1.5" />
|
||||
<span>{m.create_task()}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Textarea } from '@/ui/components/ui/textarea'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { KanbanGoalInfo } from '@shumai/dtos'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
|
||||
interface KanbanCreateGoalDialogProps {
|
||||
teamId: string
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
goalToEdit?: KanbanGoalInfo | null
|
||||
}
|
||||
|
||||
export function KanbanCreateGoalDialog({
|
||||
teamId,
|
||||
isOpen,
|
||||
onClose,
|
||||
goalToEdit,
|
||||
}: KanbanCreateGoalDialogProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [title, setTitle] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (goalToEdit) {
|
||||
setTitle(goalToEdit.title)
|
||||
setDescription(goalToEdit.description || '')
|
||||
} else {
|
||||
setTitle('')
|
||||
setDescription('')
|
||||
}
|
||||
}, [goalToEdit, isOpen])
|
||||
|
||||
const { mutate: createGoal, isPending: isCreating } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.goals.$post({
|
||||
param: { teamId },
|
||||
json: {
|
||||
title: title.trim(),
|
||||
description: description.trim() || undefined,
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: m.error() }))
|
||||
throw new Error((err as { message?: string }).message || m.error())
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'goals'] })
|
||||
toast.success(m.goal_created())
|
||||
onClose()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const { mutate: updateGoal, isPending: isUpdating } = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!goalToEdit) return
|
||||
const res = await client.api.teams[':teamId'].kanban.goals[':goalId'].$patch({
|
||||
param: { teamId, goalId: goalToEdit.id },
|
||||
json: {
|
||||
title: title.trim(),
|
||||
description: description.trim() || null,
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: m.error() }))
|
||||
throw new Error((err as { message?: string }).message || m.error())
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'goals'] })
|
||||
toast.success(m.goal_updated())
|
||||
onClose()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!title.trim()) return
|
||||
if (goalToEdit) {
|
||||
updateGoal()
|
||||
} else {
|
||||
createGoal()
|
||||
}
|
||||
}
|
||||
|
||||
const isLoading = isCreating || isUpdating
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{goalToEdit ? m.edit_goal() : m.create_goal()}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{goalToEdit ? m.edit_goal() : m.create_first_goal()}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-3 py-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="goal-title">{m.goal_title()}</Label>
|
||||
<Input
|
||||
id="goal-title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder={m.goal_title_placeholder()}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="goal-description">{m.goal_description()}</Label>
|
||||
<Textarea
|
||||
id="goal-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder={m.goal_description_placeholder()}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button type="submit" disabled={!title.trim() || isLoading}>
|
||||
{isLoading && <Loader2 className="w-4 h-4 mr-1.5 animate-spin" />}
|
||||
{goalToEdit ? m.save_changes() : m.create()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Textarea } from '@/ui/components/ui/textarea'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { DateTimePicker } from '@/ui/components/datetime-picker'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { toast } from 'sonner'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import {
|
||||
KanbanTaskPriority,
|
||||
KanbanTaskStatus,
|
||||
type KanbanGoalInfo,
|
||||
type AgentInfo,
|
||||
type KanbanTaskAssetInfo,
|
||||
UNASSIGNED_GOAL_ID,
|
||||
} from '@shumai/dtos'
|
||||
import { getPriorityBadgeColor, getPriorityLabel } from './kanban-types'
|
||||
import { TaskTargetFolderDialog } from './edit-task-dialog/task-target-folder-dialog'
|
||||
import { TaskParentSelector } from './task-parent-selector'
|
||||
import { TaskRelatedAssets } from './task-related-assets'
|
||||
import { Bot, Folder, Target, Loader2 } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
|
||||
interface KanbanCreateTaskDialogProps {
|
||||
teamId: string
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
initialStatus?: KanbanTaskStatus
|
||||
initialGoalId?: string | null
|
||||
}
|
||||
|
||||
export function KanbanCreateTaskDialog({
|
||||
teamId,
|
||||
isOpen,
|
||||
onClose,
|
||||
initialGoalId,
|
||||
}: KanbanCreateTaskDialogProps) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const effectiveInitialGoalId =
|
||||
initialGoalId === UNASSIGNED_GOAL_ID || !initialGoalId ? 'none' : initialGoalId
|
||||
|
||||
const [title, setTitle] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [isAgentTask, setIsAgentTask] = useState(false)
|
||||
const [priority, setPriority] = useState<KanbanTaskPriority>(KanbanTaskPriority.MEDIUM)
|
||||
const [goalId, setGoalId] = useState<string>(effectiveInitialGoalId)
|
||||
const [assigneeId, setAssigneeId] = useState<string>('none')
|
||||
const [reporterId, setReporterId] = useState<string>('none')
|
||||
const [startDate, setStartDate] = useState<Date | undefined>(undefined)
|
||||
const [dueDate, setDueDate] = useState<Date | undefined>(undefined)
|
||||
const [projectId, setProjectId] = useState<string | null>(null)
|
||||
const [targetFolderId, setTargetFolderId] = useState<string | null>(null)
|
||||
const [targetFolderName, setTargetFolderName] = useState<string | null>(null)
|
||||
const [parentIds, setParentIds] = useState<string[]>([])
|
||||
const [selectedAssets, setSelectedAssets] = useState<KanbanTaskAssetInfo[]>([])
|
||||
const [isFolderPickerOpen, setIsFolderPickerOpen] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setTitle('')
|
||||
setDescription('')
|
||||
setIsAgentTask(false)
|
||||
setPriority(KanbanTaskPriority.MEDIUM)
|
||||
setGoalId(effectiveInitialGoalId)
|
||||
setAssigneeId('none')
|
||||
setReporterId('none')
|
||||
setStartDate(undefined)
|
||||
setDueDate(undefined)
|
||||
setProjectId(null)
|
||||
setTargetFolderId(null)
|
||||
setTargetFolderName(null)
|
||||
setParentIds([])
|
||||
setSelectedAssets([])
|
||||
}
|
||||
}, [isOpen, effectiveInitialGoalId])
|
||||
|
||||
// Queries for selectors
|
||||
const { data: members = [] } = useQuery({
|
||||
queryKey: ['teams', teamId, 'members', 'human'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].members.$get({
|
||||
param: { teamId },
|
||||
query: { includeAgents: 'false' },
|
||||
})
|
||||
if (!res.ok) return []
|
||||
const data = await res.json()
|
||||
return Array.isArray(data) ? data : []
|
||||
},
|
||||
enabled: !!teamId && isOpen,
|
||||
})
|
||||
|
||||
const { data: agents = [] } = useQuery({
|
||||
queryKey: ['teams', teamId, 'agents'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].agents.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) return []
|
||||
return ((await res.json()) as AgentInfo[]) || []
|
||||
},
|
||||
enabled: !!teamId && isOpen,
|
||||
})
|
||||
|
||||
const { data: goalsData } = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'goals'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.goals.$get({
|
||||
param: { teamId },
|
||||
query: {},
|
||||
})
|
||||
if (!res.ok) return { data: [] }
|
||||
return (await res.json()) as { data: KanbanGoalInfo[] }
|
||||
},
|
||||
enabled: !!teamId && isOpen,
|
||||
})
|
||||
|
||||
const goals = goalsData?.data || []
|
||||
|
||||
// Create task mutation
|
||||
const { mutate: createTask, isPending } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks.$post({
|
||||
param: { teamId },
|
||||
json: {
|
||||
title: title.trim(),
|
||||
description: description.trim() || undefined,
|
||||
isAgentTask,
|
||||
priority,
|
||||
goalId: goalId !== 'none' ? goalId : undefined,
|
||||
assigneeId: assigneeId !== 'none' ? assigneeId : undefined,
|
||||
reporterId: reporterId !== 'none' ? reporterId : undefined,
|
||||
startDate: startDate ? startDate.toISOString() : undefined,
|
||||
dueDate: dueDate ? dueDate.toISOString() : undefined,
|
||||
projectId: projectId || undefined,
|
||||
targetFolderId: targetFolderId || undefined,
|
||||
parentIds: parentIds.length > 0 ? parentIds : undefined,
|
||||
assetIds: selectedAssets.length > 0 ? selectedAssets.map((a) => a.id) : undefined,
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: m.error() }))
|
||||
throw new Error((err as { message?: string }).message || m.error())
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'tasks'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'goals'] })
|
||||
toast.success(m.task_created())
|
||||
onClose()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!title.trim() || isPending) return
|
||||
createTask()
|
||||
}
|
||||
|
||||
const isAgentic = isAgentTask
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-3xl max-h-[90vh] overflow-y-auto">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{m.create_task()}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-3.5 py-1">
|
||||
{/* Title */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="create-task-title">{m.task_title()}</Label>
|
||||
<Input
|
||||
id="create-task-title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder={m.task_title_placeholder()}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="create-task-desc">{m.task_description()}</Label>
|
||||
<Textarea
|
||||
id="create-task-desc"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder={m.task_description_placeholder()}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Properties Grid */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
{/* Row 1: Agent Task Switch */}
|
||||
<div className="sm:col-span-2 flex items-center justify-between space-x-2 rounded-lg border border-border/80 bg-muted/30 p-2.5 h-14">
|
||||
<div className="space-y-0.5 min-w-0 pr-2">
|
||||
<Label
|
||||
htmlFor="create-is-agent-task"
|
||||
className="text-xs font-medium cursor-pointer flex items-center gap-1.5"
|
||||
>
|
||||
<Bot className="w-3.5 h-3.5 text-orange-500" />
|
||||
<span>{m.task_type_agent()}</span>
|
||||
</Label>
|
||||
<p className="text-[11px] text-muted-foreground line-clamp-1">
|
||||
{m.task_type_agent_desc()}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="create-is-agent-task"
|
||||
checked={isAgentTask}
|
||||
onCheckedChange={(checked) => {
|
||||
setIsAgentTask(checked)
|
||||
setAssigneeId('none')
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Row 2: Priority and Goal selectors */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">
|
||||
{m.task_priority()}
|
||||
</Label>
|
||||
<Select
|
||||
value={priority}
|
||||
onValueChange={(val) => setPriority(val as KanbanTaskPriority)}
|
||||
>
|
||||
<SelectTrigger className="w-full h-9 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.values(KanbanTaskPriority).map((p) => (
|
||||
<SelectItem key={p} value={p}>
|
||||
<span
|
||||
className={cn(
|
||||
'px-1.5 py-0.5 rounded text-[10px] uppercase font-medium',
|
||||
getPriorityBadgeColor(p),
|
||||
)}
|
||||
>
|
||||
{getPriorityLabel(p)}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">{m.goals()}</Label>
|
||||
<Select value={goalId} onValueChange={setGoalId}>
|
||||
<SelectTrigger className="w-full h-9 text-xs">
|
||||
<SelectValue placeholder="None" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">
|
||||
<span className="text-muted-foreground italic">None</span>
|
||||
</SelectItem>
|
||||
{goals
|
||||
.filter((g) => g.id !== UNASSIGNED_GOAL_ID)
|
||||
.map((g) => (
|
||||
<SelectItem key={g.id} value={g.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Target className="w-3.5 h-3.5 text-primary" />
|
||||
<span>{g.title}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Row 3: Assignee and Reporter */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">
|
||||
{isAgentic ? m.select_agent() : m.assignee()}
|
||||
</Label>
|
||||
<Select value={assigneeId} onValueChange={setAssigneeId}>
|
||||
<SelectTrigger className="w-full h-9 text-xs">
|
||||
<SelectValue placeholder={m.unassigned()} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">
|
||||
<span className="text-muted-foreground italic">{m.unassigned()}</span>
|
||||
</SelectItem>
|
||||
{isAgentic
|
||||
? agents.map((a) => (
|
||||
<SelectItem key={a.id} value={a.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Bot className="w-3.5 h-3.5 text-purple-500" />
|
||||
<span>{a.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))
|
||||
: members.map((mItem) => (
|
||||
<SelectItem key={mItem.id} value={mItem.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar size="sm" className="w-4 h-4">
|
||||
<AvatarImage src={mItem.image} />
|
||||
<AvatarFallback className="text-[8px]">
|
||||
{mItem.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{mItem.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">{m.reporter()}</Label>
|
||||
<Select value={reporterId} onValueChange={setReporterId}>
|
||||
<SelectTrigger className="w-full h-9 text-xs">
|
||||
<SelectValue placeholder={m.unassigned()} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">
|
||||
<span className="text-muted-foreground italic">{m.unassigned()}</span>
|
||||
</SelectItem>
|
||||
{members.map((mItem) => (
|
||||
<SelectItem key={mItem.id} value={mItem.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar size="sm" className="w-4 h-4">
|
||||
<AvatarImage src={mItem.image} />
|
||||
<AvatarFallback className="text-[8px]">
|
||||
{mItem.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{mItem.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Row 4: Target Folder Selector (only for agent task) */}
|
||||
{isAgentic && (
|
||||
<div className="sm:col-span-2 space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">
|
||||
{m.target_folder()}
|
||||
</Label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setIsFolderPickerOpen(true)}
|
||||
className="w-full justify-start h-9 text-xs truncate font-normal"
|
||||
>
|
||||
<Folder className="w-3.5 h-3.5 mr-2 text-primary shrink-0" />
|
||||
<span className="truncate">{targetFolderName || m.select_target_folder()}</span>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Row 5: Start Date and Due Date */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">
|
||||
{m.start_date()}
|
||||
</Label>
|
||||
<DateTimePicker
|
||||
value={startDate}
|
||||
onChange={setStartDate}
|
||||
placeholder={m.start_date()}
|
||||
className="h-9 text-xs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">{m.due_date()}</Label>
|
||||
<DateTimePicker
|
||||
value={dueDate}
|
||||
onChange={setDueDate}
|
||||
placeholder={m.due_date()}
|
||||
className="h-9 text-xs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Row 6: Parent Tasks */}
|
||||
<div className="sm:col-span-2 space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground">
|
||||
{m.parent_tasks()}
|
||||
</Label>
|
||||
<TaskParentSelector teamId={teamId} value={parentIds} onChange={setParentIds} />
|
||||
</div>
|
||||
|
||||
{/* Row 7: Related Assets */}
|
||||
<div className="sm:col-span-2 pt-1">
|
||||
<TaskRelatedAssets
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
assets={selectedAssets}
|
||||
onAddAssets={(newAssets) => setSelectedAssets((prev) => [...prev, ...newAssets])}
|
||||
onRemoveAsset={(assetId) =>
|
||||
setSelectedAssets((prev) => prev.filter((a) => a.id !== assetId))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={isPending}>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button type="submit" disabled={!title.trim() || isPending}>
|
||||
{isPending && <Loader2 className="w-4 h-4 mr-1.5 animate-spin" />}
|
||||
{m.create()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
|
||||
{/* Target Folder Dialog */}
|
||||
{isFolderPickerOpen && (
|
||||
<TaskTargetFolderDialog
|
||||
teamId={teamId}
|
||||
currentProjectId={projectId}
|
||||
currentTargetFolderId={targetFolderId}
|
||||
isOpen={isFolderPickerOpen}
|
||||
onClose={() => setIsFolderPickerOpen(false)}
|
||||
onSelect={(projId, foldId, foldName) => {
|
||||
setProjectId(projId)
|
||||
setTargetFolderId(foldId)
|
||||
setTargetFolderName(foldName || 'Selected Folder')
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import {
|
||||
Target,
|
||||
Plus,
|
||||
MoreHorizontal,
|
||||
Edit2,
|
||||
Trash2,
|
||||
ListTodo,
|
||||
Loader2,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { type KanbanGoalInfo, UNASSIGNED_GOAL_ID } from '@shumai/dtos'
|
||||
import { KanbanCreateGoalDialog } from './kanban-create-goal-dialog'
|
||||
|
||||
interface KanbanGoalSidebarProps {
|
||||
teamId: string
|
||||
selectedGoalId: string | null
|
||||
onSelectGoal: (goalId: string | null) => void
|
||||
isOwnerOrEditor?: boolean
|
||||
}
|
||||
|
||||
export function KanbanGoalSidebar({
|
||||
teamId,
|
||||
selectedGoalId,
|
||||
onSelectGoal,
|
||||
isOwnerOrEditor = true,
|
||||
}: KanbanGoalSidebarProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [isCreateGoalOpen, setIsCreateGoalOpen] = useState(false)
|
||||
const [goalToEdit, setGoalToEdit] = useState<KanbanGoalInfo | null>(null)
|
||||
const [goalToDelete, setGoalToDelete] = useState<KanbanGoalInfo | null>(null)
|
||||
const [isCollapsed, setIsCollapsed] = useState(false)
|
||||
|
||||
const { data: goalsData, isLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'goals'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.goals.$get({
|
||||
param: { teamId },
|
||||
query: {},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch goals')
|
||||
return (await res.json()) as { data: KanbanGoalInfo[] }
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
const goals = goalsData?.data || []
|
||||
const totalGoalTasks = goals.reduce((acc, g) => acc + (g.taskCount || 0), 0)
|
||||
|
||||
const { mutate: deleteGoal, isPending: isDeleting } = useMutation({
|
||||
mutationFn: async (goalId: string) => {
|
||||
const res = await client.api.teams[':teamId'].kanban.goals[':goalId'].$delete({
|
||||
param: { teamId, goalId },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: m.error() }))
|
||||
throw new Error((err as { message?: string }).message || m.error())
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: (_, deletedGoalId) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'goals'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'kanban', 'tasks'] })
|
||||
toast.success(m.goal_deleted())
|
||||
if (selectedGoalId === deletedGoalId) {
|
||||
onSelectGoal(null)
|
||||
}
|
||||
setGoalToDelete(null)
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
if (isCollapsed) {
|
||||
return (
|
||||
<div className="border-r border-sidebar-border bg-sidebar flex flex-col items-center w-12 shrink-0 transition-all duration-300">
|
||||
<div className="h-14 flex items-center justify-center border-b border-sidebar-border w-full shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setIsCollapsed(false)}
|
||||
title={m.goals()}
|
||||
className="text-sidebar-foreground/70 hover:text-sidebar-foreground"
|
||||
>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-col items-center gap-2">
|
||||
<Button
|
||||
variant={selectedGoalId === null ? 'secondary' : 'ghost'}
|
||||
size="icon-sm"
|
||||
onClick={() => onSelectGoal(null)}
|
||||
title={m.all_tasks()}
|
||||
className={cn(
|
||||
'w-8 h-8 rounded-md',
|
||||
selectedGoalId === null && 'bg-sidebar-accent text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<ListTodo className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setIsCreateGoalOpen(true)}
|
||||
title={m.new_goal()}
|
||||
className="w-8 h-8 rounded-md text-sidebar-foreground/70 hover:text-sidebar-foreground"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isCreateGoalOpen && (
|
||||
<KanbanCreateGoalDialog
|
||||
teamId={teamId}
|
||||
isOpen={isCreateGoalOpen}
|
||||
onClose={() => setIsCreateGoalOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<aside className="w-64 border-r border-sidebar-border bg-sidebar flex flex-col shrink-0 transition-all duration-300 select-none">
|
||||
{/* Sidebar Header */}
|
||||
<div className="h-14 px-3 flex items-center justify-between border-b border-sidebar-border shrink-0">
|
||||
<div className="flex items-center gap-2 font-semibold text-xs tracking-wider uppercase text-sidebar-foreground/70">
|
||||
<Target className="w-4 h-4 text-sidebar-primary" />
|
||||
<span>{m.goals()}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
{isOwnerOrEditor && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setIsCreateGoalOpen(true)}
|
||||
className="h-7 w-7 text-sidebar-foreground/70 hover:text-sidebar-foreground"
|
||||
title={m.new_goal()}
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setIsCollapsed(true)}
|
||||
className="h-7 w-7 text-sidebar-foreground/70 hover:text-sidebar-foreground"
|
||||
title="Collapse"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Goals List */}
|
||||
<ScrollArea className="flex-1 p-2">
|
||||
<div className="space-y-1">
|
||||
{/* All Tasks Item */}
|
||||
<div
|
||||
onClick={() => onSelectGoal(null)}
|
||||
className={cn(
|
||||
'flex items-center justify-between px-2.5 py-1 rounded-md text-xs font-medium cursor-pointer transition-colors group h-8 min-h-[32px]',
|
||||
selectedGoalId === null
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground font-semibold shadow-xs'
|
||||
: 'text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 truncate min-w-0">
|
||||
<ListTodo className="w-3.5 h-3.5 shrink-0 text-sidebar-primary" />
|
||||
<span className="truncate">{m.all_tasks()}</span>
|
||||
</div>
|
||||
{totalGoalTasks > 0 && (
|
||||
<span className="text-[10px] font-mono px-1.5 py-0.5 rounded-full bg-sidebar-border text-sidebar-foreground/60 shrink-0">
|
||||
{totalGoalTasks}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Goal Items */}
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center p-4">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : goals.length === 0 ? (
|
||||
<div className="px-2.5 py-4 text-center text-xs text-muted-foreground">
|
||||
{m.no_goals_yet()}
|
||||
</div>
|
||||
) : (
|
||||
goals.map((goal) => {
|
||||
const isSelected = selectedGoalId === goal.id
|
||||
const isUnassigned = goal.id === UNASSIGNED_GOAL_ID
|
||||
const title = isUnassigned ? m.unassigned() : goal.title
|
||||
const hasActions = isOwnerOrEditor && !isUnassigned
|
||||
return (
|
||||
<div
|
||||
key={goal.id}
|
||||
onClick={() => onSelectGoal(goal.id)}
|
||||
className={cn(
|
||||
'flex items-center justify-between px-2.5 py-1 rounded-md text-xs font-medium cursor-pointer transition-colors group relative min-h-[32px]',
|
||||
isSelected
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground font-semibold shadow-xs'
|
||||
: 'text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
<Target
|
||||
className={cn(
|
||||
'w-3.5 h-3.5 shrink-0',
|
||||
isSelected ? 'text-sidebar-primary' : 'text-muted-foreground',
|
||||
)}
|
||||
/>
|
||||
<span className="line-clamp-2 break-words leading-tight" title={title}>
|
||||
{title}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center shrink-0 ml-1">
|
||||
{hasActions ? (
|
||||
<>
|
||||
{(goal.taskCount ?? 0) > 0 && (
|
||||
<span className="text-[10px] font-mono px-1.5 py-0.5 rounded-full bg-sidebar-border text-sidebar-foreground/60 group-hover:hidden group-focus-within:hidden [&:has(~_div_[data-state=open])]:hidden">
|
||||
{goal.taskCount}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<div
|
||||
className="hidden group-hover:flex group-focus-within:flex [&:has([data-state=open])]:flex items-center"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="h-6 w-6 p-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<MoreHorizontal className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-36">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setGoalToEdit(goal)
|
||||
}}
|
||||
>
|
||||
<Edit2 className="w-3.5 h-3.5 mr-2" />
|
||||
{m.edit()}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive focus:bg-destructive/10"
|
||||
onClick={() => {
|
||||
setGoalToDelete(goal)
|
||||
}}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5 mr-2" />
|
||||
{m.delete()}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
(goal.taskCount ?? 0) > 0 && (
|
||||
<span className="text-[10px] font-mono px-1.5 py-0.5 rounded-full bg-sidebar-border text-sidebar-foreground/60">
|
||||
{goal.taskCount}
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
{/* Create / Edit Goal Dialog */}
|
||||
{(isCreateGoalOpen || goalToEdit) && (
|
||||
<KanbanCreateGoalDialog
|
||||
teamId={teamId}
|
||||
isOpen={isCreateGoalOpen || !!goalToEdit}
|
||||
goalToEdit={goalToEdit}
|
||||
onClose={() => {
|
||||
setIsCreateGoalOpen(false)
|
||||
setGoalToEdit(null)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Delete Goal Confirmation */}
|
||||
{goalToDelete && (
|
||||
<AlertDialog open={!!goalToDelete} onOpenChange={(open) => !open && setGoalToDelete(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{m.delete_goal()}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{m.delete_goal_confirm({ title: goalToDelete.title })}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isDeleting}>{m.cancel()}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => deleteGoal(goalToDelete.id)}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting && <Loader2 className="w-4 h-4 mr-1.5 animate-spin" />}
|
||||
{m.delete()}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Users, User, Plus, Target, X } from 'lucide-react'
|
||||
import { type KanbanGoalInfo, UNASSIGNED_GOAL_ID } from '@shumai/dtos'
|
||||
|
||||
interface KanbanHeaderProps {
|
||||
scope: 'team' | 'my'
|
||||
onScopeChange: (scope: 'team' | 'my') => void
|
||||
selectedGoal: KanbanGoalInfo | null
|
||||
onClearGoal: () => void
|
||||
onCreateTask: () => void
|
||||
}
|
||||
|
||||
export function KanbanHeader({
|
||||
scope,
|
||||
onScopeChange,
|
||||
selectedGoal,
|
||||
onClearGoal,
|
||||
onCreateTask,
|
||||
}: KanbanHeaderProps) {
|
||||
return (
|
||||
<header className="h-14 border-b border-border bg-card/60 backdrop-blur-sm px-4 flex items-center justify-between gap-3 shrink-0 select-none">
|
||||
{/* Left side: Scope switcher & Goal indicator */}
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
{/* Scope Toggle (Team vs My Tasks) */}
|
||||
<div className="flex items-center bg-muted/60 p-0.5 rounded-lg border border-border/50">
|
||||
<Button
|
||||
variant={scope === 'team' ? 'secondary' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => onScopeChange('team')}
|
||||
className={`h-7 px-2.5 text-xs font-medium gap-1.5 transition-all ${
|
||||
scope === 'team'
|
||||
? 'bg-background text-foreground shadow-xs'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
<Users className="w-3.5 h-3.5" />
|
||||
<span>{m.team_tasks()}</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant={scope === 'my' ? 'secondary' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => onScopeChange('my')}
|
||||
className={`h-7 px-2.5 text-xs font-medium gap-1.5 transition-all ${
|
||||
scope === 'my'
|
||||
? 'bg-background text-foreground shadow-xs'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
<User className="w-3.5 h-3.5" />
|
||||
<span>{m.my_tasks()}</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Selected Goal Filter Badge */}
|
||||
{selectedGoal && (
|
||||
<div className="hidden sm:flex items-center gap-1.5 px-2 py-1 rounded-md bg-sidebar-accent border border-sidebar-border text-xs text-sidebar-accent-foreground min-w-0 max-w-[200px] md:max-w-[280px]">
|
||||
<Target className="w-3.5 h-3.5 text-sidebar-primary shrink-0" />
|
||||
<span className="truncate font-medium">
|
||||
{selectedGoal.id === UNASSIGNED_GOAL_ID ? m.unassigned() : selectedGoal.title}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
onClick={onClearGoal}
|
||||
className="h-4 w-4 p-0 ml-0.5 text-muted-foreground hover:text-foreground"
|
||||
title={m.clear_filter()}
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right side: Create button */}
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{/* Create Task Button */}
|
||||
<Button size="sm" onClick={onCreateTask} className="h-8 px-3 text-xs gap-1.5 shadow-xs">
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
<span>{m.create_task()}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { KanbanTaskStatus, type KanbanGoalInfo, type KanbanTaskInfo } from '@shumai/dtos'
|
||||
import { KanbanHeader } from './kanban-header'
|
||||
import { KanbanGoalSidebar } from './kanban-goal-sidebar'
|
||||
import { KanbanBoard } from './kanban-board'
|
||||
import { KanbanCreateTaskDialog } from './kanban-create-task-dialog'
|
||||
import { EditTaskDialog } from './edit-task-dialog/edit-task-dialog'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
|
||||
interface KanbanPageProps {
|
||||
teamId: string
|
||||
initialTaskId?: string
|
||||
}
|
||||
|
||||
export function KanbanPage({ teamId, initialTaskId }: KanbanPageProps) {
|
||||
const [scope, setScope] = useState<'team' | 'my'>('team')
|
||||
const [selectedGoalId, setSelectedGoalId] = useState<string | null>(null)
|
||||
const [editingTaskId, setEditingTaskId] = useState<string | null>(initialTaskId ?? null)
|
||||
const [isCreateTaskOpen, setIsCreateTaskOpen] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (initialTaskId) {
|
||||
setEditingTaskId(initialTaskId)
|
||||
}
|
||||
}, [initialTaskId])
|
||||
const [createTaskInitialStatus, setCreateTaskInitialStatus] = useState<KanbanTaskStatus>(
|
||||
KanbanTaskStatus.TODO,
|
||||
)
|
||||
|
||||
// Query Current User Role & Info in Team
|
||||
const { data: me, isLoading: isLoadingMe } = useQuery({
|
||||
queryKey: ['teams', teamId, 'me'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].me.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch me')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
// Query Goals for active goal object lookup
|
||||
const { data: goalsData } = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'goals'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.goals.$get({
|
||||
param: { teamId },
|
||||
query: {},
|
||||
})
|
||||
if (!res.ok) return { data: [] }
|
||||
return (await res.json()) as { data: KanbanGoalInfo[] }
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
const goals = goalsData?.data || []
|
||||
const selectedGoal = selectedGoalId ? goals.find((g) => g.id === selectedGoalId) || null : null
|
||||
|
||||
const isOwnerOrEditor =
|
||||
me?.role?.toLowerCase() === 'owner' || me?.role?.toLowerCase() === 'editor'
|
||||
|
||||
const handleOpenCreateTask = (status: KanbanTaskStatus = KanbanTaskStatus.TODO) => {
|
||||
setCreateTaskInitialStatus(status)
|
||||
setIsCreateTaskOpen(true)
|
||||
}
|
||||
|
||||
const handleTaskClick = (task: KanbanTaskInfo) => {
|
||||
setEditingTaskId(task.id)
|
||||
}
|
||||
|
||||
if (isLoadingMe) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-row h-full bg-background overflow-hidden font-sans">
|
||||
{/* Left Sidebar: Goals (Full Height) */}
|
||||
<KanbanGoalSidebar
|
||||
teamId={teamId}
|
||||
selectedGoalId={selectedGoalId}
|
||||
onSelectGoal={setSelectedGoalId}
|
||||
isOwnerOrEditor={isOwnerOrEditor}
|
||||
/>
|
||||
|
||||
{/* Right Column: Top Header Bar + Kanban Board */}
|
||||
<div className="flex-1 flex flex-col min-w-0 h-full overflow-hidden">
|
||||
<KanbanHeader
|
||||
scope={scope}
|
||||
onScopeChange={setScope}
|
||||
selectedGoal={selectedGoal}
|
||||
onClearGoal={() => setSelectedGoalId(null)}
|
||||
onCreateTask={() => handleOpenCreateTask(KanbanTaskStatus.TODO)}
|
||||
/>
|
||||
|
||||
<KanbanBoard
|
||||
teamId={teamId}
|
||||
selectedGoalId={selectedGoalId}
|
||||
scope={scope}
|
||||
currentUserId={me?.id}
|
||||
currentUserRole={me?.role}
|
||||
onTaskClick={handleTaskClick}
|
||||
onCreateTaskInColumn={(status) => handleOpenCreateTask(status)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Edit Task Dialog */}
|
||||
{editingTaskId && (
|
||||
<EditTaskDialog
|
||||
teamId={teamId}
|
||||
taskId={editingTaskId}
|
||||
isOpen={!!editingTaskId}
|
||||
onClose={() => setEditingTaskId(null)}
|
||||
canEdit={isOwnerOrEditor}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Create Task Dialog */}
|
||||
{isCreateTaskOpen && (
|
||||
<KanbanCreateTaskDialog
|
||||
teamId={teamId}
|
||||
isOpen={isCreateTaskOpen}
|
||||
initialStatus={createTaskInitialStatus}
|
||||
initialGoalId={selectedGoalId}
|
||||
onClose={() => setIsCreateTaskOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { KanbanTaskPriority, KanbanTaskStatus } from '@shumai/dtos'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
export const KANBAN_STATUS_COLUMNS: KanbanTaskStatus[] = [
|
||||
KanbanTaskStatus.TODO,
|
||||
KanbanTaskStatus.READY,
|
||||
KanbanTaskStatus.IN_PROGRESS,
|
||||
KanbanTaskStatus.BLOCKED,
|
||||
KanbanTaskStatus.IN_REVIEW,
|
||||
KanbanTaskStatus.DONE,
|
||||
]
|
||||
|
||||
export function getStatusLabel(status: KanbanTaskStatus): string {
|
||||
switch (status) {
|
||||
case KanbanTaskStatus.TODO:
|
||||
return m.status_todo()
|
||||
case KanbanTaskStatus.READY:
|
||||
return m.status_ready()
|
||||
case KanbanTaskStatus.IN_PROGRESS:
|
||||
return m.status_in_progress()
|
||||
case KanbanTaskStatus.BLOCKED:
|
||||
return m.status_blocked()
|
||||
case KanbanTaskStatus.IN_REVIEW:
|
||||
return m.status_in_review()
|
||||
case KanbanTaskStatus.DONE:
|
||||
return m.status_done()
|
||||
default:
|
||||
return status
|
||||
}
|
||||
}
|
||||
|
||||
export function getStatusColor(status: KanbanTaskStatus): {
|
||||
badge: string
|
||||
border: string
|
||||
dot: string
|
||||
bg: string
|
||||
} {
|
||||
switch (status) {
|
||||
case KanbanTaskStatus.TODO:
|
||||
return {
|
||||
badge: 'bg-muted text-muted-foreground border-border',
|
||||
border: 'border-border',
|
||||
dot: 'bg-muted-foreground',
|
||||
bg: 'bg-muted/30',
|
||||
}
|
||||
case KanbanTaskStatus.READY:
|
||||
return {
|
||||
badge: 'bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20',
|
||||
border: 'border-blue-500/30',
|
||||
dot: 'bg-blue-500',
|
||||
bg: 'bg-blue-500/5',
|
||||
}
|
||||
case KanbanTaskStatus.IN_PROGRESS:
|
||||
return {
|
||||
badge: 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20',
|
||||
border: 'border-amber-500/30',
|
||||
dot: 'bg-amber-500',
|
||||
bg: 'bg-amber-500/5',
|
||||
}
|
||||
case KanbanTaskStatus.BLOCKED:
|
||||
return {
|
||||
badge: 'bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20',
|
||||
border: 'border-red-500/30',
|
||||
dot: 'bg-red-500',
|
||||
bg: 'bg-red-500/5',
|
||||
}
|
||||
case KanbanTaskStatus.IN_REVIEW:
|
||||
return {
|
||||
badge: 'bg-purple-500/10 text-purple-600 dark:text-purple-400 border-purple-500/20',
|
||||
border: 'border-purple-500/30',
|
||||
dot: 'bg-purple-500',
|
||||
bg: 'bg-purple-500/5',
|
||||
}
|
||||
case KanbanTaskStatus.DONE:
|
||||
return {
|
||||
badge: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20',
|
||||
border: 'border-emerald-500/30',
|
||||
dot: 'bg-emerald-500',
|
||||
bg: 'bg-emerald-500/5',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getStatusBadgeColor(status: KanbanTaskStatus): string {
|
||||
return getStatusColor(status).badge
|
||||
}
|
||||
|
||||
export function getPriorityLabel(priority: KanbanTaskPriority): string {
|
||||
switch (priority) {
|
||||
case KanbanTaskPriority.LOW:
|
||||
return m.priority_low()
|
||||
case KanbanTaskPriority.MEDIUM:
|
||||
return m.priority_medium()
|
||||
case KanbanTaskPriority.HIGH:
|
||||
return m.priority_high()
|
||||
case KanbanTaskPriority.URGENT:
|
||||
return m.priority_urgent()
|
||||
default:
|
||||
return priority
|
||||
}
|
||||
}
|
||||
|
||||
export function getPriorityBadgeColor(priority: KanbanTaskPriority): string {
|
||||
switch (priority) {
|
||||
case KanbanTaskPriority.LOW:
|
||||
return 'bg-muted text-muted-foreground border-border'
|
||||
case KanbanTaskPriority.MEDIUM:
|
||||
return 'bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20'
|
||||
case KanbanTaskPriority.HIGH:
|
||||
return 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20'
|
||||
case KanbanTaskPriority.URGENT:
|
||||
return 'bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20 font-semibold'
|
||||
default:
|
||||
return 'bg-muted text-muted-foreground border-border'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,771 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React from 'react'
|
||||
import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import {
|
||||
KanbanTaskPriority,
|
||||
KanbanTaskStatus,
|
||||
KanbanTaskEventType,
|
||||
type KanbanTaskInfo,
|
||||
type KanbanGoalInfo,
|
||||
type KanbanCommentInfo,
|
||||
UNASSIGNED_GOAL_ID,
|
||||
} from '@shumai/dtos'
|
||||
import {
|
||||
getStatusLabel,
|
||||
getStatusColor,
|
||||
getStatusBadgeColor,
|
||||
getPriorityLabel,
|
||||
getPriorityBadgeColor,
|
||||
} from './kanban-types'
|
||||
import { KanbanCard } from './kanban-card'
|
||||
import { KanbanHeader } from './kanban-header'
|
||||
import { KanbanBoard } from './kanban-board'
|
||||
import { KanbanGoalSidebar } from './kanban-goal-sidebar'
|
||||
import { KanbanCreateGoalDialog } from './kanban-create-goal-dialog'
|
||||
import { KanbanCreateTaskDialog } from './kanban-create-task-dialog'
|
||||
import { TaskRelatedAssets } from './task-related-assets'
|
||||
import { TaskCommentCard } from './edit-task-dialog/task-comment-card'
|
||||
import { TaskCommentInput } from './edit-task-dialog/task-comment-input'
|
||||
import type { KanbanTaskAssetInfo } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
|
||||
const mockUseDraggable = vi.fn()
|
||||
|
||||
// Mock @dnd-kit/react
|
||||
vi.mock('@dnd-kit/react', () => ({
|
||||
useDraggable: (args: unknown) => {
|
||||
mockUseDraggable(args)
|
||||
return {
|
||||
ref: vi.fn(),
|
||||
isDragging: false,
|
||||
}
|
||||
},
|
||||
useDroppable: () => ({
|
||||
ref: vi.fn(),
|
||||
isDropTarget: false,
|
||||
}),
|
||||
useDragOperation: () => ({
|
||||
source: null,
|
||||
target: null,
|
||||
}),
|
||||
DragDropProvider: ({ children }: { children?: React.ReactNode }) => children,
|
||||
PointerSensor: {
|
||||
configure: () => ({}),
|
||||
},
|
||||
KeyboardSensor: {},
|
||||
}))
|
||||
|
||||
// Mock @dnd-kit/dom
|
||||
vi.mock('@dnd-kit/dom', () => ({
|
||||
PointerActivationConstraints: {
|
||||
Distance: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
// Mock API client
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
teams: {
|
||||
':teamId': {
|
||||
kanban: {
|
||||
goals: {
|
||||
$get: vi.fn(),
|
||||
$post: vi.fn(),
|
||||
':goalId': {
|
||||
$patch: vi.fn(),
|
||||
$delete: vi.fn(),
|
||||
},
|
||||
},
|
||||
tasks: {
|
||||
$get: vi.fn(),
|
||||
$post: vi.fn(),
|
||||
':taskId': {
|
||||
$patch: vi.fn(),
|
||||
$delete: vi.fn(),
|
||||
},
|
||||
},
|
||||
},
|
||||
members: {
|
||||
$get: vi.fn().mockResolvedValue({ ok: true, json: async () => [] }),
|
||||
},
|
||||
agents: {
|
||||
$get: vi.fn().mockResolvedValue({ ok: true, json: async () => [] }),
|
||||
},
|
||||
me: {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'u-1', name: 'User 1', role: 'owner' }),
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('Kanban UI Unit & Component Tests', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('Kanban Helpers & Type Utilities', () => {
|
||||
it('maps status to correct labels and semantic badge colors', () => {
|
||||
expect(getStatusLabel(KanbanTaskStatus.TODO)).toBeDefined()
|
||||
expect(getStatusLabel(KanbanTaskStatus.READY)).toBeDefined()
|
||||
expect(getStatusLabel(KanbanTaskStatus.IN_PROGRESS)).toBeDefined()
|
||||
expect(getStatusLabel(KanbanTaskStatus.BLOCKED)).toBeDefined()
|
||||
expect(getStatusLabel(KanbanTaskStatus.IN_REVIEW)).toBeDefined()
|
||||
expect(getStatusLabel(KanbanTaskStatus.DONE)).toBeDefined()
|
||||
|
||||
expect(getStatusColor(KanbanTaskStatus.READY).badge).toBeDefined()
|
||||
expect(getStatusBadgeColor(KanbanTaskStatus.BLOCKED)).toContain('red')
|
||||
})
|
||||
|
||||
it('maps priority to labels and colors', () => {
|
||||
expect(getPriorityLabel(KanbanTaskPriority.LOW)).toBeDefined()
|
||||
expect(getPriorityLabel(KanbanTaskPriority.URGENT)).toBeDefined()
|
||||
expect(getPriorityBadgeColor(KanbanTaskPriority.URGENT)).toContain('red')
|
||||
})
|
||||
})
|
||||
|
||||
describe('KanbanCard component', () => {
|
||||
const mockManualTask: KanbanTaskInfo = {
|
||||
id: 'task-1',
|
||||
title: 'Manual Human Task',
|
||||
description: 'Test description',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.TODO,
|
||||
priority: KanbanTaskPriority.HIGH,
|
||||
startDate: null,
|
||||
dueDate: '2026-12-31T23:59:59.000Z',
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
teamId: 'team-1',
|
||||
projectId: null,
|
||||
creator: { id: 'user-1', name: 'Alice' },
|
||||
reporter: null,
|
||||
assignee: { id: 'user-2', name: 'Bob' },
|
||||
goal: { id: 'goal-1', title: 'Q3 Goal' },
|
||||
targetFolderId: null,
|
||||
latestStatusEvent: null,
|
||||
commentCount: 3,
|
||||
dependencyCount: 1,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: '2026-08-20T00:00:00.000Z',
|
||||
updatedAt: '2026-08-20T00:00:00.000Z',
|
||||
}
|
||||
|
||||
const mockAgenticTask: KanbanTaskInfo = {
|
||||
...mockManualTask,
|
||||
id: 'task-2',
|
||||
title: 'Autonomous Agent Task',
|
||||
isAgentTask: true,
|
||||
status: KanbanTaskStatus.IN_PROGRESS,
|
||||
}
|
||||
|
||||
it('renders human task card correctly without agent task label', () => {
|
||||
const onClick = vi.fn()
|
||||
render(<KanbanCard task={mockManualTask} onClick={onClick} />)
|
||||
|
||||
expect(screen.getByText('Manual Human Task')).toBeDefined()
|
||||
expect(screen.getByText('Bob')).toBeDefined()
|
||||
expect(screen.getByText('Q3 Goal')).toBeDefined()
|
||||
expect(screen.getByText('3')).toBeDefined() // Comments count
|
||||
expect(screen.getByText('1')).toBeDefined() // Dependency count
|
||||
expect(screen.queryByText(/Agent Task|智能体任务/i)).toBeNull()
|
||||
|
||||
fireEvent.click(screen.getByText('Manual Human Task'))
|
||||
expect(onClick).toHaveBeenCalledWith(mockManualTask)
|
||||
})
|
||||
|
||||
it('renders agent task card with Agent Task label in orange style and standard card border', () => {
|
||||
const onClick = vi.fn()
|
||||
const { container } = render(<KanbanCard task={mockAgenticTask} onClick={onClick} />)
|
||||
|
||||
expect(screen.getByText('Autonomous Agent Task')).toBeDefined()
|
||||
const agentBadge = screen.getByText(/^Agent Task$|^智能体任务$/i)
|
||||
expect(agentBadge).toBeDefined()
|
||||
expect(agentBadge.parentElement?.className).toContain('text-orange-600')
|
||||
// Verify card container uses standard border, not purple border highlight
|
||||
const card = container.querySelector('.border-border\\/80')
|
||||
expect(card).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders three-dot delete action for task creator or owner and triggers onDelete', () => {
|
||||
const onDelete = vi.fn()
|
||||
const { container, rerender } = render(
|
||||
<KanbanCard
|
||||
task={mockManualTask}
|
||||
onClick={vi.fn()}
|
||||
onDelete={onDelete}
|
||||
currentUserId="user-1" // mockManualTask creator is user-1
|
||||
currentUserRole="reviewer"
|
||||
/>,
|
||||
)
|
||||
|
||||
// Three-dot trigger should be rendered
|
||||
const triggerBtn = container.querySelector('button')
|
||||
expect(triggerBtn).toBeDefined()
|
||||
|
||||
// When user is not creator and not owner, delete trigger is not rendered
|
||||
rerender(
|
||||
<KanbanCard
|
||||
task={mockManualTask}
|
||||
onClick={vi.fn()}
|
||||
onDelete={onDelete}
|
||||
currentUserId="other-user"
|
||||
currentUserRole="reviewer"
|
||||
/>,
|
||||
)
|
||||
expect(container.querySelector('button')).toBeNull()
|
||||
})
|
||||
|
||||
it('enforces card drag permission: enabled for owner, reporter, or assignee; disabled for others', () => {
|
||||
// 1. Enabled when user is owner
|
||||
render(
|
||||
<KanbanCard
|
||||
task={{
|
||||
...mockManualTask,
|
||||
creator: { id: 'other', name: 'Other' },
|
||||
reporter: null,
|
||||
assignee: null,
|
||||
}}
|
||||
onClick={vi.fn()}
|
||||
currentUserRole="owner"
|
||||
currentUserId="random-user"
|
||||
/>,
|
||||
)
|
||||
expect(mockUseDraggable).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ disabled: false }),
|
||||
)
|
||||
|
||||
// 2. Enabled when user is reporter (or creator if reporter null)
|
||||
render(
|
||||
<KanbanCard
|
||||
task={{
|
||||
...mockManualTask,
|
||||
creator: { id: 'user-reporter', name: 'Rep' },
|
||||
reporter: null,
|
||||
assignee: null,
|
||||
}}
|
||||
onClick={vi.fn()}
|
||||
currentUserRole="editor"
|
||||
currentUserId="user-reporter"
|
||||
/>,
|
||||
)
|
||||
expect(mockUseDraggable).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ disabled: false }),
|
||||
)
|
||||
|
||||
// 3. Enabled when user is assignee
|
||||
render(
|
||||
<KanbanCard
|
||||
task={{
|
||||
...mockManualTask,
|
||||
creator: { id: 'other', name: 'Other' },
|
||||
reporter: null,
|
||||
assignee: { id: 'user-assignee', name: 'Assignee' },
|
||||
}}
|
||||
onClick={vi.fn()}
|
||||
currentUserRole="reviewer"
|
||||
currentUserId="user-assignee"
|
||||
/>,
|
||||
)
|
||||
expect(mockUseDraggable).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ disabled: false }),
|
||||
)
|
||||
|
||||
// 4. Disabled when user is not owner, not reporter, and not assignee
|
||||
render(
|
||||
<KanbanCard
|
||||
task={{
|
||||
...mockManualTask,
|
||||
creator: { id: 'other-1', name: 'Other' },
|
||||
reporter: { id: 'other-2', name: 'Reporter' },
|
||||
assignee: { id: 'other-3', name: 'Assignee' },
|
||||
}}
|
||||
onClick={vi.fn()}
|
||||
currentUserRole="editor"
|
||||
currentUserId="stranger-user"
|
||||
/>,
|
||||
)
|
||||
expect(mockUseDraggable).toHaveBeenLastCalledWith(expect.objectContaining({ disabled: true }))
|
||||
})
|
||||
|
||||
it('renders asset count badge when task has linked assets', () => {
|
||||
render(
|
||||
<KanbanCard
|
||||
task={{
|
||||
...mockManualTask,
|
||||
assetCount: 4,
|
||||
}}
|
||||
onClick={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('4')).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders blocked warning and reason when task is BLOCKED', () => {
|
||||
const blockedTask: KanbanTaskInfo = {
|
||||
...mockManualTask,
|
||||
status: KanbanTaskStatus.BLOCKED,
|
||||
latestStatusEvent: {
|
||||
id: 'event-1',
|
||||
type: KanbanTaskEventType.BLOCKED,
|
||||
blockReason: 'Missing API Key credentials',
|
||||
createdAt: '2026-08-20T00:00:00.000Z',
|
||||
},
|
||||
}
|
||||
|
||||
render(<KanbanCard task={blockedTask} onClick={vi.fn()} />)
|
||||
expect(screen.getByText('Missing API Key credentials')).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('KanbanHeader component', () => {
|
||||
it('handles scope switching and goal clearing', () => {
|
||||
const onScopeChange = vi.fn()
|
||||
const onClearGoal = vi.fn()
|
||||
const onCreateTask = vi.fn()
|
||||
|
||||
const selectedGoal: KanbanGoalInfo = {
|
||||
id: 'goal-1',
|
||||
title: 'Launch Goal',
|
||||
teamId: 'team-1',
|
||||
createdAt: '2026-08-20T00:00:00.000Z',
|
||||
updatedAt: '2026-08-20T00:00:00.000Z',
|
||||
}
|
||||
|
||||
render(
|
||||
<KanbanHeader
|
||||
scope="team"
|
||||
onScopeChange={onScopeChange}
|
||||
selectedGoal={selectedGoal}
|
||||
onClearGoal={onClearGoal}
|
||||
onCreateTask={onCreateTask}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Launch Goal')).toBeDefined()
|
||||
|
||||
// Click My Tasks
|
||||
const myTasksButtons = screen.getAllByRole('button')
|
||||
const myTaskBtn = myTasksButtons.find(
|
||||
(btn) => btn.textContent?.includes('My Tasks') || btn.textContent?.includes('我的任务'),
|
||||
)
|
||||
if (myTaskBtn) {
|
||||
fireEvent.click(myTaskBtn)
|
||||
expect(onScopeChange).toHaveBeenCalledWith('my')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('KanbanCreateGoalDialog component', () => {
|
||||
it('submits goal creation form', async () => {
|
||||
const mockPost = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'new-goal', title: 'New Goal' }),
|
||||
})
|
||||
// Mocking hono RPC client method for unit testing
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].kanban.goals.$post as any) = mockPost
|
||||
|
||||
const onClose = vi.fn()
|
||||
render(<KanbanCreateGoalDialog teamId="team-1" isOpen={true} onClose={onClose} />, {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
const titleInput = screen.getByLabelText(/Goal Title|目标标题/i)
|
||||
fireEvent.change(titleInput, { target: { value: 'Brand New Goal' } })
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: /Create|创建/i })
|
||||
fireEvent.click(submitBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockPost).toHaveBeenCalled()
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('TaskCommentCard and TaskCommentInput components', () => {
|
||||
it('renders comment with markdown and image/file attachments', () => {
|
||||
const mockComment: KanbanCommentInfo = {
|
||||
id: 'c-1',
|
||||
taskId: 't-1',
|
||||
author: { id: 'u-1', name: 'Alice Author' },
|
||||
body: 'Hello **bold** world',
|
||||
attachments: [
|
||||
{
|
||||
id: 'att-1',
|
||||
name: 'preview.png',
|
||||
sizeByte: 10240,
|
||||
url: 'https://example.com/preview.png',
|
||||
proxyType: 'image',
|
||||
},
|
||||
{
|
||||
id: 'att-2',
|
||||
name: 'specs.pdf',
|
||||
sizeByte: 20480,
|
||||
url: 'https://example.com/specs.pdf',
|
||||
proxyType: 'pdf',
|
||||
},
|
||||
],
|
||||
createdAt: '2026-08-20T00:00:00.000Z',
|
||||
updatedAt: '2026-08-20T00:00:00.000Z',
|
||||
}
|
||||
|
||||
const onViewAttachment = vi.fn()
|
||||
render(
|
||||
<TaskCommentCard
|
||||
teamId="team-1"
|
||||
taskId="t-1"
|
||||
comment={mockComment}
|
||||
currentUserId="u-1"
|
||||
isOwnerOrAdmin={true}
|
||||
onViewAttachment={onViewAttachment}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
expect(screen.getByText('Alice Author')).toBeDefined()
|
||||
expect(screen.getByText('bold')).toBeDefined()
|
||||
expect(screen.getByText('specs.pdf')).toBeDefined()
|
||||
|
||||
// Click image attachment
|
||||
const img = screen.getByAltText('preview.png')
|
||||
fireEvent.click(img)
|
||||
expect(onViewAttachment).toHaveBeenCalledWith(mockComment.attachments[0])
|
||||
})
|
||||
|
||||
it('renders TaskCommentInput and triggers send on button click', async () => {
|
||||
const onSendMessage = vi.fn()
|
||||
render(<TaskCommentInput teamId="team-1" onSendMessage={onSendMessage} />, {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/comment/i)
|
||||
fireEvent.change(textarea, { target: { value: 'New task comment' } })
|
||||
|
||||
const sendBtn = screen.getByTitle(/Send comment|发送/i)
|
||||
fireEvent.click(sendBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSendMessage).toHaveBeenCalledWith('New task comment', undefined)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('KanbanBoard component with mixed cache entries', () => {
|
||||
it('renders board and safely handles query cache with non-infinite task queries', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
|
||||
// Seed non-infinite task queries (like comments, events, dependency tasks) that do not have .pages
|
||||
queryClient.setQueryData(['teams', 'team-1', 'kanban', 'tasks', 't-1', 'comments'], {
|
||||
data: [{ id: 'c-1', body: 'Comment' }],
|
||||
})
|
||||
queryClient.setQueryData(['teams', 'team-1', 'kanban', 'tasks', 't-1', 'events'], {
|
||||
data: [{ id: 'e-1', type: 'CREATED' }],
|
||||
})
|
||||
queryClient.setQueryData(['teams', 'team-1', 'kanban', 'tasks', 'all'], {
|
||||
data: [{ id: 't-1', title: 'Task 1' }],
|
||||
})
|
||||
|
||||
// Mock tasks $get endpoint
|
||||
const mockGet = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: [],
|
||||
pageInfo: { total: 0, hasNextPage: false },
|
||||
}),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].kanban.tasks.$get as any) = mockGet
|
||||
|
||||
const onTaskClick = vi.fn()
|
||||
const onCreateTaskInColumn = vi.fn()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<KanbanBoard
|
||||
teamId="team-1"
|
||||
selectedGoalId={null}
|
||||
scope="team"
|
||||
onTaskClick={onTaskClick}
|
||||
onCreateTaskInColumn={onCreateTaskInColumn}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getByText(/To Do|待办/i)).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders reorder drop zones for drag-and-drop ordering', () => {
|
||||
const mockTask: KanbanTaskInfo = {
|
||||
id: 'task-1',
|
||||
title: 'Reorderable Task',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.TODO,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
startDate: null,
|
||||
dueDate: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
teamId: 'team-1',
|
||||
projectId: null,
|
||||
sortIndex: 'a0',
|
||||
creator: { id: 'user-1', name: 'Alice' },
|
||||
reporter: null,
|
||||
assignee: null,
|
||||
goal: null,
|
||||
targetFolderId: null,
|
||||
latestStatusEvent: null,
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: '2026-08-20T00:00:00.000Z',
|
||||
updatedAt: '2026-08-20T00:00:00.000Z',
|
||||
}
|
||||
|
||||
const { container } = render(<KanbanCard task={mockTask} onClick={vi.fn()} />)
|
||||
// Verify wrapper contains the task title and relative positioning for indicator lines
|
||||
expect(screen.getByText('Reorderable Task')).toBeDefined()
|
||||
expect(container.querySelector('.relative')).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders board with proper permissions and handles task update mutation', async () => {
|
||||
const mockPatch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'task-1', status: KanbanTaskStatus.IN_PROGRESS }),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].kanban.tasks[':taskId'].$patch as any) = mockPatch
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
const mockGet = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: [],
|
||||
pageInfo: { total: 0, hasNextPage: false },
|
||||
}),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].kanban.tasks.$get as any) = mockGet
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<KanbanBoard
|
||||
teamId="team-1"
|
||||
selectedGoalId={null}
|
||||
scope="team"
|
||||
currentUserId="user-1"
|
||||
currentUserRole="owner"
|
||||
onTaskClick={vi.fn()}
|
||||
onCreateTaskInColumn={vi.fn()}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(screen.getByText(/To Do|待办/i)).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('TaskRelatedAssets component', () => {
|
||||
const mockAssets: KanbanTaskAssetInfo[] = [
|
||||
{
|
||||
id: 'asset-1',
|
||||
name: 'Design_Spec.pdf',
|
||||
type: 'file',
|
||||
proxyType: 'pdf',
|
||||
thumbnailUrl: null,
|
||||
path: '/Project/Design_Spec.pdf',
|
||||
creator: { id: 'user-1', name: 'Alice' },
|
||||
sizeByte: 1024,
|
||||
fileCount: undefined,
|
||||
projectId: 'proj-1',
|
||||
createdAt: '2026-08-20T00:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'asset-2',
|
||||
name: 'Assets Folder',
|
||||
type: 'folder',
|
||||
proxyType: null,
|
||||
thumbnailUrl: null,
|
||||
path: '/Project/Assets Folder',
|
||||
creator: { id: 'user-2', name: 'Bob' },
|
||||
sizeByte: 0,
|
||||
fileCount: 5,
|
||||
projectId: 'proj-1',
|
||||
createdAt: '2026-08-20T00:00:00.000Z',
|
||||
},
|
||||
]
|
||||
|
||||
it('renders empty state when no assets are linked', () => {
|
||||
render(
|
||||
<TaskRelatedAssets
|
||||
teamId="team-1"
|
||||
assets={[]}
|
||||
onAddAssets={vi.fn()}
|
||||
onRemoveAsset={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText(/No related assets|暂无关联资产/i)).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders asset rows with name, path, and creator and triggers remove', () => {
|
||||
const onRemove = vi.fn()
|
||||
render(
|
||||
<TaskRelatedAssets
|
||||
teamId="team-1"
|
||||
assets={mockAssets}
|
||||
onAddAssets={vi.fn()}
|
||||
onRemoveAsset={onRemove}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Design_Spec.pdf')).toBeDefined()
|
||||
expect(screen.getByText('/Project/Design_Spec.pdf')).toBeDefined()
|
||||
expect(screen.getByText('Alice')).toBeDefined()
|
||||
expect(screen.getByText('Assets Folder')).toBeDefined()
|
||||
expect(screen.getByText('/Project/Assets Folder')).toBeDefined()
|
||||
|
||||
// Click remove button on first asset
|
||||
const removeButtons = screen.getAllByTitle(/Unlink Asset|取消关联资产/i)
|
||||
expect(removeButtons.length).toBe(2)
|
||||
fireEvent.click(removeButtons[0])
|
||||
expect(onRemove).toHaveBeenCalledWith('asset-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('KanbanGoalSidebar component', () => {
|
||||
it('renders goals list with unassigned goal and calculates All Tasks sum correctly', async () => {
|
||||
const mockGoals: KanbanGoalInfo[] = [
|
||||
{
|
||||
id: UNASSIGNED_GOAL_ID,
|
||||
title: 'Unassigned',
|
||||
teamId: 'team-1',
|
||||
creatorId: null,
|
||||
taskCount: 3,
|
||||
createdAt: new Date(0).toISOString(),
|
||||
updatedAt: new Date(0).toISOString(),
|
||||
},
|
||||
{
|
||||
id: 'goal-1',
|
||||
title: 'Sprint 1',
|
||||
teamId: 'team-1',
|
||||
creatorId: 'user-1',
|
||||
taskCount: 5,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
]
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].kanban.goals.$get as any) = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: mockGoals }),
|
||||
})
|
||||
|
||||
const onSelectGoal = vi.fn()
|
||||
render(
|
||||
<KanbanGoalSidebar
|
||||
teamId="team-1"
|
||||
selectedGoalId={null}
|
||||
onSelectGoal={onSelectGoal}
|
||||
isOwnerOrEditor={true}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
// Total count in All Tasks should be 3 + 5 = 8
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('8')).toBeDefined()
|
||||
expect(screen.getByText(/All Tasks|所有任务/i)).toBeDefined()
|
||||
expect(screen.getByText(/Unassigned|未指派/i)).toBeDefined()
|
||||
expect(screen.getByText('Sprint 1')).toBeDefined()
|
||||
})
|
||||
|
||||
// Clicking Unassigned triggers onSelectGoal with UNASSIGNED_GOAL_ID
|
||||
const unassignedElement = screen.getByText(/Unassigned|未指派/i)
|
||||
fireEvent.click(unassignedElement)
|
||||
expect(onSelectGoal).toHaveBeenCalledWith(UNASSIGNED_GOAL_ID)
|
||||
})
|
||||
})
|
||||
|
||||
describe('KanbanCreateTaskDialog goal handling', () => {
|
||||
it('defaults goalId to none when opened with unassigned goal and excludes unassigned from options', async () => {
|
||||
const mockGoals: KanbanGoalInfo[] = [
|
||||
{
|
||||
id: UNASSIGNED_GOAL_ID,
|
||||
title: 'Unassigned',
|
||||
teamId: 'team-1',
|
||||
creatorId: null,
|
||||
taskCount: 2,
|
||||
createdAt: new Date(0).toISOString(),
|
||||
updatedAt: new Date(0).toISOString(),
|
||||
},
|
||||
{
|
||||
id: 'goal-1',
|
||||
title: 'Alpha Goal',
|
||||
teamId: 'team-1',
|
||||
creatorId: 'user-1',
|
||||
taskCount: 1,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
]
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].kanban.goals.$get as any) = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: mockGoals }),
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].members.$get as any) = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => [],
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(client.api.teams[':teamId'].agents.$get as any) = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => [],
|
||||
})
|
||||
|
||||
render(
|
||||
<KanbanCreateTaskDialog
|
||||
teamId="team-1"
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
initialGoalId={UNASSIGNED_GOAL_ID}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Create Task|创建任务/i)).toBeDefined()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,279 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { KanbanTaskStatus, type KanbanTaskInfo, type KanbanTaskSummary } from '@shumai/dtos'
|
||||
import { getStatusBadgeColor, getStatusLabel } from './kanban-types'
|
||||
import { Link2, Search, X, Check, Loader2 } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
|
||||
interface TaskParentSelectorProps {
|
||||
teamId: string
|
||||
currentTaskId?: string
|
||||
excludeTaskIds?: string[]
|
||||
value?: string[]
|
||||
knownTasks?: Array<KanbanTaskSummary | KanbanTaskInfo>
|
||||
onChange?: (parentIds: string[]) => void
|
||||
disabled?: boolean
|
||||
canEdit?: boolean
|
||||
className?: string
|
||||
}
|
||||
|
||||
const SELECTABLE_STATUSES: KanbanTaskStatus[] = [
|
||||
KanbanTaskStatus.TODO,
|
||||
KanbanTaskStatus.READY,
|
||||
KanbanTaskStatus.IN_PROGRESS,
|
||||
KanbanTaskStatus.IN_REVIEW,
|
||||
KanbanTaskStatus.DONE,
|
||||
KanbanTaskStatus.BLOCKED,
|
||||
]
|
||||
|
||||
export function TaskParentSelector({
|
||||
teamId,
|
||||
currentTaskId,
|
||||
excludeTaskIds = [],
|
||||
value = [],
|
||||
knownTasks = [],
|
||||
onChange,
|
||||
disabled = false,
|
||||
canEdit = true,
|
||||
className,
|
||||
}: TaskParentSelectorProps) {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [selectedStatus, setSelectedStatus] = useState<KanbanTaskStatus>(KanbanTaskStatus.TODO)
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
|
||||
// Map of known tasks for label rendering of selected items
|
||||
const [taskMetadataCache, setTaskMetadataCache] = useState<
|
||||
Record<string, { title: string; status: KanbanTaskStatus }>
|
||||
>(() => {
|
||||
const initial: Record<string, { title: string; status: KanbanTaskStatus }> = {}
|
||||
for (const t of knownTasks) {
|
||||
initial[t.id] = { title: t.title, status: t.status }
|
||||
}
|
||||
return initial
|
||||
})
|
||||
|
||||
// Query 100 tasks of the currently selected status
|
||||
const { data: statusTasksData, isLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'kanban', 'tasks', 'status', selectedStatus],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].kanban.tasks.$get({
|
||||
param: { teamId },
|
||||
query: { status: selectedStatus, first: '100' },
|
||||
})
|
||||
if (!res.ok) return { data: [] }
|
||||
return (await res.json()) as { data: KanbanTaskInfo[] }
|
||||
},
|
||||
enabled: !!teamId && isOpen,
|
||||
})
|
||||
|
||||
// Update metadata cache when tasks arrive
|
||||
const fetchedTasks = statusTasksData?.data || []
|
||||
useMemo(() => {
|
||||
if (fetchedTasks.length > 0) {
|
||||
setTaskMetadataCache((prev) => {
|
||||
let changed = false
|
||||
const next = { ...prev }
|
||||
for (const t of fetchedTasks) {
|
||||
if (!next[t.id] || next[t.id].title !== t.title || next[t.id].status !== t.status) {
|
||||
next[t.id] = { title: t.title, status: t.status }
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed ? next : prev
|
||||
})
|
||||
}
|
||||
}, [fetchedTasks])
|
||||
|
||||
const excludeSet = useMemo(() => {
|
||||
const set = new Set(excludeTaskIds)
|
||||
if (currentTaskId) set.add(currentTaskId)
|
||||
return set
|
||||
}, [currentTaskId, excludeTaskIds])
|
||||
|
||||
// Filter tasks in current status tab by search query and exclusions
|
||||
const filteredTasks = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
return fetchedTasks.filter((t) => {
|
||||
if (excludeSet.has(t.id)) return false
|
||||
if (!query) return true
|
||||
return t.title.toLowerCase().includes(query)
|
||||
})
|
||||
}, [fetchedTasks, excludeSet, searchQuery])
|
||||
|
||||
const handleToggle = (taskId: string) => {
|
||||
if (!canEdit || disabled) return
|
||||
const isSelected = value.includes(taskId)
|
||||
const nextValue = isSelected ? value.filter((id) => id !== taskId) : [...value, taskId]
|
||||
onChange?.(nextValue)
|
||||
}
|
||||
|
||||
const handleRemove = (taskId: string, e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (!canEdit || disabled) return
|
||||
onChange?.(value.filter((id) => id !== taskId))
|
||||
}
|
||||
|
||||
const isInteractive = canEdit && !disabled
|
||||
|
||||
return (
|
||||
<Popover
|
||||
open={isOpen && isInteractive}
|
||||
onOpenChange={(open) => isInteractive && setIsOpen(open)}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={isInteractive ? 0 : -1}
|
||||
className={cn(
|
||||
'w-full min-h-[36px] px-2.5 py-1.5 flex flex-wrap items-center gap-1.5 rounded-md border border-input bg-background text-xs transition-colors',
|
||||
isInteractive
|
||||
? 'cursor-pointer hover:border-ring/60 focus:outline-none focus:ring-2 focus:ring-ring/50'
|
||||
: 'cursor-not-allowed opacity-70',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{value.length === 0 ? (
|
||||
<div className="flex items-center gap-1.5 text-muted-foreground">
|
||||
<Link2 className="w-3.5 h-3.5 text-muted-foreground/70" />
|
||||
<span>{m.select_parent_tasks()}</span>
|
||||
</div>
|
||||
) : (
|
||||
value.map((id) => {
|
||||
const meta = taskMetadataCache[id]
|
||||
return (
|
||||
<span
|
||||
key={id}
|
||||
className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md text-[11px] bg-muted text-foreground border border-border/80 shrink-0 max-w-[220px]"
|
||||
>
|
||||
{meta?.status && (
|
||||
<span
|
||||
className={cn(
|
||||
'px-1 py-0.2 rounded text-[9px] uppercase font-semibold shrink-0',
|
||||
getStatusBadgeColor(meta.status),
|
||||
)}
|
||||
>
|
||||
{getStatusLabel(meta.status)}
|
||||
</span>
|
||||
)}
|
||||
<span className="truncate font-medium">{meta?.title || id}</span>
|
||||
{isInteractive && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => handleRemove(id, e)}
|
||||
className="text-muted-foreground hover:text-destructive shrink-0 p-0.5 -mr-1"
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</PopoverTrigger>
|
||||
|
||||
<PopoverContent
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
className="w-[var(--radix-popover-trigger-width)] min-w-[320px] sm:min-w-[420px] max-w-[500px] p-2.5 space-y-2 bg-popover border border-border rounded-lg shadow-lg"
|
||||
>
|
||||
{/* Part 1: Status Toggle Group */}
|
||||
<div className="flex flex-wrap gap-1.5 pb-0.5">
|
||||
{SELECTABLE_STATUSES.map((st) => {
|
||||
const isSelected = selectedStatus === st
|
||||
return (
|
||||
<button
|
||||
key={st}
|
||||
type="button"
|
||||
onClick={() => setSelectedStatus(st)}
|
||||
className={cn(
|
||||
'text-[11px] h-7 px-2.5 rounded-md font-medium transition-colors border shrink-0',
|
||||
isSelected
|
||||
? 'bg-primary text-primary-foreground border-primary shadow-xs'
|
||||
: 'bg-muted/50 hover:bg-accent text-muted-foreground hover:text-foreground border-border/60',
|
||||
)}
|
||||
>
|
||||
{getStatusLabel(st)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Part 2: Search Input */}
|
||||
<div className="relative">
|
||||
<Search className="w-3.5 h-3.5 absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder={m.filter_tasks_placeholder()}
|
||||
className="h-8 pl-8 text-xs bg-muted/40"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Part 2: Selection List */}
|
||||
<div className="border rounded-md overflow-hidden bg-background/50">
|
||||
<ScrollArea className="h-48 p-1">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : filteredTasks.length === 0 ? (
|
||||
<div className="py-8 text-center text-xs text-muted-foreground italic">
|
||||
{m.no_matching_tasks()}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{filteredTasks.map((t) => {
|
||||
const isSelected = value.includes(t.id)
|
||||
return (
|
||||
<div
|
||||
key={t.id}
|
||||
onClick={() => handleToggle(t.id)}
|
||||
className={cn(
|
||||
'flex items-center justify-between p-2 rounded-md hover:bg-accent cursor-pointer transition-colors text-xs border border-transparent',
|
||||
isSelected && 'bg-accent/50 border-border/50',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1 pr-2">
|
||||
<div
|
||||
className={cn(
|
||||
'w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors',
|
||||
isSelected
|
||||
? 'bg-primary border-primary text-primary-foreground'
|
||||
: 'border-input bg-background',
|
||||
)}
|
||||
>
|
||||
{isSelected && <Check className="w-3 h-3 stroke-[3]" />}
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
'px-1.5 py-0.5 rounded text-[10px] uppercase font-medium shrink-0',
|
||||
getStatusBadgeColor(t.status),
|
||||
)}
|
||||
>
|
||||
{getStatusLabel(t.status)}
|
||||
</span>
|
||||
<span className="font-medium text-foreground truncate">{t.title}</span>
|
||||
</div>
|
||||
{t.assignee && (
|
||||
<span className="text-[10px] text-muted-foreground truncate shrink-0">
|
||||
{t.assignee.name}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Separator } from '@/ui/components/ui/separator'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { KanbanTaskAssetInfo } from '@shumai/dtos'
|
||||
import { AssetPickerDialog } from './asset-picker-dialog'
|
||||
import { Plus, X, Folder, File, Files } from 'lucide-react'
|
||||
|
||||
interface TaskRelatedAssetsProps {
|
||||
teamId: string
|
||||
projectId?: string | null
|
||||
assets: KanbanTaskAssetInfo[]
|
||||
onAddAssets: (newAssets: KanbanTaskAssetInfo[]) => void
|
||||
onRemoveAsset: (assetId: string) => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function TaskRelatedAssets({
|
||||
teamId,
|
||||
projectId,
|
||||
assets,
|
||||
onAddAssets,
|
||||
onRemoveAsset,
|
||||
disabled = false,
|
||||
}: TaskRelatedAssetsProps) {
|
||||
const [isPickerOpen, setIsPickerOpen] = useState(false)
|
||||
|
||||
const handleConfirmPicker = (selectedAssets: KanbanTaskAssetInfo[]) => {
|
||||
// Filter out already linked assets
|
||||
const existingIds = new Set(assets.map((a) => a.id))
|
||||
const toAdd = selectedAssets.filter((a) => !existingIds.has(a.id))
|
||||
if (toAdd.length > 0) {
|
||||
onAddAssets(toAdd)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{/* Title + Plus Button */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-1.5 text-xs font-semibold text-foreground">
|
||||
<Files className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
<span>{m.related_assets()}</span>
|
||||
{assets.length > 0 && (
|
||||
<span className="text-[11px] text-muted-foreground font-normal">({assets.length})</span>
|
||||
)}
|
||||
</div>
|
||||
{!disabled && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 hover:bg-muted"
|
||||
onClick={() => setIsPickerOpen(true)}
|
||||
title={m.add_assets()}
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Assets List Rows */}
|
||||
{assets.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground/70 py-1 italic">{m.no_related_assets()}</p>
|
||||
) : (
|
||||
<div className="space-y-1.5 max-h-48 overflow-y-auto pr-1">
|
||||
{assets.map((asset) => {
|
||||
const isFolder = asset.type === 'folder'
|
||||
|
||||
return (
|
||||
<div
|
||||
key={asset.id}
|
||||
className="flex items-center justify-between gap-2 p-1.5 px-2 rounded-md bg-muted/40 hover:bg-muted/70 transition-colors text-xs border border-border/40"
|
||||
>
|
||||
{/* Left: Thumbnail & Names */}
|
||||
<div className="flex items-center gap-2.5 min-w-0 flex-1">
|
||||
{/* Thumbnail / Icon */}
|
||||
<div className="w-7 h-7 rounded bg-muted border shrink-0 flex items-center justify-center overflow-hidden">
|
||||
{asset.thumbnailUrl ? (
|
||||
<img
|
||||
src={asset.thumbnailUrl}
|
||||
alt={asset.name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : isFolder ? (
|
||||
<Folder className="w-4 h-4 text-primary fill-primary/20" />
|
||||
) : (
|
||||
<File className="w-4 h-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Name & Path */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium truncate text-foreground leading-snug">
|
||||
{asset.name}
|
||||
</p>
|
||||
<p className="text-[10px] text-muted-foreground truncate leading-none mt-0.5">
|
||||
{asset.path || '/'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Creator & Remove Button */}
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{asset.creator && (
|
||||
<div
|
||||
className="flex items-center gap-1 text-[11px] text-muted-foreground"
|
||||
title={asset.creator.name}
|
||||
>
|
||||
<Avatar className="w-4 h-4 text-[9px]">
|
||||
<AvatarImage src={asset.creator.image || undefined} />
|
||||
<AvatarFallback>
|
||||
{asset.creator.name.slice(0, 1).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="hidden sm:inline text-[11px] max-w-[80px] truncate">
|
||||
{asset.creator.name}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!disabled && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-5 w-5 p-0 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => onRemoveAsset(asset.id)}
|
||||
title={m.unlink_asset()}
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Asset Picker Dialog */}
|
||||
{isPickerOpen && (
|
||||
<AssetPickerDialog
|
||||
teamId={teamId}
|
||||
initialProjectId={projectId}
|
||||
excludeAssetIds={assets.map((a) => a.id)}
|
||||
isOpen={isPickerOpen}
|
||||
onClose={() => setIsPickerOpen(false)}
|
||||
onConfirm={handleConfirmPicker}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { cn } from '@/ui/lib/utils'
|
||||
import { SpriteScrubber } from './sprite-scrubber'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import React from 'react'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
|
||||
interface NotificationCardProps {
|
||||
notification: NotificationInfo
|
||||
@@ -33,11 +34,13 @@ const renderNotification = (
|
||||
}
|
||||
|
||||
export const NotificationCard = ({ notification }: NotificationCardProps) => {
|
||||
const { creator, createdAt, isRead, type, asset, project, team, user } = notification
|
||||
const navigate = useNavigate()
|
||||
const { creator, createdAt, isRead, type, asset, project, team, user, kanbanTask } = notification
|
||||
|
||||
const message = (() => {
|
||||
const creatorName = creator?.name || m.unknown_user()
|
||||
const assetName = asset?.name || m.unknown_asset()
|
||||
const taskTitle = kanbanTask?.title || m.unknown_task()
|
||||
const projectName = project?.name || m.unknown_project()
|
||||
const teamName = team?.name || m.unknown_team()
|
||||
const targetUserName = user?.name || m.unknown_user()
|
||||
@@ -45,6 +48,7 @@ export const NotificationCard = ({ notification }: NotificationCardProps) => {
|
||||
const placeholders = {
|
||||
creator: <span className="font-semibold">{creatorName}</span>,
|
||||
asset: <span className="font-semibold">{assetName}</span>,
|
||||
task: <span className="font-semibold">{taskTitle}</span>,
|
||||
project: <span className="font-semibold">{projectName}</span>,
|
||||
team: <span className="font-semibold">{teamName}</span>,
|
||||
user: <span className="font-semibold">{targetUserName}</span>,
|
||||
@@ -63,7 +67,9 @@ export const NotificationCard = ({ notification }: NotificationCardProps) => {
|
||||
)
|
||||
case 'mention':
|
||||
return renderNotification(
|
||||
m.notification_mentioned_you({ creator: '{creator}', asset: '{asset}' }),
|
||||
kanbanTask
|
||||
? m.notification_mentioned_you_in_task({ creator: '{creator}', task: '{task}' })
|
||||
: m.notification_mentioned_you({ creator: '{creator}', asset: '{asset}' }),
|
||||
placeholders,
|
||||
)
|
||||
case 'successful_file_uploaded':
|
||||
@@ -86,6 +92,36 @@ export const NotificationCard = ({ notification }: NotificationCardProps) => {
|
||||
m.notification_joined_project({ user: '{user}', project: '{project}' }),
|
||||
placeholders,
|
||||
)
|
||||
case 'kanban_task_created':
|
||||
return renderNotification(
|
||||
m.notification_kanban_task_created({ creator: '{creator}', task: '{task}' }),
|
||||
placeholders,
|
||||
)
|
||||
case 'kanban_task_assigned':
|
||||
return renderNotification(
|
||||
m.notification_kanban_task_assigned({ creator: '{creator}', task: '{task}' }),
|
||||
placeholders,
|
||||
)
|
||||
case 'kanban_task_status_updated':
|
||||
return renderNotification(
|
||||
m.notification_kanban_task_status_updated({ creator: '{creator}', task: '{task}' }),
|
||||
placeholders,
|
||||
)
|
||||
case 'kanban_task_updated':
|
||||
return renderNotification(
|
||||
m.notification_kanban_task_updated({ creator: '{creator}', task: '{task}' }),
|
||||
placeholders,
|
||||
)
|
||||
case 'kanban_task_deleted':
|
||||
return renderNotification(
|
||||
m.notification_kanban_task_deleted({ creator: '{creator}', task: '{task}' }),
|
||||
placeholders,
|
||||
)
|
||||
case 'kanban_task_comment_created':
|
||||
return renderNotification(
|
||||
m.notification_kanban_task_comment_created({ creator: '{creator}', task: '{task}' }),
|
||||
placeholders,
|
||||
)
|
||||
default:
|
||||
return renderNotification(m.notification_generic({ creator: '{creator}' }), placeholders)
|
||||
}
|
||||
@@ -100,8 +136,21 @@ export const NotificationCard = ({ notification }: NotificationCardProps) => {
|
||||
|
||||
const hasPreview = asset?.preview && (asset.proxyType === 'image' || asset.proxyType === 'video')
|
||||
|
||||
const handleClick = () => {
|
||||
if (kanbanTask?.id && team?.id) {
|
||||
navigate({
|
||||
to: '/teams/$teamId/kanban',
|
||||
params: { teamId: team.id },
|
||||
search: { taskId: kanbanTask.id },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex py-2 cursor-pointer group border border-transparent items-center justify-center">
|
||||
<div
|
||||
onClick={handleClick}
|
||||
className="flex py-2 cursor-pointer group border border-transparent items-center justify-center hover:bg-muted/50 rounded-md px-1 transition-colors"
|
||||
>
|
||||
{/* Unread Indicator */}
|
||||
<div
|
||||
className={cn(
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
UploadCloud,
|
||||
Activity,
|
||||
Bell,
|
||||
LayoutDashboard,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { NotificationSettings as Settings } from '@shumai/dtos'
|
||||
@@ -224,6 +225,62 @@ export function NotificationSettings({ teamId }: { teamId: string }) {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Kanban Settings */}
|
||||
<Card className="border border-slate-200 dark:border-slate-800">
|
||||
<CardHeader className="border-b border-slate-100 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/50">
|
||||
<div className="flex items-center gap-2">
|
||||
<LayoutDashboard className="w-5 h-5 text-indigo-500" />
|
||||
<CardTitle className="text-lg">{m.kanban_notifications()}</CardTitle>
|
||||
</div>
|
||||
<CardDescription>{m.kanban_notification_description()}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="divide-y divide-slate-100 dark:divide-slate-800 p-0">
|
||||
{/* Kanban Tasks */}
|
||||
<div className="flex items-center justify-between p-6">
|
||||
<div className="flex gap-4">
|
||||
<div className="mt-1 flex items-center justify-center w-8 h-8 rounded-lg bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400">
|
||||
<LayoutDashboard className="w-4 h-4" />
|
||||
</div>
|
||||
<div className="space-y-0.5">
|
||||
<h4 className="text-sm font-semibold text-slate-900 dark:text-white">
|
||||
{m.kanban_tasks()}
|
||||
</h4>
|
||||
<p className="text-sm text-slate-500 dark:text-slate-400">
|
||||
{m.when_kanban_task_events()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Switch
|
||||
checked={settings?.kanbanTasks ?? true}
|
||||
onCheckedChange={() => handleToggle('kanbanTasks')}
|
||||
disabled={isUpdating}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Kanban Comments */}
|
||||
<div className="flex items-center justify-between p-6">
|
||||
<div className="flex gap-4">
|
||||
<div className="mt-1 flex items-center justify-center w-8 h-8 rounded-lg bg-cyan-50 dark:bg-cyan-900/20 text-cyan-600 dark:text-cyan-400">
|
||||
<MessageSquare className="w-4 h-4" />
|
||||
</div>
|
||||
<div className="space-y-0.5">
|
||||
<h4 className="text-sm font-semibold text-slate-900 dark:text-white">
|
||||
{m.kanban_comments()}
|
||||
</h4>
|
||||
<p className="text-sm text-slate-500 dark:text-slate-400">
|
||||
{m.when_kanban_task_commented()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Switch
|
||||
checked={settings?.kanbanComments ?? true}
|
||||
onCheckedChange={() => handleToggle('kanbanComments')}
|
||||
disabled={isUpdating}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)
|
||||
|
||||
@@ -248,3 +248,20 @@ export function UploadCloudIcon({
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export const KanbanFillIcon: React.FC<React.SVGProps<SVGSVGElement>> = ({
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 -960 960 960"
|
||||
fill="currentColor"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
className={className ? `rotate-180 ${className}` : 'rotate-180'}
|
||||
{...props}
|
||||
>
|
||||
<path d="M172-84q-36.3 0-62.15-25.85T84-172v-616q0-36.3 25.85-62.15T172-876h616q36.3 0 62.15 25.85T876-788v616q0 36.3-25.85 62.15T788-84H172Zm88-176h88v-440h-88v440Zm176 0h88v-264h-88v264Zm176 0h88v-352h-88v352Z" />
|
||||
</svg>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user