Scrum4Me/components/backlog/story-dialog.tsx
Janpeter Visser 6cd98129f2
M14: TaskDialog (create/edit) + story auto-promotion (#21)
* chore(ST-1112): add deps for task dialog

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1112): add shared zod schema for task dialog

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1112): add missing MD3 tokens for task dialog

outline-variant, on-error-container, status-review (light + dark)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1112): add saveTask and deleteTask server actions for TaskDialog

Unified create/edit action (saveTask) replaces separate formData-based
actions for the new TaskDialog. Uses shared zod schema, structured
SaveTaskResult union type, and context-aware revalidatePath for both
sprint and backlog routes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1112): add TaskDialog component (create & edit mode)

Builds the full TaskDialog on top of the existing @base-ui/react
Dialog primitive. Covers create mode, edit mode (status field +
created_at metadata + delete), dirty-check AlertDialog, delete
confirm AlertDialog, Cmd+Enter submit, and per-field char counters.
Uses react-hook-form + zodResolver against the shared taskSchema.
Priority and status are extracted to PrioritySegmented and
StatusSelect sub-components using MD3 tokens throughout.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1112): refactor task-list to open TaskDialog via URL params

Replaces inline create/edit forms with router.push navigation:
- Clicking a task row → ?editTask=<id>
- "+ Taak" button → ?newTask=1&storyId=<storyId>
Removes CreateTaskForm, EditSubmitButton, updateTaskAction, and
createTaskAction from the component. Status toggle and DnD remain
unchanged. Rows now have cursor-pointer and keyboard a11y.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1112): wire TaskDialog into sprint page via searchParams

Sprint page now reads ?newTask, ?storyId, and ?editTask query params.
For edit mode: fetches the task server-side with productAccessFilter
scope (invalid/foreign IDs redirect to closePath). Renders TaskDialog
when either param is present. closePath is the sprint route without
query params.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1112): add Suspense skeleton for edit-mode task loading

Extracts task fetch into EditTaskLoader (async server component) so
the sprint board renders immediately while the task loads.
TaskDialogSkeleton shows 3 grey bars during the fetch. Invalid or
out-of-scope task IDs redirect to closePath.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1112): render description as markdown in task-detail-dialog

Solo task detail now renders description via react-markdown +
remark-gfm with prose styling. Sanitizes script/iframe elements.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test(ST-1112): add saveTask/deleteTask server action tests

Covers all three demo-policy layers and cross-tenant scope:
demo blocked (403), unauthenticated blocked, validation 422,
edit cross-tenant forbidden, create cross-tenant forbidden,
and happy-path for both edit and create.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1112): add updateTaskStatusWithStoryPromotion helper

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1112): wire story-promotion into saveTask and PATCH /api/tasks/:id

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(ST-1112): add task-dialog doc and architecture note

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: extend allowed tools in settings.local.json

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1113): add 200ms animation-delay to TaskDialogSkeleton to prevent flicker

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1114): add DirtyCloseGuard reusable component for dirty-form close confirmation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(ST-1114): add shared Markdown wrapper, apply to task-detail and story-dialog

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: allow grep -E pattern in settings.local.json

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 16:55:20 +02:00

310 lines
12 KiB
TypeScript

