veritas-kanban/web/src/components/task/CommentsSection.tsx
Brad Groux 4b47550e6a fix: retain task confirmations during pending requests
Guard dismissal before deferred mutation state updates, preserve failed time-entry drafts, and leave Escape ownership with visible overlays. Add supporting-dialog browser geometry and delayed-failure coverage.
2026-09-03 23:11:18 -05:00

361 lines
11 KiB
TypeScript

import { UiModal as Modal, OverlayFooter } from '@/components/ui/UiOverlay';
import { UiAction } from '@/components/ui/UiVocabulary';
import { useState, useRef } from 'react';
import { MessageSquare, Pencil, Trash2, X, Check } from 'lucide-react';
import {
ActionIcon,
Avatar,
Box,
Button,
Group,
Paper,
Stack,
Text,
Textarea,
TextInput,
} from '@mantine/core';
import { MarkdownEditor } from '@/components/ui/MarkdownEditor';
import { MarkdownRenderer } from '@/components/ui/MarkdownRenderer';
import { useAddComment, useEditComment, useDeleteComment } from '@/hooks/useTasks';
import { useFeatureSettings } from '@/hooks/useFeatureSettings';
import type { Task, Comment } from '@veritas-kanban/shared';
interface CommentsSectionProps {
task: Task;
}
function formatRelativeTime(timestamp: string): string {
const now = new Date();
const date = new Date(timestamp);
const seconds = Math.floor((now.getTime() - date.getTime()) / 1000);
if (seconds < 60) return 'just now';
if (seconds < 3600)
return `${Math.floor(seconds / 60)} minute${Math.floor(seconds / 60) === 1 ? '' : 's'} ago`;
if (seconds < 86400)
return `${Math.floor(seconds / 3600)} hour${Math.floor(seconds / 3600) === 1 ? '' : 's'} ago`;
if (seconds < 604800)
return `${Math.floor(seconds / 86400)} day${Math.floor(seconds / 86400) === 1 ? '' : 's'} ago`;
return date.toLocaleDateString();
}
function getInitials(name: string): string {
return name
.split(' ')
.map((part) => part[0])
.join('')
.toUpperCase()
.slice(0, 2);
}
function CommentItem({
comment,
taskId,
markdownEnabled,
}: {
comment: Comment;
taskId: string;
markdownEnabled: boolean;
}) {
const [isEditing, setIsEditing] = useState(false);
const [editText, setEditText] = useState(comment.text);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [deleteError, setDeleteError] = useState(false);
const deletionInFlight = useRef(false);
const closeDeleteDialog = () => {
if (!deletionInFlight.current) setDeleteDialogOpen(false);
};
const editComment = useEditComment();
const deleteComment = useDeleteComment();
const handleSaveEdit = async () => {
if (!editText.trim()) return;
await editComment.mutateAsync({
taskId,
commentId: comment.id,
text: editText.trim(),
});
setIsEditing(false);
};
const handleCancelEdit = () => {
setEditText(comment.text);
setIsEditing(false);
};
const handleDelete = async () => {
if (deletionInFlight.current) return;
deletionInFlight.current = true;
setDeleteError(false);
try {
await deleteComment.mutateAsync({ taskId, commentId: comment.id });
setDeleteDialogOpen(false);
} catch {
setDeleteError(true);
} finally {
deletionInFlight.current = false;
}
};
return (
<>
<Paper className="group flex flex-col gap-3 bg-muted/30 p-3 sm:flex-row" radius="md">
<Avatar color="violet" radius="xl" size="sm" className="flex-shrink-0">
{getInitials(comment.author)}
</Avatar>
<Box className="min-w-0 flex-1">
<Group align="baseline" gap="xs" className="mb-1" wrap="wrap">
<Text size="sm" fw={500}>
{comment.author}
</Text>
<Text size="xs" c="dimmed">
{formatRelativeTime(comment.timestamp)}
</Text>
{/* Edit/Delete buttons - visible on hover */}
<Group gap={4} className="veritas-secondary-action ml-auto">
<ActionIcon
variant="subtle"
color="gray"
size="sm"
aria-label={`Edit comment by ${comment.author}`}
onClick={() => {
setEditText(comment.text);
setIsEditing(true);
}}
>
<Pencil className="h-3 w-3 text-muted-foreground hover:text-foreground" />
</ActionIcon>
<ActionIcon
variant="subtle"
color="red"
size="sm"
aria-label={`Delete comment by ${comment.author}`}
onClick={() => setDeleteDialogOpen(true)}
>
<Trash2 className="h-3 w-3" />
</ActionIcon>
</Group>
</Group>
{isEditing ? (
<Stack gap="xs">
{markdownEnabled ? (
<MarkdownEditor
value={editText}
onChange={setEditText}
minHeight={80}
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
handleSaveEdit();
}
if (e.key === 'Escape') handleCancelEdit();
}}
/>
) : (
<Textarea
value={editText}
onChange={(e) => setEditText(e.currentTarget.value)}
className="text-sm min-h-[60px] resize-none"
autoFocus
aria-label="Edit comment text"
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
handleSaveEdit();
}
if (e.key === 'Escape') handleCancelEdit();
}}
/>
)}
<Group gap="xs">
<Button
size="xs"
onClick={() => {
void handleSaveEdit();
}}
disabled={!editText.trim() || editComment.isPending}
leftSection={<Check className="h-3 w-3" />}
>
Save
</Button>
<Button
variant="subtle"
size="xs"
onClick={handleCancelEdit}
leftSection={<X className="h-3 w-3" />}
>
Cancel
</Button>
</Group>
</Stack>
) : (
<Box className="break-words text-sm text-foreground">
{markdownEnabled ? (
<MarkdownRenderer content={comment.text} className="break-words" />
) : (
<p className="whitespace-pre-wrap">{comment.text}</p>
)}
</Box>
)}
</Box>
</Paper>
<Modal
variant="confirm"
compound
opened={deleteDialogOpen}
onClose={closeDeleteDialog}
title="Delete comment?"
centered
>
<div className="vk-overlay-scroll">
{deleteError && (
<Text role="alert" size="sm" c="red">
Could not delete this comment. Try again.
</Text>
)}
<Text size="sm" c="dimmed">
This will permanently delete this comment by {comment.author}. This action cannot be
undone.
</Text>
</div>
<OverlayFooter>
<UiAction variant="quiet" disabled={deleteComment.isPending} onClick={closeDeleteDialog}>
Cancel
</UiAction>
<UiAction
variant="destructive"
loading={deleteComment.isPending}
onClick={() => {
void handleDelete();
}}
>
Delete
</UiAction>
</OverlayFooter>
</Modal>
</>
);
}
export function CommentsSection({ task }: CommentsSectionProps) {
const { settings: featureSettings } = useFeatureSettings();
const markdownEnabled = featureSettings.markdown?.enableMarkdown ?? true;
const [author, setAuthor] = useState('Veritas');
const [text, setText] = useState('');
const [isAdding, setIsAdding] = useState(false);
const addComment = useAddComment();
const comments = task.comments || [];
const handleAddComment = async () => {
if (!text.trim() || !author.trim()) return;
setIsAdding(true);
try {
await addComment.mutateAsync({
taskId: task.id,
author: author.trim(),
text: text.trim(),
});
setText('');
} finally {
setIsAdding(false);
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
handleAddComment();
}
};
return (
<Stack gap="md">
<Group gap="xs">
<MessageSquare className="h-4 w-4 text-muted-foreground" />
<Text size="sm" c="dimmed" fw={500}>
Comments
</Text>
{comments.length > 0 && (
<Text size="xs" c="dimmed">
({comments.length})
</Text>
)}
</Group>
{/* Comments list */}
{comments.length === 0 ? (
<Paper className="py-4 text-center" radius="md" withBorder>
<Text size="sm" c="dimmed" fs="italic">
No comments yet
</Text>
</Paper>
) : (
<Stack gap="sm">
{comments.map((comment) => (
<CommentItem
key={comment.id}
comment={comment}
taskId={task.id}
markdownEnabled={markdownEnabled}
/>
))}
</Stack>
)}
{/* Add comment form */}
<Stack gap="xs" className="border-t pt-2">
<Group gap="xs">
<TextInput
value={author}
onChange={(e) => setAuthor(e.currentTarget.value)}
placeholder="Your name"
className="w-full text-sm sm:max-w-[180px]"
disabled={isAdding}
aria-label="Comment author"
/>
</Group>
<Box>
{markdownEnabled ? (
<MarkdownEditor
value={text}
onChange={setText}
onKeyDown={handleKeyDown}
placeholder="Add a comment... (supports Markdown, Cmd/Ctrl+Enter to submit)"
minHeight={100}
maxHeight={240}
disabled={isAdding}
/>
) : (
<Textarea
value={text}
onChange={(e) => setText(e.currentTarget.value)}
onKeyDown={handleKeyDown}
placeholder="Add a comment... (Cmd/Ctrl+Enter to submit)"
className="text-sm min-h-[80px] resize-none"
disabled={isAdding}
aria-label="Comment text"
/>
)}
</Box>
<Group justify="flex-end">
<Button
size="sm"
onClick={() => {
void handleAddComment();
}}
disabled={!text.trim() || !author.trim() || isAdding}
className="w-full sm:w-auto"
>
Add Comment
</Button>
</Group>
</Stack>
</Stack>
);
}