Merge branch 'release/v2.0.4' into imp/task-list-performance-fixes

This commit is contained in:
Chamika J
2025-06-21 19:16:00 +05:30
committed by GitHub
11 changed files with 446 additions and 197 deletions

View File

@@ -53,12 +53,6 @@ const PrioritySection = ({ task }: PrioritySectionProps) => {
return ( return (
<Flex gap={4}> <Flex gap={4}>
{priorityIcon} {priorityIcon}
<Typography.Text
style={{ fontWeight: 500 }}
ellipsis={{ tooltip: task.name }}
>
{task.name}
</Typography.Text>
</Flex> </Flex>
); );
}; };

View File

@@ -11,7 +11,7 @@ import List from 'antd/es/list';
import Space from 'antd/es/space'; import Space from 'antd/es/space';
import { useSearchParams } from 'react-router-dom'; import { useSearchParams } from 'react-router-dom';
import { useMemo, useRef, useState } from 'react'; import { useMemo, useRef, useState, useEffect } from 'react';
import { useAppSelector } from '@/hooks/useAppSelector'; import { useAppSelector } from '@/hooks/useAppSelector';
import { colors } from '@/styles/colors'; import { colors } from '@/styles/colors';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -36,6 +36,13 @@ const LabelsFilterDropdown = () => {
const tab = searchParams.get('tab'); const tab = searchParams.get('tab');
const projectView = tab === 'tasks-list' ? 'list' : 'kanban'; const projectView = tab === 'tasks-list' ? 'list' : 'kanban';
// Fetch labels when component mounts or projectId changes
useEffect(() => {
if (projectId) {
dispatch(fetchLabelsByProject(projectId));
}
}, [dispatch, projectId]);
const filteredLabelData = useMemo(() => { const filteredLabelData = useMemo(() => {
if (projectView === 'list') { if (projectView === 'list') {
return labels.filter(label => label.name?.toLowerCase().includes(searchQuery.toLowerCase())); return labels.filter(label => label.name?.toLowerCase().includes(searchQuery.toLowerCase()));
@@ -81,9 +88,6 @@ const LabelsFilterDropdown = () => {
setTimeout(() => { setTimeout(() => {
labelInputRef.current?.focus(); labelInputRef.current?.focus();
}, 0); }, 0);
if (projectView === 'kanban') {
dispatch(setBoardLabels(labels));
}
} }
}; };

View File

@@ -76,7 +76,6 @@ const MembersFilterDropdown = () => {
const handleSelectedFiltersCount = useCallback(async (memberId: string | undefined, checked: boolean) => { const handleSelectedFiltersCount = useCallback(async (memberId: string | undefined, checked: boolean) => {
if (!memberId || !projectId) return; if (!memberId || !projectId) return;
if (!memberId || !projectId) return;
const updateMembers = async (members: Member[], setAction: any, fetchAction: any) => { const updateMembers = async (members: Member[], setAction: any, fetchAction: any) => {
const updatedMembers = members.map(member => const updatedMembers = members.map(member =>
@@ -142,11 +141,12 @@ const MembersFilterDropdown = () => {
const handleMembersDropdownOpen = useCallback((open: boolean) => { const handleMembersDropdownOpen = useCallback((open: boolean) => {
if (open) { if (open) {
setTimeout(() => membersInputRef.current?.focus(), 0); setTimeout(() => membersInputRef.current?.focus(), 0);
if (taskAssignees.length) { // Only sync the members if board members are empty
if (projectView === 'kanban' && boardTaskAssignees.length === 0 && taskAssignees.length > 0) {
dispatch(setBoardMembers(taskAssignees)); dispatch(setBoardMembers(taskAssignees));
} }
} }
}, [dispatch, taskAssignees]); }, [dispatch, taskAssignees, boardTaskAssignees, projectView]);
const buttonStyle = { const buttonStyle = {
backgroundColor: selectedCount > 0 backgroundColor: selectedCount > 0

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

@@ -459,10 +459,24 @@ const boardSlice = createSlice({
const { body, sectionId, taskId } = action.payload; const { body, sectionId, taskId } = action.payload;
const section = state.taskGroups.find(sec => sec.id === sectionId); const section = state.taskGroups.find(sec => sec.id === sectionId);
if (section) { if (section) {
const task = section.tasks.find(task => task.id === taskId); // First try to find the task in main tasks
if (task) { const mainTask = section.tasks.find(task => task.id === taskId);
task.assignees = body.assignees; if (mainTask) {
task.names = body.names; mainTask.assignees = body.assignees;
mainTask.names = body.names;
return;
}
// If not found in main tasks, look in subtasks
for (const parentTask of section.tasks) {
if (!parentTask.sub_tasks) continue;
const subtask = parentTask.sub_tasks.find(st => st.id === taskId);
if (subtask) {
subtask.assignees = body.assignees;
subtask.names = body.names;
return;
}
} }
} }
}, },

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,56 +176,98 @@ 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 (
<Dropdown
key={comment.id ?? ''}
overlay={getCommentMenu(comment.id ?? '')}
trigger={["contextMenu"]}
>
<div>
<Flex gap={8}>
<CustomAvatar avatarName={comment.created_by || ''} />
<Flex vertical flex={1}>
<Space>
<Typography.Text strong style={{ fontSize: 13, color: colors.lightGray }}>
{comment.created_by || ''}
</Typography.Text>
<Tooltip title={comment.created_at}>
<Typography.Text style={{ fontSize: 13, color: colors.deepLightGray }}>
{timeDifference}
</Typography.Text>
</Tooltip>
</Space>
<Typography.Paragraph style={{ margin: '8px 0' }} ellipsis={{ rows: 3, expandable: true }}>
<div
className={`mentions-${themeClass}`}
dangerouslySetInnerHTML={{ __html: sanitizedContent }}
onClick={handleCommentLinkClick}
/>
</Typography.Paragraph>
</Flex>
</Flex>
</div>
</Dropdown>
);
},
[theme, configProviderTheme, handleDeleteComment, handleCommentLinkClick]
);
const commentsList = useMemo(() =>
comments.map(renderComment), [comments, renderComment]
);
return ( return (
<Flex gap={24} vertical> <Flex gap={24} vertical>
<Flex vertical gap={16}> <Flex vertical gap={16}>
{ {isLoadingComments ? (
isLoadingComments ? ( <Skeleton active />
<Skeleton active /> ) : (
): commentsList
comments.map(comment => ( )}
<Flex key={comment.id} gap={8}>
<CustomAvatar avatarName={comment.created_by || ''} />
<Flex vertical flex={1}>
<Space>
<Typography.Text strong style={{ fontSize: 13, color: colors.lightGray }}>
{comment.created_by || ''}
</Typography.Text>
<Tooltip title={comment.created_at}>
<Typography.Text style={{ fontSize: 13, color: colors.deepLightGray }}>
{calculateTimeDifference(comment.created_at || '')}
</Typography.Text>
</Tooltip>
</Space>
<Typography.Paragraph
style={{ margin: '8px 0' }}
ellipsis={{ rows: 3, expandable: true }}
>
<div className={`mentions-${theme === 'dark' ? 'dark' : 'light'}`} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(comment.content || '') }} />
</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>
</Flex>
</Flex>
))}
</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

@@ -1,11 +1,25 @@
import { useState } from 'react'; import { useCallback, useState } from 'react';
import dayjs, { Dayjs } from 'dayjs'; import dayjs, { Dayjs } from 'dayjs';
import { Col, Flex, Typography, List } from 'antd'; import { Col, Flex, Typography, List, Dropdown, MenuProps, Popconfirm } from 'antd';
import { UserAddOutlined, DeleteOutlined, ExclamationCircleFilled, InboxOutlined } from '@ant-design/icons';
import CustomAvatarGroup from '@/components/board/custom-avatar-group'; import CustomAvatarGroup from '@/components/board/custom-avatar-group';
import CustomDueDatePicker from '@/components/board/custom-due-date-picker'; import CustomDueDatePicker from '@/components/board/custom-due-date-picker';
import { IProjectTask } from '@/types/project/projectTasksViewModel.types'; import { IProjectTask } from '@/types/project/projectTasksViewModel.types';
import { useAppDispatch } from '@/hooks/useAppDispatch'; import { useAppDispatch } from '@/hooks/useAppDispatch';
import { setSelectedTaskId, setShowTaskDrawer } from '@/features/task-drawer/task-drawer.slice'; import { setSelectedTaskId, setShowTaskDrawer } from '@/features/task-drawer/task-drawer.slice';
import { useTranslation } from 'react-i18next';
import { colors } from '@/styles/colors';
import { taskListBulkActionsApiService } from '@/api/tasks/task-list-bulk-actions.api.service';
import { useMixpanelTracking } from '@/hooks/useMixpanelTracking';
import {
evt_project_task_list_context_menu_assign_me,
evt_project_task_list_context_menu_delete,
evt_project_task_list_context_menu_archive,
} from '@/shared/worklenz-analytics-events';
import logger from '@/utils/errorLogger';
import { useAppSelector } from '@/hooks/useAppSelector';
import { deleteBoardTask, updateBoardTaskAssignee } from '@features/board/board-slice';
import { IBulkAssignRequest } from '@/types/tasks/bulk-action-bar.types';
interface IBoardSubTaskCardProps { interface IBoardSubTaskCardProps {
subtask: IProjectTask; subtask: IProjectTask;
@@ -14,48 +28,153 @@ interface IBoardSubTaskCardProps {
const BoardSubTaskCard = ({ subtask, sectionId }: IBoardSubTaskCardProps) => { const BoardSubTaskCard = ({ subtask, sectionId }: IBoardSubTaskCardProps) => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const { t } = useTranslation('kanban-board');
const { trackMixpanelEvent } = useMixpanelTracking();
const projectId = useAppSelector(state => state.projectReducer.projectId);
const [updatingAssignToMe, setUpdatingAssignToMe] = useState(false);
const [subtaskDueDate, setSubtaskDueDate] = useState<Dayjs | null>( const [subtaskDueDate, setSubtaskDueDate] = useState<Dayjs | null>(
subtask?.end_date ? dayjs(subtask?.end_date) : null subtask?.end_date ? dayjs(subtask?.end_date) : null
); );
const handleCardClick = (e: React.MouseEvent, id: string) => { const handleCardClick = (e: React.MouseEvent, id: string) => {
// Prevent the event from propagating to parent elements
e.stopPropagation(); e.stopPropagation();
// Add a small delay to ensure it's a click and not the start of a drag
const clickTimeout = setTimeout(() => { const clickTimeout = setTimeout(() => {
dispatch(setSelectedTaskId(id)); dispatch(setSelectedTaskId(id));
dispatch(setShowTaskDrawer(true)); dispatch(setShowTaskDrawer(true));
}, 50); }, 50);
return () => clearTimeout(clickTimeout); return () => clearTimeout(clickTimeout);
}; };
return ( const handleAssignToMe = useCallback(async () => {
<List.Item if (!projectId || !subtask.id || updatingAssignToMe) return;
key={subtask.id}
className="group" try {
style={{ setUpdatingAssignToMe(true);
width: '100%', const body: IBulkAssignRequest = {
}} tasks: [subtask.id],
onClick={e => handleCardClick(e, subtask.id || '')} project_id: projectId,
> };
<Col span={10}> const res = await taskListBulkActionsApiService.assignToMe(body);
<Typography.Text if (res.done) {
style={{ fontWeight: 500, fontSize: 14 }} trackMixpanelEvent(evt_project_task_list_context_menu_assign_me);
delete={subtask.status === 'done'} dispatch(
ellipsis={{ expanded: false }} updateBoardTaskAssignee({
body: res.body,
sectionId,
taskId: subtask.id,
})
);
}
} catch (error) {
logger.error('Error assigning task to me:', error);
} finally {
setUpdatingAssignToMe(false);
}
}, [projectId, subtask.id, updatingAssignToMe, dispatch, trackMixpanelEvent, sectionId]);
// const handleArchive = async () => {
// if (!projectId || !subtask.id) return;
// try {
// const res = await taskListBulkActionsApiService.archiveTasks(
// {
// tasks: [subtask.id],
// project_id: projectId,
// },
// false
// );
// if (res.done) {
// trackMixpanelEvent(evt_project_task_list_context_menu_archive);
// dispatch(deleteBoardTask({ sectionId, taskId: subtask.id }));
// }
// } catch (error) {
// logger.error('Error archiving subtask:', error);
// }
// };
const handleDelete = async () => {
if (!projectId || !subtask.id) return;
try {
const res = await taskListBulkActionsApiService.deleteTasks({ tasks: [subtask.id] }, projectId);
if (res.done) {
trackMixpanelEvent(evt_project_task_list_context_menu_delete);
dispatch(deleteBoardTask({ sectionId, taskId: subtask.id }));
}
} catch (error) {
logger.error('Error deleting subtask:', error);
}
};
const items: MenuProps['items'] = [
{
label: (
<span>
<UserAddOutlined />
&nbsp;
<Typography.Text>{t('assignToMe')}</Typography.Text>
</span>
),
key: '1',
onClick: () => handleAssignToMe(),
disabled: updatingAssignToMe,
},
// {
// label: (
// <span>
// <InboxOutlined />
// &nbsp;
// <Typography.Text>{t('archive')}</Typography.Text>
// </span>
// ),
// key: '2',
// onClick: () => handleArchive(),
// },
{
label: (
<Popconfirm
title={t('deleteConfirmationTitle')}
icon={<ExclamationCircleFilled style={{ color: colors.vibrantOrange }} />}
okText={t('deleteConfirmationOk')}
cancelText={t('deleteConfirmationCancel')}
onConfirm={() => handleDelete()}
> >
{subtask.name} <DeleteOutlined />
</Typography.Text> &nbsp;
</Col> {t('delete')}
</Popconfirm>
),
key: '3',
},
];
<Flex gap={8} justify="end" style={{ width: '100%' }}> return (
<CustomAvatarGroup task={subtask} sectionId={sectionId} /> <Dropdown menu={{ items }} trigger={['contextMenu']}>
<List.Item
key={subtask.id}
className="group"
style={{
width: '100%',
}}
onClick={e => handleCardClick(e, subtask.id || '')}
>
<Col span={10}>
<Typography.Text
style={{ fontWeight: 500, fontSize: 14 }}
delete={subtask.status === 'done'}
ellipsis={{ expanded: false }}
>
{subtask.name}
</Typography.Text>
</Col>
<CustomDueDatePicker task={subtask} onDateChange={setSubtaskDueDate} /> <Flex gap={8} justify="end" style={{ width: '100%' }}>
</Flex> <CustomAvatarGroup task={subtask} sectionId={sectionId} />
</List.Item> <CustomDueDatePicker task={subtask} onDateChange={setSubtaskDueDate} />
</Flex>
</List.Item>
</Dropdown>
); );
}; };

View File

@@ -256,42 +256,49 @@ const BoardViewTaskCard = ({ task, sectionId }: IBoardViewTaskCardProps) => {
}, [task.labels, themeMode]); }, [task.labels, themeMode]);
return ( return (
<Dropdown menu={{ items }} trigger={['contextMenu']}> <Flex
<Flex ref={setNodeRef}
ref={setNodeRef} {...attributes}
{...attributes} {...listeners}
{...listeners} vertical
vertical gap={12}
gap={12} style={{
style={{ ...style,
...style, width: '100%',
width: '100%', padding: 12,
padding: 12, backgroundColor: themeMode === 'dark' ? '#292929' : '#fafafa',
backgroundColor: themeMode === 'dark' ? '#292929' : '#fafafa', borderRadius: 6,
borderRadius: 6, cursor: 'grab',
cursor: 'grab', overflow: 'hidden',
overflow: 'hidden', }}
}} className={`group outline-1 ${themeWiseColor('outline-[#edeae9]', 'outline-[#6a696a]', themeMode)} hover:outline board-task-card`}
className={`group outline-1 ${themeWiseColor('outline-[#edeae9]', 'outline-[#6a696a]', themeMode)} hover:outline board-task-card`} data-id={task.id}
onClick={e => handleCardClick(e, task.id || '')} data-dragging={isDragging ? "true" : "false"}
data-id={task.id} >
data-dragging={isDragging ? "true" : "false"} <Dropdown menu={{ items }} trigger={['contextMenu']}>
> {/* Task Card */}
{/* Labels and Progress */} <Flex vertical gap={8}
<Flex align="center" justify="space-between"> onClick={e => handleCardClick(e, task.id || '')}>
<Flex> {/* Labels and Progress */}
{renderLabels} <Flex align="center" justify="space-between">
<Flex>
{renderLabels}
</Flex>
<Tooltip title={` ${task?.completed_count} / ${task?.total_tasks_count}`}>
<Progress type="circle" percent={task?.complete_ratio} size={26} strokeWidth={(task.complete_ratio || 0) >= 100 ? 9 : 7} />
</Tooltip>
</Flex>
<Flex gap={4} align="center">
{/* Action Icons */}
<PrioritySection task={task} />
<Typography.Text
style={{ fontWeight: 500 }}
ellipsis={{ tooltip: task.name }}
>
{task.name}
</Typography.Text>
</Flex> </Flex>
<Tooltip title={` ${task?.completed_count} / ${task?.total_tasks_count}`}>
<Progress type="circle" percent={task?.complete_ratio} size={26} strokeWidth={(task.complete_ratio || 0) >= 100 ? 9 : 7} />
</Tooltip>
</Flex>
{/* Action Icons */}
<PrioritySection task={task} />
<Flex vertical gap={8}>
<Flex <Flex
align="center" align="center"
justify="space-between" justify="space-between"
@@ -329,47 +336,50 @@ const BoardViewTaskCard = ({ task, sectionId }: IBoardViewTaskCardProps) => {
</Button> </Button>
</Flex> </Flex>
</Flex> </Flex>
{isSubTaskShow && (
<Flex vertical>
<Divider style={{ marginBlock: 0 }} />
<List>
{task.sub_tasks_loading && (
<List.Item>
<Skeleton active paragraph={{ rows: 2 }} title={false} style={{ marginTop: 8 }} />
</List.Item>
)}
{!task.sub_tasks_loading && task?.sub_tasks &&
task?.sub_tasks.map((subtask: any) => (
<BoardSubTaskCard key={subtask.id} subtask={subtask} sectionId={sectionId} />
))}
{showNewSubtaskCard && (
<BoardCreateSubtaskCard
sectionId={sectionId}
parentTaskId={task.id || ''}
setShowNewSubtaskCard={setShowNewSubtaskCard}
/>
)}
</List>
<Button
type="text"
style={{
width: 'fit-content',
borderRadius: 6,
boxShadow: 'none',
}}
icon={<PlusOutlined />}
onClick={handleAddSubtaskClick}
>
{t('addSubtask', 'Add Subtask')}
</Button>
</Flex>
)}
</Flex> </Flex>
</Dropdown>
{/* Subtask Section */}
<Flex vertical gap={8}>
{isSubTaskShow && (
<Flex vertical>
<Divider style={{ marginBlock: 0 }} />
<List>
{task.sub_tasks_loading && (
<List.Item>
<Skeleton active paragraph={{ rows: 2 }} title={false} style={{ marginTop: 8 }} />
</List.Item>
)}
{!task.sub_tasks_loading && task?.sub_tasks &&
task?.sub_tasks.map((subtask: any) => (
<BoardSubTaskCard key={subtask.id} subtask={subtask} sectionId={sectionId} />
))}
{showNewSubtaskCard && (
<BoardCreateSubtaskCard
sectionId={sectionId}
parentTaskId={task.id || ''}
setShowNewSubtaskCard={setShowNewSubtaskCard}
/>
)}
</List>
<Button
type="text"
style={{
width: 'fit-content',
borderRadius: 6,
boxShadow: 'none',
}}
icon={<PlusOutlined />}
onClick={handleAddSubtaskClick}
>
{t('addSubtask', 'Add Subtask')}
</Button>
</Flex>
)}
</Flex> </Flex>
</Dropdown> </Flex>
); );
}; };

View File

@@ -23,14 +23,10 @@ import {
TouchSensor, TouchSensor,
useSensor, useSensor,
useSensors, useSensors,
MeasuringStrategy,
getFirstCollision, getFirstCollision,
pointerWithin, pointerWithin,
rectIntersection, rectIntersection,
UniqueIdentifier, UniqueIdentifier,
DragOverlayProps,
DragOverlay as DragOverlayType,
closestCorners,
} from '@dnd-kit/core'; } from '@dnd-kit/core';
import BoardViewTaskCard from './board-section/board-task-card/board-view-task-card'; import BoardViewTaskCard from './board-section/board-task-card/board-view-task-card';
import { fetchStatusesCategories } from '@/features/taskAttributes/taskStatusSlice'; import { fetchStatusesCategories } from '@/features/taskAttributes/taskStatusSlice';
@@ -46,7 +42,8 @@ import { statusApiService } from '@/api/taskAttributes/status/status.api.service
import logger from '@/utils/errorLogger'; import logger from '@/utils/errorLogger';
import { checkTaskDependencyStatus } from '@/utils/check-task-dependency-status'; import { checkTaskDependencyStatus } from '@/utils/check-task-dependency-status';
import { debounce } from 'lodash'; import { debounce } from 'lodash';
import { ITaskListPriorityChangeResponse } from '@/types/tasks/task-list-priority.types';
import { updateTaskPriority as updateBoardTaskPriority } from '@/features/board/board-slice';
interface DroppableContainer { interface DroppableContainer {
id: UniqueIdentifier; id: UniqueIdentifier;
data: { data: {
@@ -273,6 +270,21 @@ const ProjectViewBoard = () => {
} }
}; };
const handlePriorityChange = (taskId: string, priorityId: string) => {
if (!taskId || !priorityId || !socket) return;
const payload = {
task_id: taskId,
priority_id: priorityId,
team_id: currentSession?.team_id,
};
socket.emit(SocketEvents.TASK_PRIORITY_CHANGE.toString(), JSON.stringify(payload));
socket.once(SocketEvents.TASK_PRIORITY_CHANGE.toString(), (data: ITaskListPriorityChangeResponse) => {
dispatch(updateBoardTaskPriority(data));
});
};
const handleDragEnd = async (event: DragEndEvent) => { const handleDragEnd = async (event: DragEndEvent) => {
isDraggingRef.current = false; isDraggingRef.current = false;
const { active, over } = event; const { active, over } = event;
@@ -317,6 +329,7 @@ const ProjectViewBoard = () => {
originalSourceGroupIdRef.current = null; // Reset the ref originalSourceGroupIdRef.current = null; // Reset the ref
return; return;
} }
if (targetGroupId !== sourceGroupId) { if (targetGroupId !== sourceGroupId) {
const canContinue = await checkTaskDependencyStatus(task.id, targetGroupId); const canContinue = await checkTaskDependencyStatus(task.id, targetGroupId);
if (!canContinue) { if (!canContinue) {
@@ -376,8 +389,6 @@ const ProjectViewBoard = () => {
team_id: currentSession?.team_id team_id: currentSession?.team_id
}; };
// logger.error('Emitting socket event with payload (task not found in source):', body);
// Emit socket event // Emit socket event
if (socket) { if (socket) {
socket.emit(SocketEvents.TASK_SORT_ORDER_CHANGE.toString(), body); socket.emit(SocketEvents.TASK_SORT_ORDER_CHANGE.toString(), body);
@@ -390,6 +401,11 @@ const ProjectViewBoard = () => {
socket.emit(SocketEvents.GET_TASK_PROGRESS.toString(), task.id); socket.emit(SocketEvents.GET_TASK_PROGRESS.toString(), task.id);
} }
}); });
// Handle priority change if groupBy is priority
if (groupBy === IGroupBy.PRIORITY) {
handlePriorityChange(task.id, targetGroupId);
}
} }
// Track analytics event // Track analytics event
@@ -544,7 +560,7 @@ const ProjectViewBoard = () => {
<Skeleton active loading={isLoading} className='mt-4 p-4'> <Skeleton active loading={isLoading} className='mt-4 p-4'>
<DndContext <DndContext
sensors={sensors} sensors={sensors}
collisionDetection={closestCorners} collisionDetection={collisionDetectionStrategy}
onDragStart={handleDragStart} onDragStart={handleDragStart}
onDragOver={handleDragOver} onDragOver={handleDragOver}
onDragEnd={handleDragEnd} onDragEnd={handleDragEnd}

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'],
}); });
}; };