'use client'
import { useEffect, useRef, useState, useTransition } from 'react'
import { Markdown } from '@/components/markdown'
import { useActionState } from 'react'
import { useFormStatus } from 'react-dom'
import { toast } from 'sonner'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogClose,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { PrioritySelect, PRIORITY_LABELS, PRIORITY_COLORS } from '@/components/shared/priority-select'
import { StoryLog } from '@/components/shared/story-log'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import { createStoryAction, updateStoryAction, deleteStoryAction, getStoryLogsAction } from '@/actions/stories'
import { cn } from '@/lib/utils'
import type { Story } from './story-panel'
export type StoryDialogState =
| { mode: 'create'; pbiId: string; productId: string; defaultPriority?: number }
| { mode: 'edit'; story: Story; productId: string }
interface StoryDialogProps {
state: StoryDialogState | null
onClose: () => void
isDemo?: boolean
}
const STATUS_COLORS: Record<string, string> = {
OPEN: 'bg-status-todo/15 text-status-todo border-status-todo/30',
IN_SPRINT: 'bg-status-in-progress/15 text-status-in-progress border-status-in-progress/30',
DONE: 'bg-status-done/15 text-status-done border-status-done/30',
}
const STATUS_LABELS: Record<string, string> = {
OPEN: 'Open',
IN_SPRINT: 'In Sprint',
DONE: 'Klaar',
}
function SubmitButton({ label, disabled }: { label: string; disabled?: boolean }) {
const { pending } = useFormStatus()
return (
<Button type="submit" disabled={disabled || pending}>
{pending ? '…' : label}
</Button>
)
}
export function StoryDialog({ state, onClose, isDemo = false }: StoryDialogProps) {
const isEdit = state?.mode === 'edit'
const story = isEdit ? (state as Extract<StoryDialogState, { mode: 'edit' }>).story : null
const createState_ = isEdit ? null : (state as Extract<StoryDialogState, { mode: 'create' }> | null)
const [priority, setPriority] = useState(story?.priority ?? createState_?.defaultPriority ?? 2)
const [confirmDelete, setConfirmDelete] = useState(false)
const [isDeleting, startDeleteTransition] = useTransition()
const [logs, setLogs] = useState<Awaited<ReturnType<typeof getStoryLogsAction>> | null>(null)
useEffect(() => {
if (!state) return
// eslint-disable-next-line react-hooks/set-state-in-effect
setConfirmDelete(false)
if (state.mode === 'edit') {
setPriority(state.story.priority)
setLogs(null)
getStoryLogsAction(state.story.id).then(setLogs)
} else {
setPriority(state.defaultPriority ?? 2)
}
}, [state])
const [createResult, createAction] = useActionState(
async (_prev: unknown, fd: FormData) => {
const result = await createStoryAction(_prev, fd)
if (result?.success) { toast.success('Story aangemaakt'); onClose() }
else if (typeof result?.error === 'string') toast.error(result.error)
return result
},
undefined
)
const [updateResult, updateAction] = useActionState(
async (_prev: unknown, fd: FormData) => {
const result = await updateStoryAction(_prev, fd)
if (result?.success) { toast.success('Story opgeslagen'); onClose() }
else if (typeof result?.error === 'string') toast.error(result.error)
return result
},
undefined
)
const fieldError = (field: string) => {
const result = isEdit ? updateResult : createResult
const err = result?.error
if (!err || typeof err === 'string') return undefined
return (err as Record<string, string[]>)[field]?.[0]
}
function handleDelete() {
if (!story) return
startDeleteTransition(async () => {
const result = await deleteStoryAction(story.id)
if (result && 'error' in result) toast.error(result.error ?? 'Verwijderen mislukt')
else toast.success('Story verwijderd')
onClose()
})
}
const titleRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (state) setTimeout(() => titleRef.current?.focus(), 50)
}, [state])
const showForm = !isDemo || !isEdit
return (
<Dialog open={!!state} onOpenChange={(open) => { if (!open) onClose() }}>
<DialogContent className="sm:max-w-lg flex flex-col gap-0 p-0 max-h-[90vh] overflow-hidden">
<DialogHeader className="px-5 pt-5 pb-4 border-b border-border shrink-0 pr-14">
<div className="flex items-start gap-2">
<DialogTitle className="flex-1">{isEdit ? story!.title : 'Nieuwe story'}</DialogTitle>
{isEdit && story!.code && (
<span className="font-mono text-[11px] text-muted-foreground border border-border rounded-md bg-surface-container px-1.5 py-0.5 shrink-0 mt-0.5">
{story!.code}
</span>
)}
</div>
{isEdit && (
<div className="flex gap-2 mt-1">
<Badge className={cn('text-xs border', PRIORITY_COLORS[priority])}>
{PRIORITY_LABELS[priority]}
</Badge>
<Badge className={cn('text-xs border', STATUS_COLORS[story!.status])}>
{STATUS_LABELS[story!.status]}
</Badge>
</div>
)}
</DialogHeader>
<form
key={isEdit ? story!.id : 'create'}
action={isEdit ? updateAction : createAction}
className="flex flex-col min-h-0 flex-1"
>
{isEdit && <input type="hidden" name="id" value={story!.id} />}
{!isEdit && (
<>
<input type="hidden" name="pbiId" value={createState_?.pbiId ?? ''} />
<input type="hidden" name="productId" value={createState_?.productId ?? ''} />
</>
)}
<input type="hidden" name="priority" value={priority} />
<div className="flex-1 overflow-y-auto">
{showForm ? (
<div className="p-5 space-y-4">
<div className="grid grid-cols-[6rem_1fr] gap-3">
<div className="space-y-1.5">
<label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Code</label>
<Input
name="code"
defaultValue={story?.code ?? ''}
placeholder={isEdit ? '' : 'auto'}
maxLength={30}
className={cn('font-mono text-sm', fieldError('code') ? 'border-error' : '')}
/>
{fieldError('code') && <p className="text-xs text-error">{fieldError('code')}</p>}
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Titel</label>
<Input
ref={titleRef}
name="title"
defaultValue={story?.title ?? ''}
required
maxLength={200}
className={fieldError('title') ? 'border-error' : ''}
/>
{fieldError('title') && <p className="text-xs text-error">{fieldError('title')}</p>}
</div>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Prioriteit</label>
<PrioritySelect value={priority} onChange={setPriority} />
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
Omschrijving <span className="normal-case font-normal">(optioneel)</span>
</label>
<Textarea
name="description"
rows={3}
defaultValue={story?.description ?? ''}
placeholder="Als… wil ik… zodat…"
className="resize-none"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
Acceptatiecriteria <span className="normal-case font-normal">(optioneel)</span>
</label>
<Textarea
name="acceptance_criteria"
rows={3}
defaultValue={story?.acceptance_criteria ?? ''}
placeholder="- Gegeven… Als… Dan…"
className="resize-none"
/>
</div>
{typeof (isEdit ? updateResult?.error : createResult?.error) === 'string' && (
<p className="text-xs text-error">
{String(isEdit ? updateResult?.error : createResult?.error)}
</p>
)}
</div>
) : (
<div className="p-5 space-y-4">
{story?.description && (
<div>
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-1">Omschrijving</p>
<Markdown>{story.description}</Markdown>
</div>
)}
{story?.acceptance_criteria && (
<div>
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-1">Acceptatiecriteria</p>
<p className="text-sm whitespace-pre-line">{story.acceptance_criteria}</p>
</div>
)}
</div>
)}
{isEdit && (
<div className="px-5 py-4 border-t border-border">
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-3">Activiteitenlog</p>
{logs && 'logs' in logs && logs.logs ? (
<StoryLog
logs={logs.logs.map(l => ({
...l,
status: l.status ?? null,
commit_hash: l.commit_hash ?? null,
commit_message: l.commit_message ?? null,
}))}
repoUrl={logs.repoUrl}
/>
) : (
<p className="text-xs text-muted-foreground">Laden</p>
)}
</div>
)}
</div>
{isEdit && (
<div className="px-5 py-3 border-t border-border shrink-0">
{!isDemo && confirmDelete ? (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground flex-1">
Weet je het zeker? Taken worden ook verwijderd.
</span>
<Button type="button" variant="destructive" size="sm" disabled={isDeleting} onClick={handleDelete}>
{isDeleting ? 'Bezig…' : 'Verwijderen'}
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => setConfirmDelete(false)}>
Annuleren
</Button>
</div>
) : (
<DemoTooltip show={isDemo}>
<Button
type="button"
variant="ghost"
size="sm"
className="text-error hover:bg-error/10"
disabled={isDemo}
onClick={() => !isDemo && setConfirmDelete(true)}
>
Story verwijderen
</Button>
</DemoTooltip>
)}
</div>
)}
<div className="flex justify-end gap-2 px-5 py-4 border-t border-border shrink-0 rounded-b-xl bg-muted/50">
<DialogClose render={<Button type="button" variant="outline" />}>
Annuleren
</DialogClose>
<DemoTooltip show={isDemo}>
<SubmitButton label={isEdit ? 'Opslaan' : 'Aanmaken'} disabled={isDemo} />
</DemoTooltip>
</div>
</form>
</DialogContent>
</Dialog>
)
}