Merge pull request #163 from shancds/fix/customer-feedback

refactor(project-view-updates): optimize comment handling and renderi…
This commit is contained in:
Chamika J
2025-06-19 13:47:55 +05:30
committed by GitHub
4 changed files with 162 additions and 70 deletions

View File

@@ -18,6 +18,7 @@ import { colors } from '@/styles/colors';
import AttachmentsGrid from '../attachments/attachments-grid'; import AttachmentsGrid from '../attachments/attachments-grid';
import { TFunction } from 'i18next'; import { TFunction } from 'i18next';
import SingleAvatar from '@/components/common/single-avatar/single-avatar'; import SingleAvatar from '@/components/common/single-avatar/single-avatar';
import { sanitizeHtml } from '@/utils/sanitizeInput';
// Helper function to format date for time separators // Helper function to format date for time separators
const formatDateForSeparator = (date: string) => { const formatDateForSeparator = (date: string) => {
@@ -56,6 +57,32 @@ const processMentions = (content: string) => {
return content.replace(/@(\w+)/g, '<span class="mentions">@$1</span>'); return content.replace(/@(\w+)/g, '<span class="mentions">@$1</span>');
}; };
// Utility to linkify URLs in text
const linkify = (text: string) => {
if (!text) return '';
// Regex to match URLs (http, https, www)
return text.replace(/(https?:\/\/[^\s]+|www\.[^\s]+)/g, (url) => {
let href = url;
if (!href.startsWith('http')) {
href = 'http://' + href;
}
return `<a href="${href}" target="_blank" rel="noopener noreferrer">${url}</a>`;
});
};
// Helper function to process mentions and links in content
const processContent = (content: string) => {
if (!content) return '';
// First, linkify URLs
let processed = linkify(content);
// Then, process mentions (if not already processed)
if (!hasProcessedMentions(processed)) {
processed = processMentions(processed);
}
// Sanitize the final HTML (allowing <a> and <span class="mentions">)
return sanitizeHtml(processed);
};
const TaskComments = ({ taskId, t }: { taskId?: string, t: TFunction }) => { const TaskComments = ({ taskId, t }: { taskId?: string, t: TFunction }) => {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [comments, setComments] = useState<ITaskCommentViewModel[]>([]); const [comments, setComments] = useState<ITaskCommentViewModel[]>([]);
@@ -80,10 +107,10 @@ const TaskComments = ({ taskId, t }: { taskId?: string, t: TFunction }) => {
return dayjs(a.created_at).isBefore(dayjs(b.created_at)) ? -1 : 1; return dayjs(a.created_at).isBefore(dayjs(b.created_at)) ? -1 : 1;
}); });
// Process mentions in content // Process content (mentions and links)
sortedComments.forEach(comment => { sortedComments.forEach(comment => {
if (comment.content && !hasProcessedMentions(comment.content)) { if (comment.content) {
comment.content = processMentions(comment.content); comment.content = processContent(comment.content);
} }
}); });
@@ -184,9 +211,9 @@ const TaskComments = ({ taskId, t }: { taskId?: string, t: TFunction }) => {
const commentUpdated = (comment: ITaskCommentViewModel) => { const commentUpdated = (comment: ITaskCommentViewModel) => {
comment.edit = false; comment.edit = false;
// Process mentions in updated content // Process content (mentions and links) in updated comment
if (comment.content && !hasProcessedMentions(comment.content)) { if (comment.content) {
comment.content = processMentions(comment.content); comment.content = processContent(comment.content);
} }
setComments([...comments]); // Force re-render setComments([...comments]); // Force re-render
}; };

View File

@@ -103,7 +103,6 @@ const InfoTabFooter = () => {
})) ?? []; })) ?? [];
const memberSelectHandler = useCallback((member: IMentionMemberSelectOption) => { const memberSelectHandler = useCallback((member: IMentionMemberSelectOption) => {
console.log('member', member);
if (!member?.value || !member?.label) return; if (!member?.value || !member?.label) return;
// Find the member ID from the members list using the name // Find the member ID from the members list using the name

View File

@@ -1,5 +1,5 @@
import { Button, ConfigProvider, Flex, Form, Mentions, Skeleton, Space, Tooltip, Typography } from 'antd'; import { Button, ConfigProvider, Flex, Form, Mentions, Skeleton, Space, Tooltip, Typography, Dropdown, Menu, Popconfirm } from 'antd';
import { useEffect, useState, useCallback } from 'react'; import { useEffect, useState, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import DOMPurify from 'dompurify'; import DOMPurify from 'dompurify';
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
@@ -10,7 +10,6 @@ import {
IMentionMemberSelectOption, IMentionMemberSelectOption,
IMentionMemberViewModel, IMentionMemberViewModel,
} from '@/types/project/projectComments.types'; } from '@/types/project/projectComments.types';
import { projectsApiService } from '@/api/projects/projects.api.service';
import { projectCommentsApiService } from '@/api/projects/comments/project-comments.api.service'; import { projectCommentsApiService } from '@/api/projects/comments/project-comments.api.service';
import { IProjectUpdateCommentViewModel } from '@/types/project/project.types'; import { IProjectUpdateCommentViewModel } from '@/types/project/project.types';
import { calculateTimeDifference } from '@/utils/calculate-time-difference'; import { calculateTimeDifference } from '@/utils/calculate-time-difference';
@@ -21,6 +20,19 @@ import { DeleteOutlined } from '@ant-design/icons';
const MAX_COMMENT_LENGTH = 2000; const MAX_COMMENT_LENGTH = 2000;
// Compile RegExp once for linkify
const urlRegex = /((https?:\/\/|www\.)[\w\-._~:/?#[\]@!$&'()*+,;=%]+)/gi;
function linkify(text: string): string {
return text.replace(
urlRegex,
url => {
const href = url.startsWith('http') ? url : `https://${url}`;
return `<a href="${href}" target="_blank" rel="noopener noreferrer">${url}</a>`;
}
);
}
const ProjectViewUpdates = () => { const ProjectViewUpdates = () => {
const { projectId } = useParams(); const { projectId } = useParams();
const [characterLength, setCharacterLength] = useState<number>(0); const [characterLength, setCharacterLength] = useState<number>(0);
@@ -68,7 +80,7 @@ const ProjectViewUpdates = () => {
} }
}, [projectId]); }, [projectId]);
const handleAddComment = async () => { const handleAddComment = useCallback(async () => {
if (!projectId || characterLength === 0) return; if (!projectId || characterLength === 0) return;
try { try {
@@ -88,7 +100,16 @@ const ProjectViewUpdates = () => {
const res = await projectCommentsApiService.createProjectComment(body); const res = await projectCommentsApiService.createProjectComment(body);
if (res.done) { if (res.done) {
await getComments(); setComments(prev => [
...prev,
{
...(res.body as IProjectUpdateCommentViewModel),
created_by: getUserSession()?.name || '',
created_at: new Date().toISOString(),
content: commentValue.trim(),
mentions: (res.body as IProjectUpdateCommentViewModel).mentions ?? [undefined, undefined],
}
]);
handleCancel(); handleCancel();
} }
} catch (error) { } catch (error) {
@@ -96,15 +117,13 @@ const ProjectViewUpdates = () => {
} finally { } finally {
setIsSubmitting(false); setIsSubmitting(false);
setCommentValue(''); setCommentValue('');
} }
}; }, [projectId, characterLength, commentValue, selectedMembers, getComments]);
useEffect(() => { useEffect(() => {
void getMembers(); void getMembers();
void getComments(); void getComments();
}, [getMembers, getComments,refreshTimestamp]); }, [getMembers, getComments, refreshTimestamp]);
const handleCancel = useCallback(() => { const handleCancel = useCallback(() => {
form.resetFields(['comment']); form.resetFields(['comment']);
@@ -113,14 +132,16 @@ const ProjectViewUpdates = () => {
setSelectedMembers([]); setSelectedMembers([]);
}, [form]); }, [form]);
const mentionsOptions = const mentionsOptions = useMemo(() =>
members?.map(member => ({ members?.map(member => ({
value: member.id, value: member.id,
label: member.name, label: member.name,
})) ?? []; })) ?? [], [members]
);
const memberSelectHandler = useCallback((member: IMentionMemberSelectOption) => { const memberSelectHandler = useCallback((member: IMentionMemberSelectOption) => {
if (!member?.value || !member?.label) return; if (!member?.value || !member?.label) return;
setSelectedMembers(prev => setSelectedMembers(prev =>
prev.some(mention => mention.id === member.value) prev.some(mention => mention.id === member.value)
? prev ? prev
@@ -131,13 +152,11 @@ const ProjectViewUpdates = () => {
const parts = prev.split('@'); const parts = prev.split('@');
const lastPart = parts[parts.length - 1]; const lastPart = parts[parts.length - 1];
const mentionText = member.label; const mentionText = member.label;
// Keep only the part before the @ and add the new mention
return prev.slice(0, prev.length - lastPart.length) + mentionText; return prev.slice(0, prev.length - lastPart.length) + mentionText;
}); });
}, []); }, []);
const handleCommentChange = useCallback((value: string) => { const handleCommentChange = useCallback((value: string) => {
// Only update the value without trying to replace mentions
setCommentValue(value); setCommentValue(value);
setCharacterLength(value.trim().length); setCharacterLength(value.trim().length);
}, []); }, []);
@@ -157,15 +176,58 @@ const ProjectViewUpdates = () => {
[getComments] [getComments]
); );
// Memoize link click handler for comment links
const handleCommentLinkClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
const target = e.target as HTMLElement;
if (target.tagName === 'A') {
e.preventDefault();
const href = (target as HTMLAnchorElement).getAttribute('href');
if (href) {
window.open(href, '_blank', 'noopener,noreferrer');
}
}
}, []);
const configProviderTheme = useMemo(() => ({
components: {
Button: {
defaultColor: colors.lightGray,
defaultHoverColor: colors.darkGray,
},
},
}), []);
// Context menu for each comment (memoized)
const getCommentMenu = useCallback((commentId: string) => (
<Menu>
<Menu.Item key="delete">
<Popconfirm
title="Are you sure you want to delete this comment?"
onConfirm={() => handleDeleteComment(commentId)}
okText="Yes"
cancelText="No"
>
Delete
</Popconfirm>
</Menu.Item>
</Menu>
), [handleDeleteComment]);
const renderComment = useCallback(
(comment: IProjectUpdateCommentViewModel) => {
const linkifiedContent = linkify(comment.content || '');
const sanitizedContent = DOMPurify.sanitize(linkifiedContent);
const timeDifference = calculateTimeDifference(comment.created_at || '');
const themeClass = theme === 'dark' ? 'dark' : 'light';
return ( return (
<Flex gap={24} vertical> <Dropdown
<Flex vertical gap={16}> key={comment.id ?? ''}
{ overlay={getCommentMenu(comment.id ?? '')}
isLoadingComments ? ( trigger={["contextMenu"]}
<Skeleton active /> >
): <div>
comments.map(comment => ( <Flex gap={8}>
<Flex key={comment.id} gap={8}>
<CustomAvatar avatarName={comment.created_by || ''} /> <CustomAvatar avatarName={comment.created_by || ''} />
<Flex vertical flex={1}> <Flex vertical flex={1}>
<Space> <Space>
@@ -174,39 +236,38 @@ const ProjectViewUpdates = () => {
</Typography.Text> </Typography.Text>
<Tooltip title={comment.created_at}> <Tooltip title={comment.created_at}>
<Typography.Text style={{ fontSize: 13, color: colors.deepLightGray }}> <Typography.Text style={{ fontSize: 13, color: colors.deepLightGray }}>
{calculateTimeDifference(comment.created_at || '')} {timeDifference}
</Typography.Text> </Typography.Text>
</Tooltip> </Tooltip>
</Space> </Space>
<Typography.Paragraph <Typography.Paragraph style={{ margin: '8px 0' }} ellipsis={{ rows: 3, expandable: true }}>
style={{ margin: '8px 0' }} <div
ellipsis={{ rows: 3, expandable: true }} className={`mentions-${themeClass}`}
> dangerouslySetInnerHTML={{ __html: sanitizedContent }}
<div className={`mentions-${theme === 'dark' ? 'dark' : 'light'}`} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(comment.content || '') }} /> onClick={handleCommentLinkClick}
</Typography.Paragraph>
<ConfigProvider
wave={{ disabled: true }}
theme={{
components: {
Button: {
defaultColor: colors.lightGray,
defaultHoverColor: colors.darkGray,
},
},
}}
>
<Button
icon={<DeleteOutlined />}
shape="circle"
type="text"
size='small'
onClick={() => handleDeleteComment(comment.id)}
/> />
</ConfigProvider> </Typography.Paragraph>
</Flex> </Flex>
</Flex> </Flex>
))} </div>
</Dropdown>
);
},
[theme, configProviderTheme, handleDeleteComment, handleCommentLinkClick]
);
const commentsList = useMemo(() =>
comments.map(renderComment), [comments, renderComment]
);
return (
<Flex gap={24} vertical>
<Flex vertical gap={16}>
{isLoadingComments ? (
<Skeleton active />
) : (
commentsList
)}
</Flex> </Flex>
<Form onFinish={handleAddComment}> <Form onFinish={handleAddComment}>
@@ -218,11 +279,16 @@ const ProjectViewUpdates = () => {
options={mentionsOptions} options={mentionsOptions}
autoSize autoSize
maxLength={MAX_COMMENT_LENGTH} maxLength={MAX_COMMENT_LENGTH}
onSelect={option => memberSelectHandler(option as IMentionMemberSelectOption)} onSelect={(option, prefix) => memberSelectHandler(option as IMentionMemberSelectOption)}
onClick={() => setIsCommentBoxExpand(true)} onClick={() => setIsCommentBoxExpand(true)}
onChange={handleCommentChange} onChange={handleCommentChange}
prefix="@" prefix="@"
split="" split=""
filterOption={(input, option) => {
if (!input) return true;
const optionLabel = (option as any)?.label || '';
return optionLabel.toLowerCase().includes(input.toLowerCase());
}}
style={{ style={{
minHeight: isCommentBoxExpand ? 180 : 60, minHeight: isCommentBoxExpand ? 180 : 60,
paddingBlockEnd: 24, paddingBlockEnd: 24,

View File

@@ -29,7 +29,7 @@ export const sanitizeHtml = (input: string): string => {
if (!input) return ''; if (!input) return '';
return DOMPurify.sanitize(input, { return DOMPurify.sanitize(input, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br'], ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br', 'span'],
ALLOWED_ATTR: ['href', 'target', 'rel'], ALLOWED_ATTR: ['href', 'target', 'rel', 'class'],
}); });
}; };