Compare commits

..

27 Commits

Author SHA1 Message Date
chamikaJ
78d960bf01 feat(gantt): introduce advanced Gantt chart components and demo page
- Added new components for an advanced Gantt chart, including AdvancedGanttChart, GanttGrid, DraggableTaskBar, and TimelineMarkers.
- Implemented a demo page (GanttDemoPage) to showcase the functionality of the new Gantt chart components.
- Enhanced project roadmap features with ProjectRoadmapGantt and related components for better project management visualization.
- Introduced sample data for testing and demonstration purposes, improving the user experience in the Gantt chart interface.
- Updated main routes to include the new Gantt demo page for easy access.
2025-07-20 22:05:42 +05:30
Chamika J
a112d39321 Merge pull request #272 from Worklenz/development
Development
2025-07-15 17:20:59 +05:30
Chamika J
4788294bc4 Merge pull request #271 from Worklenz/release/v2.1.2
Release/v2.1.2
2025-07-15 17:20:25 +05:30
chamikaJ
737f7cada2 refactor(App): streamline cache cleanup process on logout
- Removed dynamic import of CacheCleanup in the App component, directly utilizing the imported utility for clearing caches and reloading the application on user logout.
- This change simplifies the logout process and improves code readability.
2025-07-15 16:11:30 +05:30
chamikaJ
833879e0e8 feat(logout): implement cache cleanup and service worker unregistration on logout
- Added a new utility, CacheCleanup, to handle clearing caches and unregistering the service worker during user logout.
- Enhanced the LoggingOutPage to utilize CacheCleanup for clearing local session and caches before redirecting to the login page.
- Introduced ModuleErrorBoundary to manage module loading errors, providing user feedback and options to retry or reload the application.
- Updated App component to include global error handlers for improved error management related to module loading issues.
2025-07-15 16:08:07 +05:30
chamikaJ
cb5610d99b feat(timer): add useTimerInitialization hook for managing running timers
- Introduced a new custom hook, useTimerInitialization, to fetch and initialize running timers from the backend when the project view loads.
- Integrated the hook into the ProjectView component to update Redux state with active timers and their corresponding task details.
- Enhanced error handling and logging for timer initialization to improve debugging and user experience.
2025-07-15 15:57:01 +05:30
chamikaJ
0434bbb73b refactor(account-setup): update ProjectStep to use custom dispatch and refresh user session
- Replaced useDispatch with useAppDispatch for improved state management in ProjectStep component.
- Added logic to refresh user session and update user state after template setup completion.
- Enhanced error handling for session refresh to ensure robustness in user experience.
2025-07-15 15:40:06 +05:30
chamikaJ
6e911d79fc feat(auth): add combined AuthAndSetupGuard for route protection
- Introduced AuthAndSetupGuard to enforce both authentication and setup completion for protected routes.
- Updated main routes to utilize the new guard, ensuring users are redirected appropriately based on their authentication and setup status.
- Adjusted setup route to only require authentication, allowing access without completed setup.
- Refactored account setup component to use custom dispatch hook for improved state management and added session refresh after setup completion.
2025-07-15 15:34:43 +05:30
chamikaJ
0bb748cf89 feat(database-migrations): implement grouping-specific sort orders and constraints
- Added new sort order columns for tasks based on different grouping types (status, priority, phase, member).
- Updated database functions to handle these new sort orders, ensuring proper task updates during sorting operations.
- Implemented a migration to fix existing sort order constraint violations, ensuring data consistency across projects.
- Enhanced functions to avoid sort order conflicts and maintain unique sort orders within each project.
2025-07-15 15:19:16 +05:30
Chamika J
ba5d4975af Merge pull request #270 from shancds/test/row-kanban-board-v1.2.0
Enhance TaskCard accessibility by adding title attribute to task name
2025-07-15 15:09:57 +05:30
shancds
d4620148bd Update TaskProgressCircle to visually indicate task completion
- Changed the stroke color of the progress circle to green when progress reaches 100%.
- Added a green checkmark icon for completed tasks, enhancing visual feedback.
- Retained progress percentage display for tasks that are not yet complete, ensuring clarity in task status.
2025-07-15 14:48:26 +05:30
shancds
8d7d54be78 Enhance TaskCard accessibility by adding title attribute to task name
- Updated TaskCard component to include a title attribute on the task name span for improved accessibility and better user experience when hovering over task names.
2025-07-15 14:28:45 +05:30
Chamika J
c34b94c7db Merge pull request #269 from shancds/test/row-kanban-board-v1.2.0
Test/row kanban board v1.2.0
2025-07-15 14:24:24 +05:30
chamikaJ
55a0028e26 refactor(drag-and-drop): replace console logging with error logging
- Integrated an error logging utility to replace console warnings and errors in the `useDragAndDrop` hook, enhancing error tracking and debugging.
- Removed unnecessary console logs related to drag-and-drop operations, streamlining the code and improving performance.
2025-07-15 14:24:24 +05:30
chamikaJ
17371200ca feat(drag-and-drop): enhance task grouping updates and socket event handling
- Updated the `useDragAndDrop` hook to emit specific grouping field change events (phase, priority, status) when tasks are moved between groups.
- Refactored the task management slice to prevent direct updates to task grouping fields during drag-and-drop operations, ensuring these updates are handled via socket events after backend confirmation.
- Introduced a new socket handler for task sort order changes to update task properties based on backend responses, improving synchronization between frontend and backend task states.
2025-07-15 14:22:27 +05:30
shancds
83044077d3 Enhance task status handling and progress visualization in Kanban board
- Introduced a mechanism to emit a socket event when a task's status changes during drag-and-drop operations.
- Updated TaskCard to consistently display the progress circle regardless of task completion state.
- Improved TaskProgressCircle to handle complete_ratio and progress more robustly, ensuring accurate visual representation.
2025-07-15 14:13:37 +05:30
Chamika J
a03d9ef6a4 Merge pull request #268 from Worklenz/fix/task-sort-order
Fix/task sort order
2025-07-15 13:38:49 +05:30
Chamika J
fca8ace10d Merge pull request #267 from Worklenz/feature/show-multiples-levels-of-subtaks-in-task-list
Feature/show multiples levels of subtaks in task list
2025-07-15 13:31:10 +05:30
chamikaJ
d970cbb626 feat(task-management): enhance task timer synchronization and color handling
- Updated `CustomColordLabel` and `CustomNumberLabel` components to improve color handling by removing the alpha channel logic and implementing a dynamic text color based on background luminance.
- Enhanced task management slice to preserve timer state when fetching tasks, ensuring active timers are maintained across updates.
- Modified socket handlers to synchronize timer state between task slices, improving consistency in task time tracking.
- Refactored `useTaskTimer` hook to streamline local and Redux state synchronization for timer management.
2025-07-15 13:30:59 +05:30
chamikaJ
6d8c475e67 refactor(sort-orders): remove outdated deployment and implementation guides
- Deleted the `DEPLOYMENT_GUIDE_SORT_ORDERS.md` and `SEPARATE_SORT_ORDERS_IMPLEMENTATION.md` files as they are no longer relevant following the recent updates to the sort orders feature.
- Introduced new migration scripts to address duplicate sort orders and ensure data integrity across the updated task sorting system.
- Updated database schema to include new sort order columns and constraints for improved performance and organization.
- Enhanced backend functions and frontend components to support the new sorting logic and maintain user experience during task organization.
2025-07-15 13:18:51 +05:30
shancds
a1c0cef149 Remove PerformanceMonitor and VirtualizedTaskList components along with their associated styles to streamline the enhanced Kanban board. Update TaskCard to include a progress circle for better task visualization. 2025-07-15 12:17:16 +05:30
shancds
8f098143fd Merge branch 'main' of https://github.com/Worklenz/worklenz into test/row-kanban-board-v1.2.0 2025-07-15 09:00:38 +05:30
chamiakJ
407dc416ec feat(sort-orders): implement separate sort orders for task groupings
- Introduced new columns for `status_sort_order`, `priority_sort_order`, `phase_sort_order`, and `member_sort_order` in the tasks table to maintain distinct sort orders for each grouping type.
- Updated database functions to handle grouping-specific sort orders and avoid unique constraint violations.
- Enhanced backend socket handlers to emit changes based on the selected grouping.
- Modified frontend components to support drag-and-drop functionality with the new sort order fields, ensuring task organization is preserved across different views.
- Added comprehensive migration scripts and verification steps to ensure smooth deployment and backward compatibility.
2025-07-15 07:44:15 +05:30
chamikaJ
3d67145af7 refactor(task-list): adjust subtask indentation for improved visual hierarchy
- Reduced spacing for level 1 subtasks and increased spacing for deeper levels in TaskRowWithSubtasks and TitleColumn components.
- Enhanced comments to clarify indentation logic for better maintainability.
2025-07-14 12:37:54 +05:30
chamikaJ
1c981312d4 feat(task-drawer): enhance task navigation and hierarchy display
- Added functionality to navigate back to parent tasks for sub-tasks in the task drawer.
- Introduced a breadcrumb component to visually represent the hierarchy of tasks, improving user navigation.
- Updated task drawer header to display the current task name with truncation and tooltip for better readability.
- Enhanced styling for task name display and breadcrumb for improved user experience.
2025-07-14 12:28:04 +05:30
chamikaJ
02d814b935 refactor(task-list): enhance task row components with depth handling
- Added depth and maxDepth props to TaskRow, TaskRowWithSubtasks, and TitleColumn components to manage nested subtasks more effectively.
- Updated AddSubtaskRow to support depth for proper indentation and visual hierarchy.
- Improved styling for subtasks based on their depth level, ensuring better visual distinction.
- Adjusted task management slice to utilize actual subtask counts from the backend for accurate display.
2025-07-14 12:04:31 +05:30
shancds
d3023618e1 fix(enhanced-kanban): remove unused Skeleton import in EnhancedKanbanBoardNativeDnD 2025-07-11 17:00:48 +05:30
80 changed files with 7784 additions and 908 deletions

View File

@@ -0,0 +1,11 @@
{
"permissions": {
"allow": [
"Bash(find:*)",
"Bash(npm run build:*)",
"Bash(npm run type-check:*)",
"Bash(npm run:*)"
],
"deny": []
}
}

41
test_sort_fix.sql Normal file
View File

@@ -0,0 +1,41 @@
-- Test script to verify the sort order constraint fix
-- Test the helper function
SELECT get_sort_column_name('status'); -- Should return 'status_sort_order'
SELECT get_sort_column_name('priority'); -- Should return 'priority_sort_order'
SELECT get_sort_column_name('phase'); -- Should return 'phase_sort_order'
SELECT get_sort_column_name('members'); -- Should return 'member_sort_order'
SELECT get_sort_column_name('unknown'); -- Should return 'status_sort_order' (default)
-- Test bulk update function (example - would need real project_id and task_ids)
/*
SELECT update_task_sort_orders_bulk(
'[
{"task_id": "example-uuid", "sort_order": 1, "status_id": "status-uuid"},
{"task_id": "example-uuid-2", "sort_order": 2, "status_id": "status-uuid"}
]'::json,
'status'
);
*/
-- Verify that sort_order constraint still exists and works
SELECT
tc.constraint_name,
tc.table_name,
kcu.column_name
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
WHERE tc.constraint_name = 'tasks_sort_order_unique';
-- Check that new sort order columns don't have unique constraints (which is correct)
SELECT
tc.constraint_name,
tc.table_name,
kcu.column_name
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
WHERE kcu.table_name = 'tasks'
AND kcu.column_name IN ('status_sort_order', 'priority_sort_order', 'phase_sort_order', 'member_sort_order')
AND tc.constraint_type = 'UNIQUE';

30
test_sort_orders.sql Normal file
View File

@@ -0,0 +1,30 @@
-- Test script to validate the separate sort order implementation
-- Check if new columns exist
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_name = 'tasks'
AND column_name IN ('status_sort_order', 'priority_sort_order', 'phase_sort_order', 'member_sort_order')
ORDER BY column_name;
-- Check if helper function exists
SELECT routine_name, routine_type
FROM information_schema.routines
WHERE routine_name IN ('get_sort_column_name', 'update_task_sort_orders_bulk', 'handle_task_list_sort_order_change');
-- Sample test data to verify different sort orders work
-- (This would be run after the migrations)
/*
-- Test: Tasks should have different orders for different groupings
SELECT
id,
name,
sort_order,
status_sort_order,
priority_sort_order,
phase_sort_order,
member_sort_order
FROM tasks
WHERE project_id = '<test-project-id>'
ORDER BY status_sort_order;
*/

View File

@@ -0,0 +1,300 @@
-- Fix Duplicate Sort Orders Script
-- This script detects and fixes duplicate sort order values that break task ordering
-- 1. DETECTION QUERIES - Run these first to see the scope of the problem
-- Check for duplicates in main sort_order column
SELECT
project_id,
sort_order,
COUNT(*) as duplicate_count,
STRING_AGG(id::text, ', ') as task_ids
FROM tasks
WHERE project_id IS NOT NULL
GROUP BY project_id, sort_order
HAVING COUNT(*) > 1
ORDER BY project_id, sort_order;
-- Check for duplicates in status_sort_order
SELECT
project_id,
status_sort_order,
COUNT(*) as duplicate_count,
STRING_AGG(id::text, ', ') as task_ids
FROM tasks
WHERE project_id IS NOT NULL
GROUP BY project_id, status_sort_order
HAVING COUNT(*) > 1
ORDER BY project_id, status_sort_order;
-- Check for duplicates in priority_sort_order
SELECT
project_id,
priority_sort_order,
COUNT(*) as duplicate_count,
STRING_AGG(id::text, ', ') as task_ids
FROM tasks
WHERE project_id IS NOT NULL
GROUP BY project_id, priority_sort_order
HAVING COUNT(*) > 1
ORDER BY project_id, priority_sort_order;
-- Check for duplicates in phase_sort_order
SELECT
project_id,
phase_sort_order,
COUNT(*) as duplicate_count,
STRING_AGG(id::text, ', ') as task_ids
FROM tasks
WHERE project_id IS NOT NULL
GROUP BY project_id, phase_sort_order
HAVING COUNT(*) > 1
ORDER BY project_id, phase_sort_order;
-- Note: member_sort_order removed - no longer used
-- 2. CLEANUP FUNCTIONS
-- Fix duplicates in main sort_order column
CREATE OR REPLACE FUNCTION fix_sort_order_duplicates() RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
_project RECORD;
_task RECORD;
_counter INTEGER;
BEGIN
-- For each project, reassign sort_order values to ensure uniqueness
FOR _project IN
SELECT DISTINCT project_id
FROM tasks
WHERE project_id IS NOT NULL
LOOP
_counter := 0;
-- Reassign sort_order values sequentially for this project
FOR _task IN
SELECT id
FROM tasks
WHERE project_id = _project.project_id
ORDER BY sort_order, created_at
LOOP
UPDATE tasks
SET sort_order = _counter
WHERE id = _task.id;
_counter := _counter + 1;
END LOOP;
END LOOP;
RAISE NOTICE 'Fixed sort_order duplicates for all projects';
END
$$;
-- Fix duplicates in status_sort_order column
CREATE OR REPLACE FUNCTION fix_status_sort_order_duplicates() RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
_project RECORD;
_task RECORD;
_counter INTEGER;
BEGIN
FOR _project IN
SELECT DISTINCT project_id
FROM tasks
WHERE project_id IS NOT NULL
LOOP
_counter := 0;
FOR _task IN
SELECT id
FROM tasks
WHERE project_id = _project.project_id
ORDER BY status_sort_order, created_at
LOOP
UPDATE tasks
SET status_sort_order = _counter
WHERE id = _task.id;
_counter := _counter + 1;
END LOOP;
END LOOP;
RAISE NOTICE 'Fixed status_sort_order duplicates for all projects';
END
$$;
-- Fix duplicates in priority_sort_order column
CREATE OR REPLACE FUNCTION fix_priority_sort_order_duplicates() RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
_project RECORD;
_task RECORD;
_counter INTEGER;
BEGIN
FOR _project IN
SELECT DISTINCT project_id
FROM tasks
WHERE project_id IS NOT NULL
LOOP
_counter := 0;
FOR _task IN
SELECT id
FROM tasks
WHERE project_id = _project.project_id
ORDER BY priority_sort_order, created_at
LOOP
UPDATE tasks
SET priority_sort_order = _counter
WHERE id = _task.id;
_counter := _counter + 1;
END LOOP;
END LOOP;
RAISE NOTICE 'Fixed priority_sort_order duplicates for all projects';
END
$$;
-- Fix duplicates in phase_sort_order column
CREATE OR REPLACE FUNCTION fix_phase_sort_order_duplicates() RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
_project RECORD;
_task RECORD;
_counter INTEGER;
BEGIN
FOR _project IN
SELECT DISTINCT project_id
FROM tasks
WHERE project_id IS NOT NULL
LOOP
_counter := 0;
FOR _task IN
SELECT id
FROM tasks
WHERE project_id = _project.project_id
ORDER BY phase_sort_order, created_at
LOOP
UPDATE tasks
SET phase_sort_order = _counter
WHERE id = _task.id;
_counter := _counter + 1;
END LOOP;
END LOOP;
RAISE NOTICE 'Fixed phase_sort_order duplicates for all projects';
END
$$;
-- Note: fix_member_sort_order_duplicates() removed - no longer needed
-- Master function to fix all sort order duplicates
CREATE OR REPLACE FUNCTION fix_all_duplicate_sort_orders() RETURNS void
LANGUAGE plpgsql
AS
$$
BEGIN
RAISE NOTICE 'Starting sort order cleanup for all columns...';
PERFORM fix_sort_order_duplicates();
PERFORM fix_status_sort_order_duplicates();
PERFORM fix_priority_sort_order_duplicates();
PERFORM fix_phase_sort_order_duplicates();
RAISE NOTICE 'Completed sort order cleanup for all columns';
END
$$;
-- 3. VERIFICATION FUNCTION
-- Verify that duplicates have been fixed
CREATE OR REPLACE FUNCTION verify_sort_order_integrity() RETURNS TABLE(
column_name text,
project_id uuid,
duplicate_count bigint,
status text
)
LANGUAGE plpgsql
AS
$$
BEGIN
-- Check sort_order duplicates
RETURN QUERY
SELECT
'sort_order'::text as column_name,
t.project_id,
COUNT(*) as duplicate_count,
CASE WHEN COUNT(*) > 1 THEN 'DUPLICATES FOUND' ELSE 'OK' END as status
FROM tasks t
WHERE t.project_id IS NOT NULL
GROUP BY t.project_id, t.sort_order
HAVING COUNT(*) > 1;
-- Check status_sort_order duplicates
RETURN QUERY
SELECT
'status_sort_order'::text as column_name,
t.project_id,
COUNT(*) as duplicate_count,
CASE WHEN COUNT(*) > 1 THEN 'DUPLICATES FOUND' ELSE 'OK' END as status
FROM tasks t
WHERE t.project_id IS NOT NULL
GROUP BY t.project_id, t.status_sort_order
HAVING COUNT(*) > 1;
-- Check priority_sort_order duplicates
RETURN QUERY
SELECT
'priority_sort_order'::text as column_name,
t.project_id,
COUNT(*) as duplicate_count,
CASE WHEN COUNT(*) > 1 THEN 'DUPLICATES FOUND' ELSE 'OK' END as status
FROM tasks t
WHERE t.project_id IS NOT NULL
GROUP BY t.project_id, t.priority_sort_order
HAVING COUNT(*) > 1;
-- Check phase_sort_order duplicates
RETURN QUERY
SELECT
'phase_sort_order'::text as column_name,
t.project_id,
COUNT(*) as duplicate_count,
CASE WHEN COUNT(*) > 1 THEN 'DUPLICATES FOUND' ELSE 'OK' END as status
FROM tasks t
WHERE t.project_id IS NOT NULL
GROUP BY t.project_id, t.phase_sort_order
HAVING COUNT(*) > 1;
-- Note: member_sort_order verification removed - column no longer used
END
$$;
-- 4. USAGE INSTRUCTIONS
/*
USAGE:
1. First, run the detection queries to see which projects have duplicates
2. Then run this to fix all duplicates:
SELECT fix_all_duplicate_sort_orders();
3. Finally, verify the fix worked:
SELECT * FROM verify_sort_order_integrity();
If verification returns no rows, all duplicates have been fixed successfully.
WARNING: This will reassign sort order values based on current order + creation time.
Make sure to backup your database before running these functions.
*/

View File

@@ -0,0 +1,37 @@
-- Migration: Add separate sort order columns for different grouping types
-- This allows users to maintain different task orders when switching between grouping views
-- Add new sort order columns
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS status_sort_order INTEGER DEFAULT 0;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS priority_sort_order INTEGER DEFAULT 0;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS phase_sort_order INTEGER DEFAULT 0;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS member_sort_order INTEGER DEFAULT 0;
-- Initialize new columns with current sort_order values
UPDATE tasks SET
status_sort_order = sort_order,
priority_sort_order = sort_order,
phase_sort_order = sort_order,
member_sort_order = sort_order
WHERE status_sort_order = 0
OR priority_sort_order = 0
OR phase_sort_order = 0
OR member_sort_order = 0;
-- Add constraints to ensure non-negative values
ALTER TABLE tasks ADD CONSTRAINT tasks_status_sort_order_check CHECK (status_sort_order >= 0);
ALTER TABLE tasks ADD CONSTRAINT tasks_priority_sort_order_check CHECK (priority_sort_order >= 0);
ALTER TABLE tasks ADD CONSTRAINT tasks_phase_sort_order_check CHECK (phase_sort_order >= 0);
ALTER TABLE tasks ADD CONSTRAINT tasks_member_sort_order_check CHECK (member_sort_order >= 0);
-- Add indexes for performance (since these will be used for ordering)
CREATE INDEX IF NOT EXISTS idx_tasks_status_sort_order ON tasks(project_id, status_sort_order);
CREATE INDEX IF NOT EXISTS idx_tasks_priority_sort_order ON tasks(project_id, priority_sort_order);
CREATE INDEX IF NOT EXISTS idx_tasks_phase_sort_order ON tasks(project_id, phase_sort_order);
CREATE INDEX IF NOT EXISTS idx_tasks_member_sort_order ON tasks(project_id, member_sort_order);
-- Update comments for documentation
COMMENT ON COLUMN tasks.status_sort_order IS 'Sort order when grouped by status';
COMMENT ON COLUMN tasks.priority_sort_order IS 'Sort order when grouped by priority';
COMMENT ON COLUMN tasks.phase_sort_order IS 'Sort order when grouped by phase';
COMMENT ON COLUMN tasks.member_sort_order IS 'Sort order when grouped by members/assignees';

View File

@@ -0,0 +1,172 @@
-- Migration: Update database functions to handle grouping-specific sort orders
-- Function to get the appropriate sort column name based on grouping type
CREATE OR REPLACE FUNCTION get_sort_column_name(_group_by TEXT) RETURNS TEXT
LANGUAGE plpgsql
AS
$$
BEGIN
CASE _group_by
WHEN 'status' THEN RETURN 'status_sort_order';
WHEN 'priority' THEN RETURN 'priority_sort_order';
WHEN 'phase' THEN RETURN 'phase_sort_order';
WHEN 'members' THEN RETURN 'member_sort_order';
ELSE RETURN 'sort_order'; -- fallback to general sort_order
END CASE;
END;
$$;
-- Updated bulk sort order function to handle different sort columns
CREATE OR REPLACE FUNCTION update_task_sort_orders_bulk(_updates json, _group_by text DEFAULT 'status') RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
_update_record RECORD;
_sort_column TEXT;
_sql TEXT;
BEGIN
-- Get the appropriate sort column based on grouping
_sort_column := get_sort_column_name(_group_by);
-- Simple approach: update each task's sort_order from the provided array
FOR _update_record IN
SELECT
(item->>'task_id')::uuid as task_id,
(item->>'sort_order')::int as sort_order,
(item->>'status_id')::uuid as status_id,
(item->>'priority_id')::uuid as priority_id,
(item->>'phase_id')::uuid as phase_id
FROM json_array_elements(_updates) as item
LOOP
-- Update the appropriate sort column and other fields using dynamic SQL
-- Only update sort_order if we're using the default sorting
IF _sort_column = 'sort_order' THEN
UPDATE tasks SET
sort_order = _update_record.sort_order,
status_id = COALESCE(_update_record.status_id, status_id),
priority_id = COALESCE(_update_record.priority_id, priority_id)
WHERE id = _update_record.task_id;
ELSE
-- Update only the grouping-specific sort column, not the main sort_order
_sql := 'UPDATE tasks SET ' || _sort_column || ' = $1, ' ||
'status_id = COALESCE($2, status_id), ' ||
'priority_id = COALESCE($3, priority_id) ' ||
'WHERE id = $4';
EXECUTE _sql USING
_update_record.sort_order,
_update_record.status_id,
_update_record.priority_id,
_update_record.task_id;
END IF;
-- Handle phase updates separately since it's in a different table
IF _update_record.phase_id IS NOT NULL THEN
INSERT INTO task_phase (task_id, phase_id)
VALUES (_update_record.task_id, _update_record.phase_id)
ON CONFLICT (task_id) DO UPDATE SET phase_id = _update_record.phase_id;
END IF;
END LOOP;
END;
$$;
-- Updated main sort order change handler
CREATE OR REPLACE FUNCTION handle_task_list_sort_order_change(_body json) RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
_from_index INT;
_to_index INT;
_task_id UUID;
_project_id UUID;
_from_group UUID;
_to_group UUID;
_group_by TEXT;
_batch_size INT := 100;
_sort_column TEXT;
_sql TEXT;
BEGIN
_project_id = (_body ->> 'project_id')::UUID;
_task_id = (_body ->> 'task_id')::UUID;
_from_index = (_body ->> 'from_index')::INT;
_to_index = (_body ->> 'to_index')::INT;
_from_group = (_body ->> 'from_group')::UUID;
_to_group = (_body ->> 'to_group')::UUID;
_group_by = (_body ->> 'group_by')::TEXT;
-- Get the appropriate sort column
_sort_column := get_sort_column_name(_group_by);
-- Handle group changes
IF (_from_group <> _to_group OR (_from_group <> _to_group) IS NULL) THEN
IF (_group_by = 'status') THEN
UPDATE tasks
SET status_id = _to_group
WHERE id = _task_id
AND status_id = _from_group
AND project_id = _project_id;
END IF;
IF (_group_by = 'priority') THEN
UPDATE tasks
SET priority_id = _to_group
WHERE id = _task_id
AND priority_id = _from_group
AND project_id = _project_id;
END IF;
IF (_group_by = 'phase') THEN
IF (is_null_or_empty(_to_group) IS FALSE) THEN
INSERT INTO task_phase (task_id, phase_id)
VALUES (_task_id, _to_group)
ON CONFLICT (task_id) DO UPDATE SET phase_id = _to_group;
ELSE
DELETE FROM task_phase WHERE task_id = _task_id;
END IF;
END IF;
END IF;
-- Handle sort order changes using dynamic SQL
IF (_from_index <> _to_index) THEN
-- For the main sort_order column, we need to be careful about unique constraints
IF _sort_column = 'sort_order' THEN
-- Use a transaction-safe approach for the main sort_order column
IF (_to_index > _from_index) THEN
-- Moving down: decrease sort_order for items between old and new position
UPDATE tasks SET sort_order = sort_order - 1
WHERE project_id = _project_id
AND sort_order > _from_index
AND sort_order <= _to_index;
ELSE
-- Moving up: increase sort_order for items between new and old position
UPDATE tasks SET sort_order = sort_order + 1
WHERE project_id = _project_id
AND sort_order >= _to_index
AND sort_order < _from_index;
END IF;
-- Set the new sort_order for the moved task
UPDATE tasks SET sort_order = _to_index WHERE id = _task_id;
ELSE
-- For grouping-specific columns, use dynamic SQL since there's no unique constraint
IF (_to_index > _from_index) THEN
-- Moving down: decrease sort_order for items between old and new position
_sql := 'UPDATE tasks SET ' || _sort_column || ' = ' || _sort_column || ' - 1 ' ||
'WHERE project_id = $1 AND ' || _sort_column || ' > $2 AND ' || _sort_column || ' <= $3';
EXECUTE _sql USING _project_id, _from_index, _to_index;
ELSE
-- Moving up: increase sort_order for items between new and old position
_sql := 'UPDATE tasks SET ' || _sort_column || ' = ' || _sort_column || ' + 1 ' ||
'WHERE project_id = $1 AND ' || _sort_column || ' >= $2 AND ' || _sort_column || ' < $3';
EXECUTE _sql USING _project_id, _to_index, _from_index;
END IF;
-- Set the new sort_order for the moved task
_sql := 'UPDATE tasks SET ' || _sort_column || ' = $1 WHERE id = $2';
EXECUTE _sql USING _to_index, _task_id;
END IF;
END IF;
END;
$$;

View File

@@ -0,0 +1,179 @@
-- Migration: Fix sort order constraint violations
-- First, let's ensure all existing tasks have unique sort_order values within each project
-- This is a one-time fix to ensure data consistency
DO $$
DECLARE
_project RECORD;
_task RECORD;
_counter INTEGER;
BEGIN
-- For each project, reassign sort_order values to ensure uniqueness
FOR _project IN
SELECT DISTINCT project_id
FROM tasks
WHERE project_id IS NOT NULL
LOOP
_counter := 0;
-- Reassign sort_order values sequentially for this project
FOR _task IN
SELECT id
FROM tasks
WHERE project_id = _project.project_id
ORDER BY sort_order, created_at
LOOP
UPDATE tasks
SET sort_order = _counter
WHERE id = _task.id;
_counter := _counter + 1;
END LOOP;
END LOOP;
END
$$;
-- Now create a better version of our functions that properly handles the constraints
-- Updated bulk sort order function that avoids sort_order conflicts
CREATE OR REPLACE FUNCTION update_task_sort_orders_bulk(_updates json, _group_by text DEFAULT 'status') RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
_update_record RECORD;
_sort_column TEXT;
_sql TEXT;
BEGIN
-- Get the appropriate sort column based on grouping
_sort_column := get_sort_column_name(_group_by);
-- Process each update record
FOR _update_record IN
SELECT
(item->>'task_id')::uuid as task_id,
(item->>'sort_order')::int as sort_order,
(item->>'status_id')::uuid as status_id,
(item->>'priority_id')::uuid as priority_id,
(item->>'phase_id')::uuid as phase_id
FROM json_array_elements(_updates) as item
LOOP
-- Update the grouping-specific sort column and other fields
_sql := 'UPDATE tasks SET ' || _sort_column || ' = $1, ' ||
'status_id = COALESCE($2, status_id), ' ||
'priority_id = COALESCE($3, priority_id), ' ||
'updated_at = CURRENT_TIMESTAMP ' ||
'WHERE id = $4';
EXECUTE _sql USING
_update_record.sort_order,
_update_record.status_id,
_update_record.priority_id,
_update_record.task_id;
-- Handle phase updates separately since it's in a different table
IF _update_record.phase_id IS NOT NULL THEN
INSERT INTO task_phase (task_id, phase_id)
VALUES (_update_record.task_id, _update_record.phase_id)
ON CONFLICT (task_id) DO UPDATE SET phase_id = _update_record.phase_id;
END IF;
END LOOP;
END;
$$;
-- Also update the helper function to be more explicit
CREATE OR REPLACE FUNCTION get_sort_column_name(_group_by TEXT) RETURNS TEXT
LANGUAGE plpgsql
AS
$$
BEGIN
CASE _group_by
WHEN 'status' THEN RETURN 'status_sort_order';
WHEN 'priority' THEN RETURN 'priority_sort_order';
WHEN 'phase' THEN RETURN 'phase_sort_order';
WHEN 'members' THEN RETURN 'member_sort_order';
-- For backward compatibility, still support general sort_order but be explicit
WHEN 'general' THEN RETURN 'sort_order';
ELSE RETURN 'status_sort_order'; -- Default to status sorting
END CASE;
END;
$$;
-- Updated main sort order change handler that avoids conflicts
CREATE OR REPLACE FUNCTION handle_task_list_sort_order_change(_body json) RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
_from_index INT;
_to_index INT;
_task_id UUID;
_project_id UUID;
_from_group UUID;
_to_group UUID;
_group_by TEXT;
_sort_column TEXT;
_sql TEXT;
BEGIN
_project_id = (_body ->> 'project_id')::UUID;
_task_id = (_body ->> 'task_id')::UUID;
_from_index = (_body ->> 'from_index')::INT;
_to_index = (_body ->> 'to_index')::INT;
_from_group = (_body ->> 'from_group')::UUID;
_to_group = (_body ->> 'to_group')::UUID;
_group_by = (_body ->> 'group_by')::TEXT;
-- Get the appropriate sort column
_sort_column := get_sort_column_name(_group_by);
-- Handle group changes first
IF (_from_group <> _to_group OR (_from_group <> _to_group) IS NULL) THEN
IF (_group_by = 'status') THEN
UPDATE tasks
SET status_id = _to_group, updated_at = CURRENT_TIMESTAMP
WHERE id = _task_id
AND project_id = _project_id;
END IF;
IF (_group_by = 'priority') THEN
UPDATE tasks
SET priority_id = _to_group, updated_at = CURRENT_TIMESTAMP
WHERE id = _task_id
AND project_id = _project_id;
END IF;
IF (_group_by = 'phase') THEN
IF (is_null_or_empty(_to_group) IS FALSE) THEN
INSERT INTO task_phase (task_id, phase_id)
VALUES (_task_id, _to_group)
ON CONFLICT (task_id) DO UPDATE SET phase_id = _to_group;
ELSE
DELETE FROM task_phase WHERE task_id = _task_id;
END IF;
END IF;
END IF;
-- Handle sort order changes for the grouping-specific column only
IF (_from_index <> _to_index) THEN
-- Update the grouping-specific sort order (no unique constraint issues)
IF (_to_index > _from_index) THEN
-- Moving down: decrease sort order for items between old and new position
_sql := 'UPDATE tasks SET ' || _sort_column || ' = ' || _sort_column || ' - 1, ' ||
'updated_at = CURRENT_TIMESTAMP ' ||
'WHERE project_id = $1 AND ' || _sort_column || ' > $2 AND ' || _sort_column || ' <= $3';
EXECUTE _sql USING _project_id, _from_index, _to_index;
ELSE
-- Moving up: increase sort order for items between new and old position
_sql := 'UPDATE tasks SET ' || _sort_column || ' = ' || _sort_column || ' + 1, ' ||
'updated_at = CURRENT_TIMESTAMP ' ||
'WHERE project_id = $1 AND ' || _sort_column || ' >= $2 AND ' || _sort_column || ' < $3';
EXECUTE _sql USING _project_id, _to_index, _from_index;
END IF;
-- Set the new sort order for the moved task
_sql := 'UPDATE tasks SET ' || _sort_column || ' = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2';
EXECUTE _sql USING _to_index, _task_id;
END IF;
END;
$$;

View File

@@ -1410,6 +1410,9 @@ CREATE TABLE IF NOT EXISTS tasks (
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL,
sort_order INTEGER DEFAULT 0 NOT NULL,
roadmap_sort_order INTEGER DEFAULT 0 NOT NULL,
status_sort_order INTEGER DEFAULT 0 NOT NULL,
priority_sort_order INTEGER DEFAULT 0 NOT NULL,
phase_sort_order INTEGER DEFAULT 0 NOT NULL,
billable BOOLEAN DEFAULT TRUE,
schedule_id UUID
);
@@ -1499,6 +1502,21 @@ ALTER TABLE tasks
ADD CONSTRAINT tasks_total_minutes_check
CHECK ((total_minutes >= (0)::NUMERIC) AND (total_minutes <= (999999)::NUMERIC));
-- Add constraints for new sort order columns
ALTER TABLE tasks ADD CONSTRAINT tasks_status_sort_order_check CHECK (status_sort_order >= 0);
ALTER TABLE tasks ADD CONSTRAINT tasks_priority_sort_order_check CHECK (priority_sort_order >= 0);
ALTER TABLE tasks ADD CONSTRAINT tasks_phase_sort_order_check CHECK (phase_sort_order >= 0);
-- Add indexes for performance on new sort order columns
CREATE INDEX IF NOT EXISTS idx_tasks_status_sort_order ON tasks(project_id, status_sort_order);
CREATE INDEX IF NOT EXISTS idx_tasks_priority_sort_order ON tasks(project_id, priority_sort_order);
CREATE INDEX IF NOT EXISTS idx_tasks_phase_sort_order ON tasks(project_id, phase_sort_order);
-- Add comments for documentation
COMMENT ON COLUMN tasks.status_sort_order IS 'Sort order when grouped by status';
COMMENT ON COLUMN tasks.priority_sort_order IS 'Sort order when grouped by priority';
COMMENT ON COLUMN tasks.phase_sort_order IS 'Sort order when grouped by phase';
CREATE TABLE IF NOT EXISTS tasks_assignees (
task_id UUID NOT NULL,
project_member_id UUID NOT NULL,

View File

@@ -4313,6 +4313,24 @@ BEGIN
END
$$;
-- Helper function to get the appropriate sort column name based on grouping type
CREATE OR REPLACE FUNCTION get_sort_column_name(_group_by TEXT) RETURNS TEXT
LANGUAGE plpgsql
AS
$$
BEGIN
CASE _group_by
WHEN 'status' THEN RETURN 'status_sort_order';
WHEN 'priority' THEN RETURN 'priority_sort_order';
WHEN 'phase' THEN RETURN 'phase_sort_order';
WHEN 'members' THEN RETURN 'member_sort_order';
-- For backward compatibility, still support general sort_order but be explicit
WHEN 'general' THEN RETURN 'sort_order';
ELSE RETURN 'status_sort_order'; -- Default to status sorting
END CASE;
END;
$$;
CREATE OR REPLACE FUNCTION handle_task_list_sort_order_change(_body json) RETURNS void
LANGUAGE plpgsql
AS
@@ -4325,66 +4343,67 @@ DECLARE
_from_group UUID;
_to_group UUID;
_group_by TEXT;
_batch_size INT := 100; -- PERFORMANCE OPTIMIZATION: Batch size for large updates
_sort_column TEXT;
_sql TEXT;
BEGIN
_project_id = (_body ->> 'project_id')::UUID;
_task_id = (_body ->> 'task_id')::UUID;
_from_index = (_body ->> 'from_index')::INT; -- from sort_order
_to_index = (_body ->> 'to_index')::INT; -- to sort_order
_from_index = (_body ->> 'from_index')::INT;
_to_index = (_body ->> 'to_index')::INT;
_from_group = (_body ->> 'from_group')::UUID;
_to_group = (_body ->> 'to_group')::UUID;
_group_by = (_body ->> 'group_by')::TEXT;
-- PERFORMANCE OPTIMIZATION: Use CTE for better query planning
IF (_from_group <> _to_group OR (_from_group <> _to_group) IS NULL)
THEN
-- PERFORMANCE OPTIMIZATION: Batch update group changes
IF (_group_by = 'status')
THEN
-- Get the appropriate sort column
_sort_column := get_sort_column_name(_group_by);
-- Handle group changes first
IF (_from_group <> _to_group OR (_from_group <> _to_group) IS NULL) THEN
IF (_group_by = 'status') THEN
UPDATE tasks
SET status_id = _to_group
SET status_id = _to_group, updated_at = CURRENT_TIMESTAMP
WHERE id = _task_id
AND status_id = _from_group
AND project_id = _project_id;
END IF;
IF (_group_by = 'priority')
THEN
IF (_group_by = 'priority') THEN
UPDATE tasks
SET priority_id = _to_group
SET priority_id = _to_group, updated_at = CURRENT_TIMESTAMP
WHERE id = _task_id
AND priority_id = _from_group
AND project_id = _project_id;
END IF;
IF (_group_by = 'phase')
THEN
IF (is_null_or_empty(_to_group) IS FALSE)
THEN
IF (_group_by = 'phase') THEN
IF (is_null_or_empty(_to_group) IS FALSE) THEN
INSERT INTO task_phase (task_id, phase_id)
VALUES (_task_id, _to_group)
ON CONFLICT (task_id) DO UPDATE SET phase_id = _to_group;
ELSE
DELETE FROM task_phase WHERE task_id = _task_id;
END IF;
IF (is_null_or_empty(_to_group) IS TRUE)
THEN
DELETE
FROM task_phase
WHERE task_id = _task_id;
END IF;
END IF;
-- PERFORMANCE OPTIMIZATION: Optimized sort order handling
IF ((_body ->> 'to_last_index')::BOOLEAN IS TRUE AND _from_index < _to_index)
THEN
PERFORM handle_task_list_sort_inside_group_optimized(_from_index, _to_index, _task_id, _project_id, _batch_size);
-- Handle sort order changes for the grouping-specific column only
IF (_from_index <> _to_index) THEN
-- Update the grouping-specific sort order (no unique constraint issues)
IF (_to_index > _from_index) THEN
-- Moving down: decrease sort order for items between old and new position
_sql := 'UPDATE tasks SET ' || _sort_column || ' = ' || _sort_column || ' - 1, ' ||
'updated_at = CURRENT_TIMESTAMP ' ||
'WHERE project_id = $1 AND ' || _sort_column || ' > $2 AND ' || _sort_column || ' <= $3';
EXECUTE _sql USING _project_id, _from_index, _to_index;
ELSE
PERFORM handle_task_list_sort_between_groups_optimized(_from_index, _to_index, _task_id, _project_id, _batch_size);
-- Moving up: increase sort order for items between new and old position
_sql := 'UPDATE tasks SET ' || _sort_column || ' = ' || _sort_column || ' + 1, ' ||
'updated_at = CURRENT_TIMESTAMP ' ||
'WHERE project_id = $1 AND ' || _sort_column || ' >= $2 AND ' || _sort_column || ' < $3';
EXECUTE _sql USING _project_id, _to_index, _from_index;
END IF;
ELSE
PERFORM handle_task_list_sort_inside_group_optimized(_from_index, _to_index, _task_id, _project_id, _batch_size);
-- Set the new sort order for the moved task
_sql := 'UPDATE tasks SET ' || _sort_column || ' = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2';
EXECUTE _sql USING _to_index, _task_id;
END IF;
END
$$;
@@ -4589,31 +4608,31 @@ BEGIN
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Progress', 'PROGRESS', 3, TRUE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Members', 'ASSIGNEES', 4, TRUE);
VALUES (_project_id, 'Status', 'STATUS', 4, TRUE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Labels', 'LABELS', 5, TRUE);
VALUES (_project_id, 'Members', 'ASSIGNEES', 5, TRUE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Status', 'STATUS', 6, TRUE);
VALUES (_project_id, 'Labels', 'LABELS', 6, TRUE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Priority', 'PRIORITY', 7, TRUE);
VALUES (_project_id, 'Phase', 'PHASE', 7, TRUE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Time Tracking', 'TIME_TRACKING', 8, TRUE);
VALUES (_project_id, 'Priority', 'PRIORITY', 8, TRUE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Estimation', 'ESTIMATION', 9, FALSE);
VALUES (_project_id, 'Time Tracking', 'TIME_TRACKING', 9, TRUE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Start Date', 'START_DATE', 10, FALSE);
VALUES (_project_id, 'Estimation', 'ESTIMATION', 10, FALSE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Due Date', 'DUE_DATE', 11, TRUE);
VALUES (_project_id, 'Start Date', 'START_DATE', 11, FALSE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Completed Date', 'COMPLETED_DATE', 12, FALSE);
VALUES (_project_id, 'Due Date', 'DUE_DATE', 12, TRUE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Created Date', 'CREATED_DATE', 13, FALSE);
VALUES (_project_id, 'Completed Date', 'COMPLETED_DATE', 13, FALSE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Last Updated', 'LAST_UPDATED', 14, FALSE);
VALUES (_project_id, 'Created Date', 'CREATED_DATE', 14, FALSE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Reporter', 'REPORTER', 15, FALSE);
VALUES (_project_id, 'Last Updated', 'LAST_UPDATED', 15, FALSE);
INSERT INTO project_task_list_cols (project_id, name, key, index, pinned)
VALUES (_project_id, 'Phase', 'PHASE', 16, FALSE);
VALUES (_project_id, 'Reporter', 'REPORTER', 16, FALSE);
END
$$;
@@ -6521,15 +6540,20 @@ BEGIN
END
$$;
-- Simple function to update task sort orders in bulk
CREATE OR REPLACE FUNCTION update_task_sort_orders_bulk(_updates json) RETURNS void
-- Updated bulk sort order function that avoids sort_order conflicts
CREATE OR REPLACE FUNCTION update_task_sort_orders_bulk(_updates json, _group_by text DEFAULT 'status') RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
_update_record RECORD;
_sort_column TEXT;
_sql TEXT;
BEGIN
-- Simple approach: update each task's sort_order from the provided array
-- Get the appropriate sort column based on grouping
_sort_column := get_sort_column_name(_group_by);
-- Process each update record
FOR _update_record IN
SELECT
(item->>'task_id')::uuid as task_id,
@@ -6539,12 +6563,18 @@ BEGIN
(item->>'phase_id')::uuid as phase_id
FROM json_array_elements(_updates) as item
LOOP
UPDATE tasks
SET
sort_order = _update_record.sort_order,
status_id = COALESCE(_update_record.status_id, status_id),
priority_id = COALESCE(_update_record.priority_id, priority_id)
WHERE id = _update_record.task_id;
-- Update the grouping-specific sort column and other fields
_sql := 'UPDATE tasks SET ' || _sort_column || ' = $1, ' ||
'status_id = COALESCE($2, status_id), ' ||
'priority_id = COALESCE($3, priority_id), ' ||
'updated_at = CURRENT_TIMESTAMP ' ||
'WHERE id = $4';
EXECUTE _sql USING
_update_record.sort_order,
_update_record.status_id,
_update_record.priority_id,
_update_record.task_id;
-- Handle phase updates separately since it's in a different table
IF _update_record.phase_id IS NOT NULL THEN
@@ -6555,3 +6585,66 @@ BEGIN
END LOOP;
END
$$;
-- Function to get the appropriate sort column name based on grouping type
CREATE OR REPLACE FUNCTION get_sort_column_name(_group_by TEXT) RETURNS TEXT
LANGUAGE plpgsql
AS
$$
BEGIN
CASE _group_by
WHEN 'status' THEN RETURN 'status_sort_order';
WHEN 'priority' THEN RETURN 'priority_sort_order';
WHEN 'phase' THEN RETURN 'phase_sort_order';
-- For backward compatibility, still support general sort_order but be explicit
WHEN 'general' THEN RETURN 'sort_order';
ELSE RETURN 'status_sort_order'; -- Default to status sorting
END CASE;
END;
$$;
-- Updated bulk sort order function to handle different sort columns
CREATE OR REPLACE FUNCTION update_task_sort_orders_bulk(_updates json, _group_by text DEFAULT 'status') RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
_update_record RECORD;
_sort_column TEXT;
_sql TEXT;
BEGIN
-- Get the appropriate sort column based on grouping
_sort_column := get_sort_column_name(_group_by);
-- Process each update record
FOR _update_record IN
SELECT
(item->>'task_id')::uuid as task_id,
(item->>'sort_order')::int as sort_order,
(item->>'status_id')::uuid as status_id,
(item->>'priority_id')::uuid as priority_id,
(item->>'phase_id')::uuid as phase_id
FROM json_array_elements(_updates) as item
LOOP
-- Update the grouping-specific sort column and other fields
_sql := 'UPDATE tasks SET ' || _sort_column || ' = $1, ' ||
'status_id = COALESCE($2, status_id), ' ||
'priority_id = COALESCE($3, priority_id), ' ||
'updated_at = CURRENT_TIMESTAMP ' ||
'WHERE id = $4';
EXECUTE _sql USING
_update_record.sort_order,
_update_record.status_id,
_update_record.priority_id,
_update_record.task_id;
-- Handle phase updates separately since it's in a different table
IF _update_record.phase_id IS NOT NULL THEN
INSERT INTO task_phase (task_id, phase_id)
VALUES (_update_record.task_id, _update_record.phase_id)
ON CONFLICT (task_id) DO UPDATE SET phase_id = _update_record.phase_id;
END IF;
END LOOP;
END;
$$;

View File

@@ -109,12 +109,29 @@ export default class TasksControllerV2 extends TasksControllerBase {
}
private static getQuery(userId: string, options: ParsedQs) {
const searchField = options.search ? ["t.name", "CONCAT((SELECT key FROM projects WHERE id = t.project_id), '-', task_no)"] : "sort_order";
// Determine which sort column to use based on grouping
const groupBy = options.group || 'status';
let defaultSortColumn = 'sort_order';
switch (groupBy) {
case 'status':
defaultSortColumn = 'status_sort_order';
break;
case 'priority':
defaultSortColumn = 'priority_sort_order';
break;
case 'phase':
defaultSortColumn = 'phase_sort_order';
break;
default:
defaultSortColumn = 'sort_order';
}
const searchField = options.search ? ["t.name", "CONCAT((SELECT key FROM projects WHERE id = t.project_id), '-', task_no)"] : defaultSortColumn;
const { searchQuery, sortField } = TasksControllerV2.toPaginationOptions(options, searchField);
const isSubTasks = !!options.parent_task;
const sortFields = sortField.replace(/ascend/g, "ASC").replace(/descend/g, "DESC") || "sort_order";
const sortFields = sortField.replace(/ascend/g, "ASC").replace(/descend/g, "DESC") || defaultSortColumn;
// Filter tasks by statuses
const statusesFilter = TasksControllerV2.getFilterByStatusWhereClosure(options.statuses as string);
@@ -196,6 +213,9 @@ export default class TasksControllerV2 extends TasksControllerBase {
t.archived,
t.description,
t.sort_order,
t.status_sort_order,
t.priority_sort_order,
t.phase_sort_order,
t.progress_value,
t.manual_progress,
t.weight,
@@ -1088,7 +1108,7 @@ export default class TasksControllerV2 extends TasksControllerBase {
custom_column_values: task.custom_column_values || {}, // Include custom column values
createdAt: task.created_at || new Date().toISOString(),
updatedAt: task.updated_at || new Date().toISOString(),
order: typeof task.sort_order === "number" ? task.sort_order : 0,
order: TasksControllerV2.getTaskSortOrder(task, groupBy),
// Additional metadata for frontend
originalStatusId: task.status,
originalPriorityId: task.priority,
@@ -1292,6 +1312,19 @@ export default class TasksControllerV2 extends TasksControllerBase {
}));
}
private static getTaskSortOrder(task: any, groupBy: string): number {
switch (groupBy) {
case GroupBy.STATUS:
return typeof task.status_sort_order === "number" ? task.status_sort_order : 0;
case GroupBy.PRIORITY:
return typeof task.priority_sort_order === "number" ? task.priority_sort_order : 0;
case GroupBy.PHASE:
return typeof task.phase_sort_order === "number" ? task.phase_sort_order : 0;
default:
return typeof task.sort_order === "number" ? task.sort_order : 0;
}
}
private static getDefaultGroupColor(groupBy: string, groupValue: string): string {
const colorMaps: Record<string, Record<string, string>> = {
[GroupBy.STATUS]: {

View File

@@ -53,11 +53,27 @@ function notifyStatusChange(socket: Socket, config: Config) {
}
async function emitSortOrderChange(data: ChangeRequest, socket: Socket) {
// Determine which sort column to use based on group_by
let sortColumn = "sort_order";
switch (data.group_by) {
case "status":
sortColumn = "status_sort_order";
break;
case "priority":
sortColumn = "priority_sort_order";
break;
case "phase":
sortColumn = "phase_sort_order";
break;
default:
sortColumn = "sort_order";
}
const q = `
SELECT id, sort_order, completed_at
SELECT id, sort_order, ${sortColumn} as current_sort_order, completed_at
FROM tasks
WHERE project_id = $1
ORDER BY sort_order;
ORDER BY ${sortColumn};
`;
const tasks = await db.query(q, [data.project_id]);
socket.emit(SocketEvents.TASK_SORT_ORDER_CHANGE.toString(), tasks.rows);
@@ -84,9 +100,9 @@ export async function on_task_sort_order_change(_io: Server, socket: Socket, dat
}
}
// Use the simple bulk update function
const q = `SELECT update_task_sort_orders_bulk($1);`;
await db.query(q, [JSON.stringify(data.task_updates)]);
// Use the simple bulk update function with group_by parameter
const q = `SELECT update_task_sort_orders_bulk($1, $2);`;
await db.query(q, [JSON.stringify(data.task_updates), data.group_by || "status"]);
await emitSortOrderChange(data, socket);
// Handle notifications and logging

View File

@@ -1,37 +1,43 @@
{
"taskHeader": {
"taskNamePlaceholder": "Shkruani Detyrën tuaj",
"deleteTask": "Fshi Detyrën"
"taskNamePlaceholder": "Shkruani detyrën tuaj",
"deleteTask": "Fshi detyrën",
"parentTask": "Detyra kryesore",
"currentTask": "Detyra aktuale",
"back": "Kthehu",
"backToParent": "Kthehu te detyra kryesore",
"toParentTask": "te detyra kryesore",
"loadingHierarchy": "Duke ngarkuar hierarkinë..."
},
"taskInfoTab": {
"title": "Informacioni",
"details": {
"title": "Detajet",
"task-key": "Çelësi i Detyrës",
"task-key": "Çelësi i detyrës",
"phase": "Faza",
"assignees": "Të Caktuar",
"due-date": "Data e Përfundimit",
"time-estimation": "Vlerësimi i Kohës",
"assignees": "Të caktuarit",
"due-date": "Data e përfundimit",
"time-estimation": "Vlerësimi i kohës",
"priority": "Prioriteti",
"labels": "Etiketat",
"billable": "E Faturueshme",
"billable": "I faturueshëm",
"notify": "Njofto",
"when-done-notify": "Kur përfundon, njofto",
"start-date": "Data e Fillimit",
"end-date": "Data e Përfundimit",
"hide-start-date": "Fshih Datën e Fillimit",
"show-start-date": "Shfaq Datën e Fillimit",
"start-date": "Data e fillimit",
"end-date": "Data e përfundimit",
"hide-start-date": "Fshih datën e fillimit",
"show-start-date": "Shfaq datën e fillimit",
"hours": "Orë",
"minutes": "Minuta",
"progressValue": "Vlera e Progresit",
"progressValueTooltip": "Vendosni përqindjen e progresit (0-100%)",
"progressValue": "Vlera e progresit",
"progressValueTooltip": "Vendos përqindjen e progresit (0-100%)",
"progressValueRequired": "Ju lutemi vendosni një vlerë progresi",
"progressValueRange": "Progresi duhet të jetë midis 0 dhe 100",
"taskWeight": "Pesha e Detyrës",
"taskWeightTooltip": "Vendosni peshën e kësaj nëndetyre (përqindje)",
"taskWeight": "Pesha e detyrës",
"taskWeightTooltip": "Vendos peshën e kësaj nëndetyre (përqindje)",
"taskWeightRequired": "Ju lutemi vendosni një peshë detyre",
"taskWeightRange": "Pesha duhet të jetë midis 0 dhe 100",
"recurring": "E Përsëritur"
"recurring": "Përsëritëse"
},
"labels": {
"labelInputPlaceholder": "Kërko ose krijo",
@@ -43,71 +49,71 @@
},
"subTasks": {
"title": "Nëndetyrat",
"addSubTask": "Shto Nëndetyrë",
"addSubTask": "Shto nëndetyrë",
"addSubTaskInputPlaceholder": "Shkruani detyrën tuaj dhe shtypni enter",
"refreshSubTasks": "Rifresko Nëndetyrat",
"edit": "Modifiko",
"refreshSubTasks": "Rifresko nëndetyrat",
"edit": "Redakto",
"delete": "Fshi",
"confirmDeleteSubTask": "Jeni i sigurt që doni të fshini këtë nëndetyrë?",
"deleteSubTask": "Fshi Nëndetyrën"
"confirmDeleteSubTask": "Jeni i sigurt që dëshironi ta fshini këtë nëndetyrë?",
"deleteSubTask": "Fshi nëndetyrën"
},
"dependencies": {
"title": "Varësitë",
"addDependency": "+ Shto varësi të re",
"blockedBy": "Bllokuar nga",
"searchTask": "Shkruani për të kërkuar detyrë",
"searchTask": "Shkruaj për të kërkuar detyrën",
"noTasksFound": "Nuk u gjetën detyra",
"confirmDeleteDependency": "Jeni i sigurt që doni të fshini?"
"confirmDeleteDependency": "Jeni i sigurt që dëshironi ta fshini?"
},
"attachments": {
"title": "Bashkëngjitjet",
"chooseOrDropFileToUpload": "Zgjidhni ose hidhni skedar për të ngarkuar",
"chooseOrDropFileToUpload": "Zgjidh ose lësho skedarin për ta ngarkuar",
"uploading": "Duke ngarkuar..."
},
"comments": {
"title": "Komentet",
"addComment": "+ Shto koment të ri",
"noComments": "Ende pa komente. Bëhu i pari që komenton!",
"noComments": "Ende pa komente. Bëhu i pari që komentoni!",
"delete": "Fshi",
"confirmDeleteComment": "Jeni i sigurt që doni të fshini këtë koment?",
"confirmDeleteComment": "Jeni i sigurt që dëshironi ta fshini këtë koment?",
"addCommentPlaceholder": "Shto një koment...",
"cancel": "Anulo",
"commentButton": "Komento",
"attachFiles": "Bashkëngjit skedarë",
"addMoreFiles": "Shto më shumë skedarë",
"selectedFiles": "Skedarët e Zgjedhur (Deri në 25MB, Maksimumi {count})",
"maxFilesError": "Mund të ngarkoni maksimum {count} skedarë",
"processFilesError": "Dështoi përpunimi i skedarëve",
"selectedFiles": "Skedarët e zgjedhur (Deri në 25MB, Maksimumi {count})",
"maxFilesError": "Mund të ngarkoni maksimumi {count} skedarë",
"processFilesError": "Dështoi përpunimin e skedarëve",
"addCommentError": "Ju lutemi shtoni një koment ose bashkëngjitni skedarë",
"createdBy": "Krijuar {{time}} nga {{user}}",
"updatedTime": "Përditësuar {{time}}"
},
"searchInputPlaceholder": "Kërko sipas emrit",
"pendingInvitation": "Ftesë në Pritje"
"pendingInvitation": "Ftesë në pritje"
},
"taskTimeLogTab": {
"title": "Regjistri i Kohës",
"addTimeLog": "Shto regjistrim të ri kohe",
"totalLogged": "Totali i Regjistruar",
"title": "Regjistri i kohës",
"addTimeLog": "Shto regjistër të ri kohe",
"totalLogged": "Totali i regjistruar",
"exportToExcel": "Eksporto në Excel",
"noTimeLogsFound": "Nuk u gjetën regjistra kohe",
"noTimeLogsFound": "Nuk u gjetën regjistrime kohe",
"timeLogForm": {
"date": "Data",
"startTime": "Koha e Fillimit",
"endTime": "Koha e Përfundimit",
"workDescription": "Përshkrimi i Punës",
"startTime": "Ora e fillimit",
"endTime": "Ora e përfundimit",
"workDescription": "Përshkrimi i punës",
"descriptionPlaceholder": "Shto një përshkrim",
"logTime": "Regjistro kohën",
"updateTime": "Përditëso kohën",
"cancel": "Anulo",
"selectDateError": "Ju lutemi zgjidhni një datë",
"selectStartTimeError": "Ju lutemi zgjidhni kohën e fillimit",
"selectEndTimeError": "Ju lutemi zgjidhni kohën e përfundimit",
"endTimeAfterStartError": "Koha e përfundimit duhet të jetë pas kohës së fillimit"
"selectStartTimeError": "Ju lutemi zgjidhni orën e fillimit",
"selectEndTimeError": "Ju lutemi zgjidhni orën e përfundimit",
"endTimeAfterStartError": "Ora e përfundimit duhet të jetë pas orës së fillimit"
}
},
"taskActivityLogTab": {
"title": "Regjistri i Aktivitetit",
"title": "Regjistri i aktivitetit",
"add": "SHTO",
"remove": "HIQE",
"none": "Asnjë",
@@ -115,9 +121,9 @@
"createdTask": "krijoi detyrën."
},
"taskProgress": {
"markAsDoneTitle": "Shëno Detyrën si të Kryer?",
"confirmMarkAsDone": "Po, shëno si të kryer",
"cancelMarkAsDone": "Jo, mbaj statusin aktual",
"markAsDoneDescription": "Keni vendosur progresin në 100%. Doni të përditësoni statusin e detyrës në \"Kryer\"?"
"markAsDoneTitle": "Shëno detyrën si të përfunduar?",
"confirmMarkAsDone": "Po, shënoje si të përfunduar",
"cancelMarkAsDone": "Jo, mbaj gjendjen aktuale",
"markAsDoneDescription": "Keni vendosur progresin në 100%. Dëshironi ta përditësoni gjendjen e detyrës në \"Përfunduar\"?"
}
}

View File

@@ -39,6 +39,7 @@
"addTaskText": "Shto Detyrë",
"addSubTaskText": "+ Shto Nën-Detyrë",
"noTasksInGroup": "Nuk ka detyra në këtë grup",
"dropTaskHere": "Lëshoje detyrën këtu",
"addTaskInputPlaceholder": "Shkruaj detyrën dhe shtyp Enter",
"openButton": "Hap",

View File

@@ -1,22 +1,28 @@
{
"taskHeader": {
"taskNamePlaceholder": "Geben Sie Ihre Aufgabe ein",
"deleteTask": "Aufgabe löschen"
"deleteTask": "Aufgabe löschen",
"parentTask": "Übergeordnete Aufgabe",
"currentTask": "Aktuelle Aufgabe",
"back": "Zurück",
"backToParent": "Zurück zur übergeordneten Aufgabe",
"toParentTask": "zur übergeordneten Aufgabe",
"loadingHierarchy": "Hierarchie wird geladen..."
},
"taskInfoTab": {
"title": "Info",
"details": {
"title": "Details",
"task-key": "Aufgaben-Schlüssel",
"task-key": "Aufgabenschlüssel",
"phase": "Phase",
"assignees": "Beauftragte",
"assignees": "Zugewiesene",
"due-date": "Fälligkeitsdatum",
"time-estimation": "Zeitschätzung",
"priority": "Priorität",
"labels": "Labels",
"billable": "Abrechenbar",
"notify": "Benachrichtigen",
"when-done-notify": "Bei Abschluss benachrichtigen",
"when-done-notify": "Bei Fertigstellung benachrichtigen",
"start-date": "Startdatum",
"end-date": "Enddatum",
"hide-start-date": "Startdatum ausblenden",
@@ -24,50 +30,50 @@
"hours": "Stunden",
"minutes": "Minuten",
"progressValue": "Fortschrittswert",
"progressValueTooltip": "Fortschritt in Prozent einstellen (0-100%)",
"progressValueTooltip": "Setzen Sie den Fortschrittsprozentsatz (0-100%)",
"progressValueRequired": "Bitte geben Sie einen Fortschrittswert ein",
"progressValueRange": "Fortschritt muss zwischen 0 und 100 liegen",
"taskWeight": "Aufgabengewicht",
"taskWeightTooltip": "Gewicht dieser Teilaufgabe festlegen (Prozent)",
"taskWeightTooltip": "Setzen Sie das Gewicht dieser Unteraufgabe (Prozentsatz)",
"taskWeightRequired": "Bitte geben Sie ein Aufgabengewicht ein",
"taskWeightRange": "Gewicht muss zwischen 0 und 100 liegen",
"recurring": "Wiederkehrend"
},
"labels": {
"labelInputPlaceholder": "Suchen oder erstellen",
"labelsSelectorInputTip": "Enter drücken zum Erstellen"
"labelsSelectorInputTip": "Drücken Sie Enter zum Erstellen"
},
"description": {
"title": "Beschreibung",
"placeholder": "Detailliertere Beschreibung hinzufügen..."
"placeholder": "Fügen Sie eine detailliertere Beschreibung hinzu..."
},
"subTasks": {
"title": "Teilaufgaben",
"addSubTask": "Teilaufgabe hinzufügen",
"title": "Unteraufgaben",
"addSubTask": "Unteraufgabe hinzufügen",
"addSubTaskInputPlaceholder": "Geben Sie Ihre Aufgabe ein und drücken Sie Enter",
"refreshSubTasks": "Teilaufgaben aktualisieren",
"refreshSubTasks": "Unteraufgaben aktualisieren",
"edit": "Bearbeiten",
"delete": "Löschen",
"confirmDeleteSubTask": "Sind Sie sicher, dass Sie diese Teilaufgabe löschen möchten?",
"deleteSubTask": "Teilaufgabe löschen"
"confirmDeleteSubTask": "Sind Sie sicher, dass Sie diese Unteraufgabe löschen möchten?",
"deleteSubTask": "Unteraufgabe löschen"
},
"dependencies": {
"title": "Abhängigkeiten",
"addDependency": "+ Neue Abhängigkeit hinzufügen",
"blockedBy": "Blockiert von",
"searchTask": "Aufgabe suchen",
"searchTask": "Zum Suchen der Aufgabe eingeben",
"noTasksFound": "Keine Aufgaben gefunden",
"confirmDeleteDependency": "Sind Sie sicher, dass Sie löschen möchten?"
},
"attachments": {
"title": "Anhänge",
"chooseOrDropFileToUpload": "Datei zum Hochladen wählen oder ablegen",
"chooseOrDropFileToUpload": "Datei zum Hochladen auswählen oder ablegen",
"uploading": "Wird hochgeladen..."
},
"comments": {
"title": "Kommentare",
"addComment": "+ Neuen Kommentar hinzufügen",
"noComments": "Noch keine Kommentare. Seien Sie der Erste!",
"noComments": "Noch keine Kommentare. Seien Sie der Erste, der kommentiert!",
"delete": "Löschen",
"confirmDeleteComment": "Sind Sie sicher, dass Sie diesen Kommentar löschen möchten?",
"addCommentPlaceholder": "Kommentar hinzufügen...",
@@ -75,9 +81,9 @@
"commentButton": "Kommentieren",
"attachFiles": "Dateien anhängen",
"addMoreFiles": "Weitere Dateien hinzufügen",
"selectedFiles": "Ausgewählte Dateien (Bis zu 25MB, Maximum {count})",
"selectedFiles": "Ausgewählte Dateien (Bis zu 25MB, Maximum von {count})",
"maxFilesError": "Sie können maximal {count} Dateien hochladen",
"processFilesError": "Fehler beim Verarbeiten der Dateien",
"processFilesError": "Dateien konnten nicht verarbeitet werden",
"addCommentError": "Bitte fügen Sie einen Kommentar hinzu oder hängen Sie Dateien an",
"createdBy": "Erstellt {{time}} von {{user}}",
"updatedTime": "Aktualisiert {{time}}"
@@ -86,18 +92,18 @@
"pendingInvitation": "Ausstehende Einladung"
},
"taskTimeLogTab": {
"title": "Zeiterfassung",
"addTimeLog": "Neuen Zeiteintrag hinzufügen",
"totalLogged": "Gesamt erfasst",
"title": "Zeitprotokoll",
"addTimeLog": "Neues Zeitprotokoll hinzufügen",
"totalLogged": "Gesamt protokolliert",
"exportToExcel": "Nach Excel exportieren",
"noTimeLogsFound": "Keine Zeiteinträge gefunden",
"noTimeLogsFound": "Keine Zeitprotokolle gefunden",
"timeLogForm": {
"date": "Datum",
"startTime": "Startzeit",
"endTime": "Endzeit",
"workDescription": "Arbeitsbeschreibung",
"descriptionPlaceholder": "Beschreibung hinzufügen",
"logTime": "Zeit erfassen",
"logTime": "Zeit protokollieren",
"updateTime": "Zeit aktualisieren",
"cancel": "Abbrechen",
"selectDateError": "Bitte wählen Sie ein Datum",

View File

@@ -40,6 +40,7 @@
"addSubTaskText": "+ Unteraufgabe hinzufügen",
"addTaskInputPlaceholder": "Aufgabe eingeben und Enter drücken",
"noTasksInGroup": "Keine Aufgaben in dieser Gruppe",
"dropTaskHere": "Aufgabe hier ablegen",
"openButton": "Öffnen",
"okButton": "OK",

View File

@@ -1,7 +1,13 @@
{
"taskHeader": {
"taskNamePlaceholder": "Type your Task",
"deleteTask": "Delete Task"
"deleteTask": "Delete Task",
"parentTask": "Parent Task",
"currentTask": "Current Task",
"back": "Back",
"backToParent": "Back to Parent Task",
"toParentTask": "to parent task",
"loadingHierarchy": "Loading hierarchy..."
},
"taskInfoTab": {
"title": "Info",

View File

@@ -40,6 +40,7 @@
"addSubTaskText": "Add Sub Task",
"addTaskInputPlaceholder": "Type your task and hit enter",
"noTasksInGroup": "No tasks in this group",
"dropTaskHere": "Drop task here",
"openButton": "Open",
"okButton": "Ok",

View File

@@ -1,35 +1,41 @@
{
"taskHeader": {
"taskNamePlaceholder": "Escriba su Tarea",
"deleteTask": "Eliminar Tarea"
"taskNamePlaceholder": "Escribe tu tarea",
"deleteTask": "Eliminar tarea",
"parentTask": "Tarea principal",
"currentTask": "Tarea actual",
"back": "Volver",
"backToParent": "Volver a la tarea principal",
"toParentTask": "a la tarea principal",
"loadingHierarchy": "Cargando jerarquía..."
},
"taskInfoTab": {
"title": "Información",
"details": {
"title": "Detalles",
"task-key": "Clave de Tarea",
"task-key": "Clave de tarea",
"phase": "Fase",
"assignees": "Asignados",
"due-date": "Fecha de Vencimiento",
"time-estimation": "Estimación de Tiempo",
"due-date": "Fecha de vencimiento",
"time-estimation": "Estimación de tiempo",
"priority": "Prioridad",
"labels": "Etiquetas",
"billable": "Facturable",
"notify": "Notificar",
"when-done-notify": "Al terminar, notificar",
"start-date": "Fecha de Inicio",
"end-date": "Fecha de Fin",
"hide-start-date": "Ocultar Fecha de Inicio",
"show-start-date": "Mostrar Fecha de Inicio",
"when-done-notify": "Al finalizar, notificar",
"start-date": "Fecha de inicio",
"end-date": "Fecha de finalización",
"hide-start-date": "Ocultar fecha de inicio",
"show-start-date": "Mostrar fecha de inicio",
"hours": "Horas",
"minutes": "Minutos",
"progressValue": "Valor de Progreso",
"progressValue": "Valor de progreso",
"progressValueTooltip": "Establecer el porcentaje de progreso (0-100%)",
"progressValueRequired": "Por favor, introduzca un valor de progreso",
"progressValueRequired": "Por favor ingrese un valor de progreso",
"progressValueRange": "El progreso debe estar entre 0 y 100",
"taskWeight": "Peso de la Tarea",
"taskWeight": "Peso de la tarea",
"taskWeightTooltip": "Establecer el peso de esta subtarea (porcentaje)",
"taskWeightRequired": "Por favor, introduzca un peso de tarea",
"taskWeightRequired": "Por favor ingrese un peso de tarea",
"taskWeightRange": "El peso debe estar entre 0 y 100",
"recurring": "Recurrente"
},
@@ -39,85 +45,85 @@
},
"description": {
"title": "Descripción",
"placeholder": "Añadir una descripción más detallada..."
"placeholder": "Añade una descripción más detallada..."
},
"subTasks": {
"title": "Sub Tareas",
"addSubTask": "Agregar Sub Tarea",
"addSubTaskInputPlaceholder": "Escriba su tarea y presione enter",
"refreshSubTasks": "Actualizar Sub Tareas",
"title": "Subtareas",
"addSubTask": "Añadir subtarea",
"addSubTaskInputPlaceholder": "Escribe tu tarea y presiona enter",
"refreshSubTasks": "Actualizar subtareas",
"edit": "Editar",
"delete": "Eliminar",
"confirmDeleteSubTask": "¿Está seguro de que desea eliminar esta subtarea?",
"deleteSubTask": "Eliminar Sub Tarea"
"confirmDeleteSubTask": "¿Estás seguro de que quieres eliminar esta subtarea?",
"deleteSubTask": "Eliminar subtarea"
},
"dependencies": {
"title": "Dependencias",
"addDependency": "+ Agregar nueva dependencia",
"addDependency": "+ Añadir nueva dependencia",
"blockedBy": "Bloqueado por",
"searchTask": "Escribir para buscar tarea",
"searchTask": "Escribe para buscar tarea",
"noTasksFound": "No se encontraron tareas",
"confirmDeleteDependency": "¿Está seguro de que desea eliminar?"
"confirmDeleteDependency": "¿Estás seguro de que quieres eliminar?"
},
"attachments": {
"title": "Adjuntos",
"chooseOrDropFileToUpload": "Elija o arrastre un archivo para subir",
"chooseOrDropFileToUpload": "Elige o arrastra archivo para subir",
"uploading": "Subiendo..."
},
"comments": {
"title": "Comentarios",
"addComment": "+ Agregar nuevo comentario",
"addComment": "+ Añadir nuevo comentario",
"noComments": "Aún no hay comentarios. ¡Sé el primero en comentar!",
"delete": "Eliminar",
"confirmDeleteComment": "¿Está seguro de que desea eliminar este comentario?",
"addCommentPlaceholder": "Agregar un comentario...",
"confirmDeleteComment": "¿Estás seguro de que quieres eliminar este comentario?",
"addCommentPlaceholder": "Añadir un comentario...",
"cancel": "Cancelar",
"commentButton": "Comentar",
"attachFiles": "Adjuntar archivos",
"addMoreFiles": "Agregar más archivos",
"selectedFiles": "Archivos Seleccionados (Hasta 25MB, Máximo {count})",
"maxFilesError": "Solo puede subir un máximo de {count} archivos",
"addMoreFiles": "Añadir más archivos",
"selectedFiles": "Archivos seleccionados (Hasta 25MB, Máximo de {count})",
"maxFilesError": "Solo puedes subir un máximo de {count} archivos",
"processFilesError": "Error al procesar archivos",
"addCommentError": "Por favor agregue un comentario o adjunte archivos",
"addCommentError": "Por favor añade un comentario o adjunta archivos",
"createdBy": "Creado {{time}} por {{user}}",
"updatedTime": "Actualizado {{time}}"
},
"searchInputPlaceholder": "Buscar por nombre",
"pendingInvitation": "Invitación Pendiente"
"pendingInvitation": "Invitación pendiente"
},
"taskTimeLogTab": {
"title": "Registro de Tiempo",
"title": "Registro de tiempo",
"addTimeLog": "Añadir nuevo registro de tiempo",
"totalLogged": "Total Registrado",
"totalLogged": "Total registrado",
"exportToExcel": "Exportar a Excel",
"noTimeLogsFound": "No se encontraron registros de tiempo",
"timeLogForm": {
"date": "Fecha",
"startTime": "Hora de Inicio",
"endTime": "Hora de Fin",
"workDescription": "Descripción del Trabajo",
"descriptionPlaceholder": "Agregar una descripción",
"startTime": "Hora de inicio",
"endTime": "Hora de finalización",
"workDescription": "Descripción del trabajo",
"descriptionPlaceholder": "Añadir una descripción",
"logTime": "Registrar tiempo",
"updateTime": "Actualizar tiempo",
"cancel": "Cancelar",
"selectDateError": "Por favor seleccione una fecha",
"selectStartTimeError": "Por favor seleccione la hora de inicio",
"selectEndTimeError": "Por favor seleccione la hora de fin",
"endTimeAfterStartError": "La hora de fin debe ser posterior a la hora de inicio"
"selectDateError": "Por favor selecciona una fecha",
"selectStartTimeError": "Por favor selecciona hora de inicio",
"selectEndTimeError": "Por favor selecciona hora de finalización",
"endTimeAfterStartError": "La hora de finalización debe ser posterior a la de inicio"
}
},
"taskActivityLogTab": {
"title": "Registro de Actividad",
"add": "AGREGAR",
"remove": "QUITAR",
"title": "Registro de actividad",
"add": "AÑADIR",
"remove": "ELIMINAR",
"none": "Ninguno",
"weight": "Peso",
"createdTask": "creó la tarea."
},
"taskProgress": {
"markAsDoneTitle": "¿Marcar Tarea como Completada?",
"markAsDoneTitle": "¿Marcar tarea como completada?",
"confirmMarkAsDone": "Sí, marcar como completada",
"cancelMarkAsDone": "No, mantener estado actual",
"markAsDoneDescription": "Ha establecido el progreso al 100%. ¿Le gustaría actualizar el estado de la tarea a \"Completada\"?"
"markAsDoneDescription": "Has establecido el progreso al 100%. ¿Te gustaría actualizar el estado de la tarea a \"Completada\"?"
}
}

View File

@@ -39,6 +39,7 @@
"addTaskText": "Agregar tarea",
"addSubTaskText": "Agregar subtarea",
"noTasksInGroup": "No hay tareas en este grupo",
"dropTaskHere": "Soltar tarea aquí",
"addTaskInputPlaceholder": "Escribe tu tarea y presiona enter",
"openButton": "Abrir",

View File

@@ -1,33 +1,39 @@
{
"taskHeader": {
"taskNamePlaceholder": "Digite sua Tarefa",
"deleteTask": "Deletar Tarefa"
"taskNamePlaceholder": "Digite sua tarefa",
"deleteTask": "Excluir tarefa",
"parentTask": "Tarefa principal",
"currentTask": "Tarefa atual",
"back": "Voltar",
"backToParent": "Voltar à tarefa principal",
"toParentTask": "à tarefa principal",
"loadingHierarchy": "Carregando hierarquia..."
},
"taskInfoTab": {
"title": "Informações",
"details": {
"title": "Detalhes",
"task-key": "Chave da Tarefa",
"task-key": "Chave da tarefa",
"phase": "Fase",
"assignees": "Responsáveis",
"due-date": "Data de Vencimento",
"time-estimation": "Estimativa de Tempo",
"due-date": "Data de vencimento",
"time-estimation": "Estimativa de tempo",
"priority": "Prioridade",
"labels": "Etiquetas",
"billable": "Faturável",
"notify": "Notificar",
"when-done-notify": "Quando concluído, notificar",
"start-date": "Data de Início",
"end-date": "Data de Fim",
"hide-start-date": "Ocultar Data de Início",
"show-start-date": "Mostrar Data de Início",
"when-done-notify": "Ao concluir, notificar",
"start-date": "Data de início",
"end-date": "Data de término",
"hide-start-date": "Ocultar data de início",
"show-start-date": "Mostrar data de início",
"hours": "Horas",
"minutes": "Minutos",
"progressValue": "Valor do Progresso",
"progressValue": "Valor do progresso",
"progressValueTooltip": "Definir a porcentagem de progresso (0-100%)",
"progressValueRequired": "Por favor, insira um valor de progresso",
"progressValueRange": "O progresso deve estar entre 0 e 100",
"taskWeight": "Peso da Tarefa",
"taskWeight": "Peso da tarefa",
"taskWeightTooltip": "Definir o peso desta subtarefa (porcentagem)",
"taskWeightRequired": "Por favor, insira um peso da tarefa",
"taskWeightRange": "O peso deve estar entre 0 e 100",
@@ -39,17 +45,17 @@
},
"description": {
"title": "Descrição",
"placeholder": "Adicionar uma descrição mais detalhada..."
"placeholder": "Adicione uma descrição mais detalhada..."
},
"subTasks": {
"title": "Sub Tarefas",
"addSubTask": "Adicionar Sub Tarefa",
"title": "Subtarefas",
"addSubTask": "Adicionar subtarefa",
"addSubTaskInputPlaceholder": "Digite sua tarefa e pressione enter",
"refreshSubTasks": "Atualizar Sub Tarefas",
"refreshSubTasks": "Atualizar subtarefas",
"edit": "Editar",
"delete": "Deletar",
"confirmDeleteSubTask": "Tem certeza de que deseja deletar esta subtarefa?",
"deleteSubTask": "Deletar Sub Tarefa"
"delete": "Excluir",
"confirmDeleteSubTask": "Tem certeza de que deseja excluir esta subtarefa?",
"deleteSubTask": "Excluir subtarefa"
},
"dependencies": {
"title": "Dependências",
@@ -57,57 +63,57 @@
"blockedBy": "Bloqueado por",
"searchTask": "Digite para pesquisar tarefa",
"noTasksFound": "Nenhuma tarefa encontrada",
"confirmDeleteDependency": "Tem certeza de que deseja deletar?"
"confirmDeleteDependency": "Tem certeza de que deseja excluir?"
},
"attachments": {
"title": "Anexos",
"chooseOrDropFileToUpload": "Escolha ou arraste um arquivo para upload",
"chooseOrDropFileToUpload": "Escolha ou arraste arquivo para enviar",
"uploading": "Enviando..."
},
"comments": {
"title": "Comentários",
"addComment": "+ Adicionar novo comentário",
"noComments": "Ainda não há comentários. Seja o primeiro a comentar!",
"delete": "Deletar",
"confirmDeleteComment": "Tem certeza de que deseja deletar este comentário?",
"delete": "Excluir",
"confirmDeleteComment": "Tem certeza de que deseja excluir este comentário?",
"addCommentPlaceholder": "Adicionar um comentário...",
"cancel": "Cancelar",
"commentButton": "Comentar",
"attachFiles": "Anexar arquivos",
"addMoreFiles": "Adicionar mais arquivos",
"selectedFiles": "Arquivos Selecionados (Até 25MB, Máximo {count})",
"maxFilesError": "Você pode fazer upload de no máximo {count} arquivos",
"selectedFiles": "Arquivos selecionados (Até 25MB, Máximo de {count})",
"maxFilesError": "Você pode enviar no máximo {count} arquivos",
"processFilesError": "Falha ao processar arquivos",
"addCommentError": "Por favor adicione um comentário ou anexe arquivos",
"addCommentError": "Por favor, adicione um comentário ou anexe arquivos",
"createdBy": "Criado {{time}} por {{user}}",
"updatedTime": "Atualizado {{time}}"
},
"searchInputPlaceholder": "Pesquisar por nome",
"pendingInvitation": "Convite Pendente"
"pendingInvitation": "Convite pendente"
},
"taskTimeLogTab": {
"title": "Registro de Tempo",
"title": "Registro de tempo",
"addTimeLog": "Adicionar novo registro de tempo",
"totalLogged": "Total Registrado",
"totalLogged": "Total registrado",
"exportToExcel": "Exportar para Excel",
"noTimeLogsFound": "Nenhum registro de tempo encontrado",
"timeLogForm": {
"date": "Data",
"startTime": "Hora de Início",
"endTime": "Hora de Fim",
"workDescription": "Descrição do Trabalho",
"startTime": "Hora de início",
"endTime": "Hora de término",
"workDescription": "Descrição do trabalho",
"descriptionPlaceholder": "Adicionar uma descrição",
"logTime": "Registrar tempo",
"updateTime": "Atualizar tempo",
"cancel": "Cancelar",
"selectDateError": "Por favor selecione uma data",
"selectStartTimeError": "Por favor selecione a hora de início",
"selectEndTimeError": "Por favor selecione a hora de fim",
"endTimeAfterStartError": "A hora de fim deve ser posterior à hora de início"
"selectDateError": "Por favor, selecione uma data",
"selectStartTimeError": "Por favor, selecione a hora de início",
"selectEndTimeError": "Por favor, selecione a hora de término",
"endTimeAfterStartError": "A hora de término deve ser posterior à hora de início"
}
},
"taskActivityLogTab": {
"title": "Registro de Atividade",
"title": "Registro de atividade",
"add": "ADICIONAR",
"remove": "REMOVER",
"none": "Nenhum",
@@ -115,7 +121,7 @@
"createdTask": "criou a tarefa."
},
"taskProgress": {
"markAsDoneTitle": "Marcar Tarefa como Concluída?",
"markAsDoneTitle": "Marcar tarefa como concluída?",
"confirmMarkAsDone": "Sim, marcar como concluída",
"cancelMarkAsDone": "Não, manter status atual",
"markAsDoneDescription": "Você definiu o progresso para 100%. Gostaria de atualizar o status da tarefa para \"Concluída\"?"

View File

@@ -39,6 +39,7 @@
"addTaskText": "Adicionar Tarefa",
"addSubTaskText": "+ Adicionar Subtarefa",
"noTasksInGroup": "Nenhuma tarefa neste grupo",
"dropTaskHere": "Soltar tarefa aqui",
"addTaskInputPlaceholder": "Digite sua tarefa e pressione enter",
"openButton": "Abrir",

View File

@@ -1,22 +1,28 @@
{
"taskHeader": {
"taskNamePlaceholder": "输入您的任务",
"deleteTask": "删除任务"
"deleteTask": "删除任务",
"parentTask": "父任务",
"currentTask": "当前任务",
"back": "返回",
"backToParent": "返回父任务",
"toParentTask": "到父任务",
"loadingHierarchy": "加载层次结构..."
},
"taskInfoTab": {
"title": "信息",
"details": {
"title": "详",
"title": "详细信息",
"task-key": "任务键",
"phase": "阶段",
"assignees": "受人",
"assignees": "受人",
"due-date": "截止日期",
"time-estimation": "时间估算",
"priority": "优先级",
"labels": "标签",
"billable": "可计费",
"notify": "通知",
"when-done-notify": "完成时通知",
"when-done-notify": "完成时通知",
"start-date": "开始日期",
"end-date": "结束日期",
"hide-start-date": "隐藏开始日期",
@@ -24,18 +30,18 @@
"hours": "小时",
"minutes": "分钟",
"progressValue": "进度值",
"progressValueTooltip": "设置进度百分比0-100%",
"progressValueTooltip": "设置进度百分比 (0-100%)",
"progressValueRequired": "请输入进度值",
"progressValueRange": "进度必须在 0 到 100 之间",
"taskWeight": "任务权重",
"taskWeightTooltip": "设置此子任务的权重百分比",
"taskWeightTooltip": "设置此子任务的权重 (百分比)",
"taskWeightRequired": "请输入任务权重",
"taskWeightRange": "权重必须在 0 到 100 之间",
"recurring": "重复"
},
"labels": {
"labelInputPlaceholder": "搜索或创建",
"labelsSelectorInputTip": "按回车创建"
"labelsSelectorInputTip": "按 Enter 键创建"
},
"description": {
"title": "描述",
@@ -44,7 +50,7 @@
"subTasks": {
"title": "子任务",
"addSubTask": "添加子任务",
"addSubTaskInputPlaceholder": "输入您的任务并按回车",
"addSubTaskInputPlaceholder": "输入您的任务并按回车",
"refreshSubTasks": "刷新子任务",
"edit": "编辑",
"delete": "删除",
@@ -52,10 +58,10 @@
"deleteSubTask": "删除子任务"
},
"dependencies": {
"title": "依赖关系",
"addDependency": "+ 添加新依赖",
"title": "依赖",
"addDependency": "+ 添加新依赖",
"blockedBy": "被阻止",
"searchTask": "输入搜索任务",
"searchTask": "输入搜索任务",
"noTasksFound": "未找到任务",
"confirmDeleteDependency": "您确定要删除吗?"
},
@@ -67,7 +73,7 @@
"comments": {
"title": "评论",
"addComment": "+ 添加新评论",
"noComments": "还没有评论。成为第一个评论的人",
"noComments": "还没有评论。成为第一个评论",
"delete": "删除",
"confirmDeleteComment": "您确定要删除此评论吗?",
"addCommentPlaceholder": "添加评论...",
@@ -75,11 +81,11 @@
"commentButton": "评论",
"attachFiles": "附加文件",
"addMoreFiles": "添加更多文件",
"selectedFiles": "已选择的文件(最多25MB{count}个)",
"selectedFiles": "选定文件 (最多 25MB{count} 个)",
"maxFilesError": "您最多只能上传 {count} 个文件",
"processFilesError": "处理文件失败",
"addCommentError": "请添加评论或附加文件",
"createdBy": "{{time}}由{{user}}创建",
"createdBy": "由 {{user}} 在 {{time}} 创建",
"updatedTime": "更新于 {{time}}"
},
"searchInputPlaceholder": "按名称搜索",
@@ -88,7 +94,7 @@
"taskTimeLogTab": {
"title": "时间日志",
"addTimeLog": "添加新时间日志",
"totalLogged": "总记录时间",
"totalLogged": "总记录",
"exportToExcel": "导出到 Excel",
"noTimeLogsFound": "未找到时间日志",
"timeLogForm": {
@@ -103,7 +109,7 @@
"selectDateError": "请选择日期",
"selectStartTimeError": "请选择开始时间",
"selectEndTimeError": "请选择结束时间",
"endTimeAfterStartError": "结束时间必须开始时间之后"
"endTimeAfterStartError": "结束时间必须晚于开始时间"
}
},
"taskActivityLogTab": {
@@ -116,8 +122,8 @@
},
"taskProgress": {
"markAsDoneTitle": "将任务标记为完成?",
"confirmMarkAsDone": "是,标记为完成",
"cancelMarkAsDone": ",保持当前状态",
"confirmMarkAsDone": "是,标记为完成",
"cancelMarkAsDone": ",保持当前状态",
"markAsDoneDescription": "您已将进度设置为 100%。您想将任务状态更新为\"完成\"吗?"
}
}

View File

@@ -37,6 +37,7 @@
"addSubTaskText": "+ 添加子任务",
"addTaskInputPlaceholder": "输入任务并按回车键",
"noTasksInGroup": "此组中没有任务",
"dropTaskHere": "将任务拖到这里",
"openButton": "打开",
"okButton": "确定",
"noLabelsFound": "未找到标签",

View File

@@ -331,6 +331,13 @@ self.addEventListener('message', event => {
});
break;
case 'LOGOUT':
// Special handler for logout - clear all caches and unregister
handleLogout().then(() => {
event.ports[0].postMessage({ success: true });
});
break;
default:
console.log('Service Worker: Unknown message type', type);
}
@@ -342,4 +349,19 @@ async function clearAllCaches() {
console.log('Service Worker: All caches cleared');
}
async function handleLogout() {
try {
// Clear all caches
await clearAllCaches();
// Unregister the service worker to force fresh registration on next visit
await self.registration.unregister();
console.log('Service Worker: Logout handled - caches cleared and unregistered');
} catch (error) {
console.error('Service Worker: Error during logout handling', error);
throw error;
}
}
console.log('Service Worker: Loaded successfully');

View File

@@ -5,6 +5,7 @@ import i18next from 'i18next';
// Components
import ThemeWrapper from './features/theme/ThemeWrapper';
import ModuleErrorBoundary from './components/ModuleErrorBoundary';
// Routes
import router from './app/routes';
@@ -13,6 +14,7 @@ import router from './app/routes';
import { useAppSelector } from './hooks/useAppSelector';
import { initMixpanel } from './utils/mixpanelInit';
import { initializeCsrfToken } from './api/api-client';
import CacheCleanup from './utils/cache-cleanup';
// Types & Constants
import { Language } from './features/i18n/localesSlice';
@@ -113,6 +115,56 @@ const App: React.FC = memo(() => {
};
}, []);
// Global error handlers for module loading issues
useEffect(() => {
const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
const error = event.reason;
// Check if this is a module loading error
if (
error?.message?.includes('Failed to fetch dynamically imported module') ||
error?.message?.includes('Loading chunk') ||
error?.name === 'ChunkLoadError'
) {
console.error('Unhandled module loading error:', error);
event.preventDefault(); // Prevent default browser error handling
// Clear caches and reload
CacheCleanup.clearAllCaches()
.then(() => CacheCleanup.forceReload('/auth/login'))
.catch(() => window.location.reload());
}
};
const handleError = (event: ErrorEvent) => {
const error = event.error;
// Check if this is a module loading error
if (
error?.message?.includes('Failed to fetch dynamically imported module') ||
error?.message?.includes('Loading chunk') ||
error?.name === 'ChunkLoadError'
) {
console.error('Global module loading error:', error);
event.preventDefault(); // Prevent default browser error handling
// Clear caches and reload
CacheCleanup.clearAllCaches()
.then(() => CacheCleanup.forceReload('/auth/login'))
.catch(() => window.location.reload());
}
};
// Add global error handlers
window.addEventListener('unhandledrejection', handleUnhandledRejection);
window.addEventListener('error', handleError);
return () => {
window.removeEventListener('unhandledrejection', handleUnhandledRejection);
window.removeEventListener('error', handleError);
};
}, []);
// Register service worker
useEffect(() => {
registerSW({
@@ -150,12 +202,14 @@ const App: React.FC = memo(() => {
return (
<Suspense fallback={<SuspenseFallback />}>
<ThemeWrapper>
<ModuleErrorBoundary>
<RouterProvider
router={router}
future={{
v7_startTransition: true,
}}
/>
</ModuleErrorBoundary>
</ThemeWrapper>
</Suspense>
);

View File

@@ -90,6 +90,23 @@ export const SetupGuard = memo(({ children }: GuardProps) => {
SetupGuard.displayName = 'SetupGuard';
// Combined guard for routes that require both authentication and setup completion
export const AuthAndSetupGuard = memo(({ children }: GuardProps) => {
const { isAuthenticated, isSetupComplete, location } = useAuthStatus();
if (!isAuthenticated) {
return <Navigate to="/auth" state={{ from: location }} replace />;
}
if (!isSetupComplete) {
return <Navigate to="/worklenz/setup" />;
}
return <>{children}</>;
});
AuthAndSetupGuard.displayName = 'AuthAndSetupGuard';
// Optimized route wrapping function with Suspense boundaries
const wrapRoutes = (
routes: RouteObject[],
@@ -171,9 +188,11 @@ StaticLicenseExpired.displayName = 'StaticLicenseExpired';
// Create route arrays (moved outside of useMemo to avoid hook violations)
const publicRoutes = [...rootRoutes, ...authRoutes, notFoundRoute];
const protectedMainRoutes = wrapRoutes(mainRoutes, AuthGuard);
// Apply combined guard to main routes that require both auth and setup completion
const protectedMainRoutes = wrapRoutes(mainRoutes, AuthAndSetupGuard);
const adminRoutes = wrapRoutes(reportingRoutes, AdminGuard);
const setupRoutes = wrapRoutes([accountSetupRoute], SetupGuard);
// Setup route should be accessible without setup completion, only requires authentication
const setupRoutes = wrapRoutes([accountSetupRoute], AuthGuard);
// License expiry check function
const withLicenseExpiryCheck = (routes: RouteObject[]): RouteObject[] => {

View File

@@ -17,6 +17,7 @@ const ProjectTemplateEditView = lazy(
const LicenseExpired = lazy(() => import('@/pages/license-expired/license-expired'));
const ProjectView = lazy(() => import('@/pages/projects/projectView/project-view'));
const Unauthorized = lazy(() => import('@/pages/unauthorized/unauthorized'));
const GanttDemoPage = lazy(() => import('@/pages/GanttDemoPage'));
// Define AdminGuard component with defensive programming
const AdminGuard = ({ children }: { children: React.ReactNode }) => {
@@ -106,6 +107,14 @@ const mainRoutes: RouteObject[] = [
</Suspense>
),
},
{
path: 'gantt-demo',
element: (
<Suspense fallback={<SuspenseFallback />}>
<GanttDemoPage />
</Suspense>
),
},
...settingsRoutes,
...adminCenterRoutes,
],

View File

@@ -39,7 +39,7 @@ const CustomColordLabel = React.forwardRef<HTMLSpanElement, CustomColordLabelPro
<Tooltip title={label.name}>
<span
ref={ref}
className="inline-flex items-center px-2 py-0.5 rounded-sm text-xs font-medium shrink-0 max-w-[120px]"
className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium shrink-0 max-w-[100px]"
style={{
backgroundColor,
color: textColor,

View File

@@ -21,8 +21,8 @@ const CustomNumberLabel = React.forwardRef<HTMLSpanElement, CustomNumberLabelPro
<Tooltip title={labelList.join(', ')}>
<span
ref={ref}
className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium text-white cursor-help"
style={{ backgroundColor }}
className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium cursor-help"
style={{ backgroundColor, color: 'white' }}
>
{namesString}
</span>

View File

@@ -0,0 +1,110 @@
import React, { Component, ErrorInfo, ReactNode } from 'react';
import { Button, Result } from 'antd';
import CacheCleanup from '@/utils/cache-cleanup';
interface Props {
children: ReactNode;
}
interface State {
hasError: boolean;
error?: Error;
}
class ModuleErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error: Error): State {
// Check if this is a module loading error
const isModuleError =
error.message.includes('Failed to fetch dynamically imported module') ||
error.message.includes('Loading chunk') ||
error.message.includes('Loading CSS chunk') ||
error.name === 'ChunkLoadError';
if (isModuleError) {
return { hasError: true, error };
}
// For other errors, let them bubble up
return { hasError: false };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Module Error Boundary caught an error:', error, errorInfo);
// If this is a module loading error, clear caches and reload
if (this.state.hasError) {
this.handleModuleError();
}
}
private async handleModuleError() {
try {
console.log('Handling module loading error - clearing caches...');
// Clear all caches
await CacheCleanup.clearAllCaches();
// Force reload to login page
CacheCleanup.forceReload('/auth/login');
} catch (cacheError) {
console.error('Failed to handle module error:', cacheError);
// Fallback: just reload the page
window.location.reload();
}
}
private handleRetry = async () => {
try {
await CacheCleanup.clearAllCaches();
CacheCleanup.forceReload('/auth/login');
} catch (error) {
console.error('Retry failed:', error);
window.location.reload();
}
};
render() {
if (this.state.hasError) {
return (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minHeight: '100vh',
padding: '20px'
}}>
<Result
status="error"
title="Module Loading Error"
subTitle="There was an issue loading the application. This usually happens after updates or during logout."
extra={[
<Button
type="primary"
key="retry"
onClick={this.handleRetry}
loading={false}
>
Retry
</Button>,
<Button
key="reload"
onClick={() => window.location.reload()}
>
Reload Page
</Button>
]}
/>
</div>
);
}
return this.props.children;
}
}
export default ModuleErrorBoundary;

View File

@@ -1,5 +1,5 @@
import React, { startTransition, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -18,6 +18,11 @@ import { IAccountSetupRequest } from '@/types/project-templates/project-template
import { evt_account_setup_template_complete } from '@/shared/worklenz-analytics-events';
import { useMixpanelTracking } from '@/hooks/useMixpanelTracking';
import { createPortal } from 'react-dom';
import { useAppDispatch } from '@/hooks/useAppDispatch';
import { verifyAuthentication } from '@/features/auth/authSlice';
import { setUser } from '@/features/user/userSlice';
import { setSession } from '@/utils/session-helper';
import { IAuthorizeResponse } from '@/types/auth/login.types';
const { Title } = Typography;
@@ -29,7 +34,7 @@ interface Props {
export const ProjectStep: React.FC<Props> = ({ onEnter, styles, isDarkMode = false }) => {
const { t } = useTranslation('account-setup');
const dispatch = useDispatch();
const dispatch = useAppDispatch();
const navigate = useNavigate();
const { trackMixpanelEvent } = useMixpanelTracking();
@@ -69,6 +74,18 @@ export const ProjectStep: React.FC<Props> = ({ onEnter, styles, isDarkMode = fal
if (res.done && res.body.id) {
toggleTemplateSelector(false);
trackMixpanelEvent(evt_account_setup_template_complete);
// Refresh user session to update setup_completed status
try {
const authResponse = await dispatch(verifyAuthentication()).unwrap() as IAuthorizeResponse;
if (authResponse?.authenticated && authResponse?.user) {
setSession(authResponse.user);
dispatch(setUser(authResponse.user));
}
} catch (error) {
logger.error('Failed to refresh user session after template setup completion', error);
}
navigate(`/worklenz/projects/${res.body.id}?tab=tasks-list&pinned_tab=tasks-list`);
}
} catch (error) {

View File

@@ -0,0 +1,612 @@
import React, { useReducer, useMemo, useCallback, useRef, useEffect, useState } from 'react';
import {
GanttTask,
ColumnConfig,
TimelineConfig,
VirtualScrollConfig,
ZoomLevel,
GanttState,
GanttAction,
AdvancedGanttProps,
SelectionState,
GanttViewState,
DragState
} from '../../types/advanced-gantt.types';
import GanttGrid from './GanttGrid';
import DraggableTaskBar from './DraggableTaskBar';
import TimelineMarkers, { holidayPresets, workingDayPresets } from './TimelineMarkers';
import VirtualScrollContainer, { VirtualTimeline } from './VirtualScrollContainer';
import {
usePerformanceMonitoring,
useTaskCalculations,
useDateCalculations,
useDebounce,
useThrottle
} from '../../utils/gantt-performance';
import { useAppSelector } from '../../hooks/useAppSelector';
import { themeWiseColor } from '../../utils/themeWiseColor';
// Default configurations
const defaultColumns: ColumnConfig[] = [
{
field: 'name',
title: 'Task Name',
width: 250,
minWidth: 150,
resizable: true,
sortable: true,
fixed: true,
editor: 'text'
},
{
field: 'startDate',
title: 'Start Date',
width: 120,
minWidth: 100,
resizable: true,
sortable: true,
fixed: true,
editor: 'date'
},
{
field: 'endDate',
title: 'End Date',
width: 120,
minWidth: 100,
resizable: true,
sortable: true,
fixed: true,
editor: 'date'
},
{
field: 'duration',
title: 'Duration',
width: 80,
minWidth: 60,
resizable: true,
sortable: false,
fixed: true
},
{
field: 'progress',
title: 'Progress',
width: 100,
minWidth: 80,
resizable: true,
sortable: true,
fixed: true,
editor: 'number'
},
];
const defaultTimelineConfig: TimelineConfig = {
topTier: { unit: 'month', format: 'MMM yyyy', height: 30 },
bottomTier: { unit: 'day', format: 'dd', height: 25 },
showWeekends: true,
showNonWorkingDays: true,
holidays: holidayPresets.US,
workingDays: workingDayPresets.standard,
workingHours: { start: 9, end: 17 },
dayWidth: 30,
};
const defaultVirtualScrollConfig: VirtualScrollConfig = {
enableRowVirtualization: true,
enableTimelineVirtualization: true,
bufferSize: 10,
itemHeight: 40,
overscan: 5,
};
const defaultZoomLevels: ZoomLevel[] = [
{
name: 'Year',
dayWidth: 2,
scale: 0.1,
topTier: { unit: 'year', format: 'yyyy' },
bottomTier: { unit: 'month', format: 'MMM' }
},
{
name: 'Month',
dayWidth: 8,
scale: 0.5,
topTier: { unit: 'month', format: 'MMM yyyy' },
bottomTier: { unit: 'week', format: 'w' }
},
{
name: 'Week',
dayWidth: 25,
scale: 1,
topTier: { unit: 'week', format: 'MMM dd' },
bottomTier: { unit: 'day', format: 'dd' }
},
{
name: 'Day',
dayWidth: 50,
scale: 2,
topTier: { unit: 'day', format: 'MMM dd' },
bottomTier: { unit: 'hour', format: 'HH' }
},
];
// Gantt state reducer
function ganttReducer(state: GanttState, action: GanttAction): GanttState {
switch (action.type) {
case 'SET_TASKS':
return { ...state, tasks: action.payload };
case 'UPDATE_TASK':
return {
...state,
tasks: state.tasks.map(task =>
task.id === action.payload.id
? { ...task, ...action.payload.updates }
: task
),
};
case 'ADD_TASK':
return { ...state, tasks: [...state.tasks, action.payload] };
case 'DELETE_TASK':
return {
...state,
tasks: state.tasks.filter(task => task.id !== action.payload),
};
case 'SET_SELECTION':
return {
...state,
selectionState: { ...state.selectionState, selectedTasks: action.payload },
};
case 'SET_DRAG_STATE':
return { ...state, dragState: action.payload };
case 'SET_ZOOM_LEVEL':
const newZoomLevel = Math.max(0, Math.min(state.zoomLevels.length - 1, action.payload));
return {
...state,
viewState: { ...state.viewState, zoomLevel: newZoomLevel },
timelineConfig: {
...state.timelineConfig,
dayWidth: state.zoomLevels[newZoomLevel].dayWidth,
topTier: state.zoomLevels[newZoomLevel].topTier,
bottomTier: state.zoomLevels[newZoomLevel].bottomTier,
},
};
case 'SET_SCROLL_POSITION':
return {
...state,
viewState: { ...state.viewState, scrollPosition: action.payload },
};
case 'SET_SPLITTER_POSITION':
return {
...state,
viewState: { ...state.viewState, splitterPosition: action.payload },
};
case 'TOGGLE_TASK_EXPANSION':
return {
...state,
tasks: state.tasks.map(task =>
task.id === action.payload
? { ...task, isExpanded: !task.isExpanded }
: task
),
};
case 'SET_VIEW_STATE':
return {
...state,
viewState: { ...state.viewState, ...action.payload },
};
case 'UPDATE_COLUMN_WIDTH':
return {
...state,
columns: state.columns.map(col =>
col.field === action.payload.field
? { ...col, width: action.payload.width }
: col
),
};
default:
return state;
}
}
const AdvancedGanttChart: React.FC<AdvancedGanttProps> = ({
tasks: initialTasks,
columns = defaultColumns,
timelineConfig = {},
virtualScrollConfig = {},
zoomLevels = defaultZoomLevels,
initialViewState = {},
initialSelection = [],
onTaskUpdate,
onTaskCreate,
onTaskDelete,
onTaskMove,
onTaskResize,
onProgressChange,
onSelectionChange,
onColumnResize,
onDependencyCreate,
onDependencyDelete,
className = '',
style = {},
theme = 'auto',
enableDragDrop = true,
enableResize = true,
enableProgressEdit = true,
enableInlineEdit = true,
enableVirtualScrolling = true,
enableDebouncing = true,
debounceDelay = 300,
maxVisibleTasks = 1000,
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
const themeMode = useAppSelector(state => state.themeReducer.mode);
const { startMeasure, endMeasure, metrics } = usePerformanceMonitoring();
const { getDaysBetween } = useDateCalculations();
// Initialize state
const initialState: GanttState = {
tasks: initialTasks,
columns,
timelineConfig: { ...defaultTimelineConfig, ...timelineConfig },
virtualScrollConfig: { ...defaultVirtualScrollConfig, ...virtualScrollConfig },
dragState: null,
selectionState: {
selectedTasks: initialSelection,
selectedRows: [],
focusedTask: undefined,
},
viewState: {
zoomLevel: 2, // Week view by default
scrollPosition: { x: 0, y: 0 },
viewportSize: { width: 0, height: 0 },
splitterPosition: 40, // 40% for grid, 60% for timeline
showCriticalPath: false,
showBaseline: false,
showProgress: true,
showDependencies: true,
autoSchedule: false,
readOnly: false,
...initialViewState,
},
zoomLevels,
performanceMetrics: {
renderTime: 0,
taskCount: initialTasks.length,
visibleTaskCount: 0,
},
};
const [state, dispatch] = useReducer(ganttReducer, initialState);
const { taskMap, parentChildMap, totalTasks } = useTaskCalculations(state.tasks);
// Calculate project timeline bounds
const projectBounds = useMemo(() => {
if (state.tasks.length === 0) {
const today = new Date();
return {
start: new Date(today.getFullYear(), today.getMonth(), 1),
end: new Date(today.getFullYear(), today.getMonth() + 3, 0),
};
}
const startDates = state.tasks.map(task => task.startDate);
const endDates = state.tasks.map(task => task.endDate);
const minStart = new Date(Math.min(...startDates.map(d => d.getTime())));
const maxEnd = new Date(Math.max(...endDates.map(d => d.getTime())));
// Add some padding
minStart.setDate(minStart.getDate() - 7);
maxEnd.setDate(maxEnd.getDate() + 7);
return { start: minStart, end: maxEnd };
}, [state.tasks]);
// Debounced event handlers
const debouncedTaskUpdate = useDebounce(
useCallback((taskId: string, updates: Partial<GanttTask>) => {
dispatch({ type: 'UPDATE_TASK', payload: { id: taskId, updates } });
onTaskUpdate?.(taskId, updates);
}, [onTaskUpdate]),
enableDebouncing ? debounceDelay : 0
);
const debouncedTaskMove = useDebounce(
useCallback((taskId: string, newDates: { start: Date; end: Date }) => {
dispatch({ type: 'UPDATE_TASK', payload: {
id: taskId,
updates: { startDate: newDates.start, endDate: newDates.end }
}});
onTaskMove?.(taskId, newDates);
}, [onTaskMove]),
enableDebouncing ? debounceDelay : 0
);
const debouncedProgressChange = useDebounce(
useCallback((taskId: string, progress: number) => {
dispatch({ type: 'UPDATE_TASK', payload: { id: taskId, updates: { progress } }});
onProgressChange?.(taskId, progress);
}, [onProgressChange]),
enableDebouncing ? debounceDelay : 0
);
// Throttled scroll handler
const throttledScrollHandler = useThrottle(
useCallback((scrollLeft: number, scrollTop: number) => {
dispatch({ type: 'SET_SCROLL_POSITION', payload: { x: scrollLeft, y: scrollTop } });
}, []),
16 // 60fps
);
// Container size observer
useEffect(() => {
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
setContainerSize({ width, height });
dispatch({
type: 'SET_VIEW_STATE',
payload: { viewportSize: { width, height } }
});
}
});
if (containerRef.current) {
observer.observe(containerRef.current);
}
return () => observer.disconnect();
}, []);
// Calculate grid and timeline dimensions
const gridWidth = useMemo(() => {
return Math.floor(containerSize.width * (state.viewState.splitterPosition / 100));
}, [containerSize.width, state.viewState.splitterPosition]);
const timelineWidth = useMemo(() => {
return containerSize.width - gridWidth;
}, [containerSize.width, gridWidth]);
// Handle zoom changes
const handleZoomChange = useCallback((direction: 'in' | 'out') => {
const currentZoom = state.viewState.zoomLevel;
const newZoom = direction === 'in'
? Math.min(state.zoomLevels.length - 1, currentZoom + 1)
: Math.max(0, currentZoom - 1);
dispatch({ type: 'SET_ZOOM_LEVEL', payload: newZoom });
}, [state.viewState.zoomLevel, state.zoomLevels.length]);
// Theme-aware colors
const colors = useMemo(() => ({
background: themeWiseColor('#ffffff', '#1f2937', themeMode),
border: themeWiseColor('#e5e7eb', '#4b5563', themeMode),
timelineBackground: themeWiseColor('#f8f9fa', '#374151', themeMode),
}), [themeMode]);
// Render timeline header
const renderTimelineHeader = () => {
const currentZoom = state.zoomLevels[state.viewState.zoomLevel];
const totalDays = getDaysBetween(projectBounds.start, projectBounds.end);
const totalWidth = totalDays * state.timelineConfig.dayWidth;
return (
<div className="timeline-header border-b" style={{
height: (currentZoom.topTier.height || 30) + (currentZoom.bottomTier.height || 25),
backgroundColor: colors.timelineBackground,
borderColor: colors.border,
}}>
<VirtualTimeline
startDate={projectBounds.start}
endDate={projectBounds.end}
dayWidth={state.timelineConfig.dayWidth}
containerWidth={timelineWidth}
containerHeight={(currentZoom.topTier.height || 30) + (currentZoom.bottomTier.height || 25)}
onScroll={throttledScrollHandler}
>
{(date, index, style) => (
<div className="timeline-cell flex flex-col border-r text-xs text-center" style={{
...style,
borderColor: colors.border,
}}>
<div className="top-tier border-b px-1 py-1" style={{
height: currentZoom.topTier.height || 30,
borderColor: colors.border,
}}>
{formatDateForUnit(date, currentZoom.topTier.unit)}
</div>
<div className="bottom-tier px-1 py-1" style={{
height: currentZoom.bottomTier.height || 25,
}}>
{formatDateForUnit(date, currentZoom.bottomTier.unit)}
</div>
</div>
)}
</VirtualTimeline>
</div>
);
};
// Render timeline content
const renderTimelineContent = () => {
const headerHeight = (state.zoomLevels[state.viewState.zoomLevel].topTier.height || 30) +
(state.zoomLevels[state.viewState.zoomLevel].bottomTier.height || 25);
const contentHeight = containerSize.height - headerHeight;
return (
<div className="timeline-content relative" style={{ height: contentHeight }}>
{/* Timeline markers (weekends, holidays, etc.) */}
<TimelineMarkers
startDate={projectBounds.start}
endDate={projectBounds.end}
dayWidth={state.timelineConfig.dayWidth}
containerHeight={contentHeight}
timelineConfig={state.timelineConfig}
holidays={state.timelineConfig.holidays}
showWeekends={state.timelineConfig.showWeekends}
showHolidays={true}
showToday={true}
/>
{/* Task bars */}
<VirtualScrollContainer
items={state.tasks}
itemHeight={state.virtualScrollConfig.itemHeight}
containerHeight={contentHeight}
containerWidth={timelineWidth}
overscan={state.virtualScrollConfig.overscan}
onScroll={throttledScrollHandler}
>
{(task, index, style) => (
<DraggableTaskBar
key={task.id}
task={task}
timelineStart={projectBounds.start}
dayWidth={state.timelineConfig.dayWidth}
rowHeight={state.virtualScrollConfig.itemHeight}
index={index}
onTaskMove={debouncedTaskMove}
onTaskResize={debouncedTaskMove}
onProgressChange={debouncedProgressChange}
enableDragDrop={enableDragDrop}
enableResize={enableResize}
enableProgressEdit={enableProgressEdit}
readOnly={state.viewState.readOnly}
/>
)}
</VirtualScrollContainer>
</div>
);
};
// Render toolbar
const renderToolbar = () => (
<div className="gantt-toolbar flex items-center justify-between p-2 border-b bg-gray-50 dark:bg-gray-800" style={{
borderColor: colors.border,
}}>
<div className="toolbar-left flex items-center space-x-2">
<button
onClick={() => handleZoomChange('out')}
disabled={state.viewState.zoomLevel === 0}
className="px-2 py-1 text-sm border rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
>
Zoom Out
</button>
<span className="text-sm text-gray-600 dark:text-gray-400">
{state.zoomLevels[state.viewState.zoomLevel].name}
</span>
<button
onClick={() => handleZoomChange('in')}
disabled={state.viewState.zoomLevel === state.zoomLevels.length - 1}
className="px-2 py-1 text-sm border rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
>
Zoom In
</button>
</div>
<div className="toolbar-right flex items-center space-x-2 text-xs text-gray-500">
<span>Tasks: {state.tasks.length}</span>
<span></span>
<span>Render: {Math.round(metrics.renderTime)}ms</span>
</div>
</div>
);
// Performance monitoring
useEffect(() => {
startMeasure('render');
return () => endMeasure('render');
});
return (
<div
ref={containerRef}
className={`advanced-gantt-chart flex flex-col ${className}`}
style={{
height: '100%',
backgroundColor: colors.background,
...style,
}}
>
{/* Toolbar */}
{renderToolbar()}
{/* Main content */}
<div className="gantt-content flex flex-1 overflow-hidden">
{/* Grid */}
<div className="gantt-grid-container" style={{ width: gridWidth }}>
<GanttGrid
tasks={state.tasks}
columns={state.columns}
rowHeight={state.virtualScrollConfig.itemHeight}
containerHeight={containerSize.height - 50} // Subtract toolbar height
selection={state.selectionState}
enableInlineEdit={enableInlineEdit}
onTaskClick={(task) => {
// Handle task selection
const newSelection = { ...state.selectionState, selectedTasks: [task.id] };
dispatch({ type: 'SET_SELECTION', payload: [task.id] });
onSelectionChange?.(newSelection);
}}
onTaskExpand={(taskId) => {
dispatch({ type: 'TOGGLE_TASK_EXPANSION', payload: taskId });
}}
onColumnResize={(field, width) => {
dispatch({ type: 'UPDATE_COLUMN_WIDTH', payload: { field, width } });
onColumnResize?.(field, width);
}}
onTaskUpdate={debouncedTaskUpdate}
/>
</div>
{/* Timeline */}
<div className="gantt-timeline-container border-l" style={{
width: timelineWidth,
borderColor: colors.border,
}}>
{renderTimelineHeader()}
{renderTimelineContent()}
</div>
</div>
</div>
);
};
// Helper function to format dates based on unit
function formatDateForUnit(date: Date, unit: string): string {
switch (unit) {
case 'year':
return date.getFullYear().toString();
case 'month':
return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
case 'week':
return `W${getWeekNumber(date)}`;
case 'day':
return date.getDate().toString();
case 'hour':
return date.getHours().toString().padStart(2, '0');
default:
return '';
}
}
function getWeekNumber(date: Date): number {
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
const dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d.getTime() - yearStart.getTime()) / 86400000) + 1) / 7);
}
export default AdvancedGanttChart;

View File

@@ -0,0 +1,668 @@
import React, { useState, useMemo } from 'react';
import { Button, Space, message, Card } from 'antd';
import AdvancedGanttChart from './AdvancedGanttChart';
import { GanttTask, ColumnConfig } from '../../types/advanced-gantt.types';
import { useAppSelector } from '../../hooks/useAppSelector';
import { holidayPresets, workingDayPresets } from './TimelineMarkers';
// Enhanced sample data with more realistic project structure
const generateSampleTasks = (): GanttTask[] => {
const baseDate = new Date(2024, 11, 1); // December 1, 2024
return [
// Project Phase 1: Planning & Design
{
id: 'project-1',
name: '🚀 Web Platform Development',
startDate: new Date(2024, 11, 1),
endDate: new Date(2025, 2, 31),
progress: 45,
type: 'project',
status: 'in-progress',
priority: 'high',
color: '#1890ff',
hasChildren: true,
isExpanded: true,
level: 0,
},
{
id: 'planning-phase',
name: '📋 Planning & Analysis Phase',
startDate: new Date(2024, 11, 1),
endDate: new Date(2024, 11, 20),
progress: 85,
type: 'project',
status: 'in-progress',
priority: 'high',
parent: 'project-1',
color: '#52c41a',
hasChildren: true,
isExpanded: true,
level: 1,
},
{
id: 'requirements-analysis',
name: 'Requirements Gathering & Analysis',
startDate: new Date(2024, 11, 1),
endDate: new Date(2024, 11, 8),
progress: 100,
type: 'task',
status: 'completed',
priority: 'high',
parent: 'planning-phase',
assignee: {
id: 'user-1',
name: 'Alice Johnson',
avatar: 'https://ui-avatars.com/api/?name=Alice+Johnson&background=1890ff&color=fff',
},
tags: ['research', 'documentation'],
level: 2,
},
{
id: 'technical-architecture',
name: 'Technical Architecture Design',
startDate: new Date(2024, 11, 8),
endDate: new Date(2024, 11, 18),
progress: 75,
type: 'task',
status: 'in-progress',
priority: 'high',
parent: 'planning-phase',
assignee: {
id: 'user-2',
name: 'Bob Smith',
avatar: 'https://ui-avatars.com/api/?name=Bob+Smith&background=52c41a&color=fff',
},
dependencies: ['requirements-analysis'],
tags: ['architecture', 'design'],
level: 2,
},
{
id: 'ui-ux-design',
name: 'UI/UX Design & Prototyping',
startDate: new Date(2024, 11, 10),
endDate: new Date(2024, 11, 20),
progress: 60,
type: 'task',
status: 'in-progress',
priority: 'medium',
parent: 'planning-phase',
assignee: {
id: 'user-3',
name: 'Carol Davis',
avatar: 'https://ui-avatars.com/api/?name=Carol+Davis&background=faad14&color=fff',
},
dependencies: ['requirements-analysis'],
tags: ['design', 'prototype'],
level: 2,
},
{
id: 'milestone-planning-complete',
name: '🎯 Planning Phase Complete',
startDate: new Date(2024, 11, 20),
endDate: new Date(2024, 11, 20),
progress: 0,
type: 'milestone',
status: 'not-started',
priority: 'critical',
parent: 'planning-phase',
dependencies: ['technical-architecture', 'ui-ux-design'],
level: 2,
},
// Development Phase
{
id: 'development-phase',
name: '⚡ Development Phase',
startDate: new Date(2024, 11, 21),
endDate: new Date(2025, 1, 28),
progress: 35,
type: 'project',
status: 'in-progress',
priority: 'high',
parent: 'project-1',
color: '#722ed1',
hasChildren: true,
isExpanded: true,
level: 1,
},
{
id: 'backend-development',
name: 'Backend API Development',
startDate: new Date(2024, 11, 21),
endDate: new Date(2025, 1, 15),
progress: 45,
type: 'task',
status: 'in-progress',
priority: 'high',
parent: 'development-phase',
assignee: {
id: 'user-4',
name: 'David Wilson',
avatar: 'https://ui-avatars.com/api/?name=David+Wilson&background=722ed1&color=fff',
},
dependencies: ['milestone-planning-complete'],
tags: ['backend', 'api'],
level: 2,
},
{
id: 'frontend-development',
name: 'Frontend React Application',
startDate: new Date(2025, 0, 5),
endDate: new Date(2025, 1, 25),
progress: 25,
type: 'task',
status: 'in-progress',
priority: 'high',
parent: 'development-phase',
assignee: {
id: 'user-5',
name: 'Eva Brown',
avatar: 'https://ui-avatars.com/api/?name=Eva+Brown&background=ff7a45&color=fff',
},
dependencies: ['backend-development'],
tags: ['frontend', 'react'],
level: 2,
},
{
id: 'database-setup',
name: 'Database Schema & Migration',
startDate: new Date(2024, 11, 21),
endDate: new Date(2025, 0, 10),
progress: 80,
type: 'task',
status: 'in-progress',
priority: 'medium',
parent: 'development-phase',
assignee: {
id: 'user-6',
name: 'Frank Miller',
avatar: 'https://ui-avatars.com/api/?name=Frank+Miller&background=13c2c2&color=fff',
},
dependencies: ['milestone-planning-complete'],
tags: ['database', 'migration'],
level: 2,
},
// Testing Phase
{
id: 'testing-phase',
name: '🧪 Testing & QA Phase',
startDate: new Date(2025, 2, 1),
endDate: new Date(2025, 2, 20),
progress: 0,
type: 'project',
status: 'not-started',
priority: 'high',
parent: 'project-1',
color: '#fa8c16',
hasChildren: true,
isExpanded: false,
level: 1,
},
{
id: 'unit-testing',
name: 'Unit Testing Implementation',
startDate: new Date(2025, 2, 1),
endDate: new Date(2025, 2, 10),
progress: 0,
type: 'task',
status: 'not-started',
priority: 'high',
parent: 'testing-phase',
assignee: {
id: 'user-7',
name: 'Grace Lee',
avatar: 'https://ui-avatars.com/api/?name=Grace+Lee&background=fa8c16&color=fff',
},
dependencies: ['frontend-development'],
tags: ['testing', 'unit'],
level: 2,
},
{
id: 'integration-testing',
name: 'Integration & E2E Testing',
startDate: new Date(2025, 2, 8),
endDate: new Date(2025, 2, 18),
progress: 0,
type: 'task',
status: 'not-started',
priority: 'high',
parent: 'testing-phase',
assignee: {
id: 'user-8',
name: 'Henry Clark',
avatar: 'https://ui-avatars.com/api/?name=Henry+Clark&background=eb2f96&color=fff',
},
dependencies: ['unit-testing'],
tags: ['testing', 'integration'],
level: 2,
},
{
id: 'milestone-beta-ready',
name: '🎯 Beta Release Ready',
startDate: new Date(2025, 2, 20),
endDate: new Date(2025, 2, 20),
progress: 0,
type: 'milestone',
status: 'not-started',
priority: 'critical',
parent: 'testing-phase',
dependencies: ['integration-testing'],
level: 2,
},
// Deployment Phase
{
id: 'deployment-phase',
name: '🚀 Deployment & Launch',
startDate: new Date(2025, 2, 21),
endDate: new Date(2025, 2, 31),
progress: 0,
type: 'project',
status: 'not-started',
priority: 'critical',
parent: 'project-1',
color: '#f5222d',
hasChildren: true,
isExpanded: false,
level: 1,
},
{
id: 'production-deployment',
name: 'Production Environment Setup',
startDate: new Date(2025, 2, 21),
endDate: new Date(2025, 2, 25),
progress: 0,
type: 'task',
status: 'not-started',
priority: 'critical',
parent: 'deployment-phase',
assignee: {
id: 'user-9',
name: 'Ivy Taylor',
avatar: 'https://ui-avatars.com/api/?name=Ivy+Taylor&background=f5222d&color=fff',
},
dependencies: ['milestone-beta-ready'],
tags: ['deployment', 'production'],
level: 2,
},
{
id: 'go-live',
name: 'Go Live & Monitoring',
startDate: new Date(2025, 2, 26),
endDate: new Date(2025, 2, 31),
progress: 0,
type: 'task',
status: 'not-started',
priority: 'critical',
parent: 'deployment-phase',
assignee: {
id: 'user-10',
name: 'Jack Anderson',
avatar: 'https://ui-avatars.com/api/?name=Jack+Anderson&background=2f54eb&color=fff',
},
dependencies: ['production-deployment'],
tags: ['launch', 'monitoring'],
level: 2,
},
{
id: 'milestone-project-complete',
name: '🎉 Project Launch Complete',
startDate: new Date(2025, 2, 31),
endDate: new Date(2025, 2, 31),
progress: 0,
type: 'milestone',
status: 'not-started',
priority: 'critical',
parent: 'deployment-phase',
dependencies: ['go-live'],
level: 2,
},
];
};
// Enhanced column configuration
const sampleColumns: ColumnConfig[] = [
{
field: 'name',
title: 'Task / Phase Name',
width: 300,
minWidth: 200,
resizable: true,
sortable: true,
fixed: true,
editor: 'text'
},
{
field: 'assignee',
title: 'Assignee',
width: 150,
minWidth: 120,
resizable: true,
sortable: true,
fixed: true
},
{
field: 'startDate',
title: 'Start Date',
width: 120,
minWidth: 100,
resizable: true,
sortable: true,
fixed: true,
editor: 'date'
},
{
field: 'endDate',
title: 'End Date',
width: 120,
minWidth: 100,
resizable: true,
sortable: true,
fixed: true,
editor: 'date'
},
{
field: 'duration',
title: 'Duration',
width: 80,
minWidth: 60,
resizable: true,
sortable: false,
fixed: true,
align: 'center'
},
{
field: 'progress',
title: 'Progress',
width: 120,
minWidth: 100,
resizable: true,
sortable: true,
fixed: true,
editor: 'number'
},
{
field: 'status',
title: 'Status',
width: 100,
minWidth: 80,
resizable: true,
sortable: true,
fixed: true,
editor: 'select',
editorOptions: [
{ value: 'not-started', label: 'Not Started' },
{ value: 'in-progress', label: 'In Progress' },
{ value: 'completed', label: 'Completed' },
{ value: 'on-hold', label: 'On Hold' },
{ value: 'overdue', label: 'Overdue' },
]
},
{
field: 'priority',
title: 'Priority',
width: 100,
minWidth: 80,
resizable: true,
sortable: true,
fixed: true,
editor: 'select',
editorOptions: [
{ value: 'low', label: 'Low' },
{ value: 'medium', label: 'Medium' },
{ value: 'high', label: 'High' },
{ value: 'critical', label: 'Critical' },
]
},
];
const AdvancedGanttDemo: React.FC = () => {
const [tasks, setTasks] = useState<GanttTask[]>(generateSampleTasks());
const [selectedTasks, setSelectedTasks] = useState<string[]>([]);
const themeMode = useAppSelector(state => state.themeReducer.mode);
const handleTaskUpdate = (taskId: string, updates: Partial<GanttTask>) => {
setTasks(prevTasks =>
prevTasks.map(task =>
task.id === taskId ? { ...task, ...updates } : task
)
);
message.success(`Task "${tasks.find(t => t.id === taskId)?.name}" updated`);
};
const handleTaskMove = (taskId: string, newDates: { start: Date; end: Date }) => {
setTasks(prevTasks =>
prevTasks.map(task =>
task.id === taskId
? { ...task, startDate: newDates.start, endDate: newDates.end }
: task
)
);
message.info(`Task moved: ${newDates.start.toLocaleDateString()} - ${newDates.end.toLocaleDateString()}`);
};
const handleProgressChange = (taskId: string, progress: number) => {
setTasks(prevTasks =>
prevTasks.map(task =>
task.id === taskId ? { ...task, progress } : task
)
);
message.info(`Progress updated: ${Math.round(progress)}%`);
};
const handleSelectionChange = (selection: any) => {
setSelectedTasks(selection.selectedTasks);
};
const resetToSampleData = () => {
setTasks(generateSampleTasks());
setSelectedTasks([]);
message.info('Gantt chart reset to sample data');
};
const addSampleTask = () => {
const newTask: GanttTask = {
id: `task-${Date.now()}`,
name: `New Task ${tasks.length + 1}`,
startDate: new Date(),
endDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // +7 days
progress: 0,
type: 'task',
status: 'not-started',
priority: 'medium',
level: 0,
};
setTasks(prev => [...prev, newTask]);
message.success('New task added');
};
const deleteSelectedTasks = () => {
if (selectedTasks.length === 0) {
message.warning('No tasks selected');
return;
}
setTasks(prev => prev.filter(task => !selectedTasks.includes(task.id)));
setSelectedTasks([]);
message.success(`${selectedTasks.length} task(s) deleted`);
};
const taskStats = useMemo(() => {
const total = tasks.length;
const completed = tasks.filter(t => t.status === 'completed').length;
const inProgress = tasks.filter(t => t.status === 'in-progress').length;
const overdue = tasks.filter(t => t.status === 'overdue').length;
const avgProgress = tasks.reduce((sum, t) => sum + t.progress, 0) / total;
return { total, completed, inProgress, overdue, avgProgress };
}, [tasks]);
return (
<div className="advanced-gantt-demo p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
{/* Header */}
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-sm mb-4">
<div className="p-6">
<div className="flex justify-between items-start mb-4">
<div>
<h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100 mb-2">
🚀 Advanced Gantt Chart Demo
</h1>
<p className="text-gray-600 dark:text-gray-400 mb-4">
Professional Gantt chart with draggable tasks, virtual scrolling, holiday markers,
and performance optimizations for modern project management.
</p>
</div>
<div className="flex flex-col items-end space-y-2">
<Space>
<Button
onClick={addSampleTask}
type="primary"
className="dark:border-gray-600"
>
Add Task
</Button>
<Button
onClick={deleteSelectedTasks}
danger
disabled={selectedTasks.length === 0}
className="dark:border-gray-600"
>
Delete Selected ({selectedTasks.length})
</Button>
<Button
onClick={resetToSampleData}
className="dark:border-gray-600 dark:text-gray-300"
>
Reset Data
</Button>
</Space>
</div>
</div>
{/* Project Statistics */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="bg-blue-50 dark:bg-blue-900 dark:bg-opacity-20 rounded-lg p-3">
<div className="text-blue-600 dark:text-blue-400 text-sm font-medium">Total Tasks</div>
<div className="text-2xl font-bold text-blue-700 dark:text-blue-300">{taskStats.total}</div>
</div>
<div className="bg-green-50 dark:bg-green-900 dark:bg-opacity-20 rounded-lg p-3">
<div className="text-green-600 dark:text-green-400 text-sm font-medium">Completed</div>
<div className="text-2xl font-bold text-green-700 dark:text-green-300">{taskStats.completed}</div>
</div>
<div className="bg-yellow-50 dark:bg-yellow-900 dark:bg-opacity-20 rounded-lg p-3">
<div className="text-yellow-600 dark:text-yellow-400 text-sm font-medium">In Progress</div>
<div className="text-2xl font-bold text-yellow-700 dark:text-yellow-300">{taskStats.inProgress}</div>
</div>
<div className="bg-purple-50 dark:bg-purple-900 dark:bg-opacity-20 rounded-lg p-3">
<div className="text-purple-600 dark:text-purple-400 text-sm font-medium">Avg Progress</div>
<div className="text-2xl font-bold text-purple-700 dark:text-purple-300">
{Math.round(taskStats.avgProgress)}%
</div>
</div>
</div>
</div>
</div>
{/* Gantt Chart */}
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-sm" style={{ height: '70vh' }}>
<AdvancedGanttChart
tasks={tasks}
columns={sampleColumns}
timelineConfig={{
showWeekends: true,
showNonWorkingDays: true,
holidays: holidayPresets.US,
workingDays: workingDayPresets.standard,
dayWidth: 30,
}}
onTaskUpdate={handleTaskUpdate}
onTaskMove={handleTaskMove}
onProgressChange={handleProgressChange}
onSelectionChange={handleSelectionChange}
enableDragDrop={true}
enableResize={true}
enableProgressEdit={true}
enableInlineEdit={true}
enableVirtualScrolling={true}
className="h-full"
/>
</div>
{/* Feature List */}
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-sm mt-4">
<div className="p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-3">
Advanced Features Demonstrated
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 text-sm">
<div className="space-y-2">
<h4 className="font-medium text-gray-900 dark:text-gray-100">Performance & UX</h4>
<ul className="space-y-1 text-gray-600 dark:text-gray-400">
<li> Virtual scrolling for 1000+ tasks</li>
<li> Smooth 60fps drag & drop</li>
<li> Debounced updates</li>
<li> Memory-optimized rendering</li>
<li> Responsive design</li>
</ul>
</div>
<div className="space-y-2">
<h4 className="font-medium text-gray-900 dark:text-gray-100">Gantt Features</h4>
<ul className="space-y-1 text-gray-600 dark:text-gray-400">
<li> Draggable task bars</li>
<li> Resizable task duration</li>
<li> Progress editing</li>
<li> Multi-level hierarchy</li>
<li> Task dependencies</li>
</ul>
</div>
<div className="space-y-2">
<h4 className="font-medium text-gray-900 dark:text-gray-100">Timeline & Markers</h4>
<ul className="space-y-1 text-gray-600 dark:text-gray-400">
<li> Weekend & holiday markers</li>
<li> Working day indicators</li>
<li> Today line</li>
<li> Multi-tier timeline</li>
<li> Zoom levels (Year/Month/Week/Day)</li>
</ul>
</div>
<div className="space-y-2">
<h4 className="font-medium text-gray-900 dark:text-gray-100">Grid Features</h4>
<ul className="space-y-1 text-gray-600 dark:text-gray-400">
<li> Fixed columns layout</li>
<li> Inline editing</li>
<li> Column resizing</li>
<li> Multi-select</li>
<li> Hierarchical tree view</li>
</ul>
</div>
<div className="space-y-2">
<h4 className="font-medium text-gray-900 dark:text-gray-100">UI/UX</h4>
<ul className="space-y-1 text-gray-600 dark:text-gray-400">
<li> Dark/Light theme support</li>
<li> Tailwind CSS styling</li>
<li> Consistent with Worklenz</li>
<li> Accessibility features</li>
<li> Mobile responsive</li>
</ul>
</div>
<div className="space-y-2">
<h4 className="font-medium text-gray-900 dark:text-gray-100">Architecture</h4>
<ul className="space-y-1 text-gray-600 dark:text-gray-400">
<li> Modern React patterns</li>
<li> TypeScript safety</li>
<li> Optimized performance</li>
<li> Enterprise features</li>
<li> Best practices 2025</li>
</ul>
</div>
</div>
</div>
</div>
</div>
);
};
export default AdvancedGanttDemo;

View File

@@ -0,0 +1,304 @@
import React, { useState, useRef, useCallback, useMemo } from 'react';
import { GanttTask, DragState } from '../../types/advanced-gantt.types';
import { useAppSelector } from '../../hooks/useAppSelector';
import { themeWiseColor } from '../../utils/themeWiseColor';
import { useDateCalculations } from '../../utils/gantt-performance';
interface DraggableTaskBarProps {
task: GanttTask;
timelineStart: Date;
dayWidth: number;
rowHeight: number;
index: number;
onTaskMove?: (taskId: string, newDates: { start: Date; end: Date }) => void;
onTaskResize?: (taskId: string, newDates: { start: Date; end: Date }) => void;
onProgressChange?: (taskId: string, progress: number) => void;
onTaskClick?: (task: GanttTask) => void;
onTaskDoubleClick?: (task: GanttTask) => void;
enableDragDrop?: boolean;
enableResize?: boolean;
enableProgressEdit?: boolean;
readOnly?: boolean;
}
const DraggableTaskBar: React.FC<DraggableTaskBarProps> = ({
task,
timelineStart,
dayWidth,
rowHeight,
index,
onTaskMove,
onTaskResize,
onProgressChange,
onTaskClick,
onTaskDoubleClick,
enableDragDrop = true,
enableResize = true,
enableProgressEdit = true,
readOnly = false,
}) => {
const [dragState, setDragState] = useState<DragState | null>(null);
const [hoverState, setHoverState] = useState<string | null>(null);
const taskBarRef = useRef<HTMLDivElement>(null);
const themeMode = useAppSelector(state => state.themeReducer.mode);
const { getDaysBetween, addDays } = useDateCalculations();
// Calculate task position and dimensions
const taskPosition = useMemo(() => {
const startDays = getDaysBetween(timelineStart, task.startDate);
const duration = getDaysBetween(task.startDate, task.endDate);
return {
x: startDays * dayWidth,
width: Math.max(dayWidth * 0.5, duration * dayWidth),
y: index * rowHeight + 8, // 8px padding
height: rowHeight - 16, // 16px total padding
};
}, [task.startDate, task.endDate, timelineStart, dayWidth, rowHeight, index, getDaysBetween]);
// Theme-aware colors
const colors = useMemo(() => {
const baseColor = task.color || getDefaultTaskColor(task.status);
return {
background: themeWiseColor(baseColor, adjustColorForDarkMode(baseColor), themeMode),
border: themeWiseColor(darkenColor(baseColor, 0.2), lightenColor(baseColor, 0.2), themeMode),
progress: themeWiseColor('#52c41a', '#34d399', themeMode),
text: themeWiseColor('#ffffff', '#f9fafb', themeMode),
hover: themeWiseColor(lightenColor(baseColor, 0.1), darkenColor(baseColor, 0.1), themeMode),
};
}, [task.color, task.status, themeMode]);
// Mouse event handlers
const handleMouseDown = useCallback((e: React.MouseEvent, dragType: DragState['dragType']) => {
if (readOnly || !enableDragDrop) return;
e.preventDefault();
e.stopPropagation();
const rect = taskBarRef.current?.getBoundingClientRect();
if (!rect) return;
setDragState({
isDragging: true,
dragType,
taskId: task.id,
initialPosition: { x: e.clientX, y: e.clientY },
currentPosition: { x: e.clientX, y: e.clientY },
initialDates: { start: task.startDate, end: task.endDate },
initialProgress: task.progress,
snapToGrid: true,
});
// Add global mouse event listeners
const handleMouseMove = (moveEvent: MouseEvent) => {
handleMouseMove_Internal(moveEvent, dragType);
};
const handleMouseUp = () => {
handleMouseUp_Internal();
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
}, [readOnly, enableDragDrop, task]);
const handleMouseMove_Internal = useCallback((e: MouseEvent, dragType: DragState['dragType']) => {
if (!dragState) return;
const deltaX = e.clientX - dragState.initialPosition.x;
const deltaDays = Math.round(deltaX / dayWidth);
let newStartDate = task.startDate;
let newEndDate = task.endDate;
switch (dragType) {
case 'move':
newStartDate = addDays(dragState.initialDates.start, deltaDays);
newEndDate = addDays(dragState.initialDates.end, deltaDays);
break;
case 'resize-start':
newStartDate = addDays(dragState.initialDates.start, deltaDays);
// Ensure minimum duration
if (newStartDate >= newEndDate) {
newStartDate = addDays(newEndDate, -1);
}
break;
case 'resize-end':
newEndDate = addDays(dragState.initialDates.end, deltaDays);
// Ensure minimum duration
if (newEndDate <= newStartDate) {
newEndDate = addDays(newStartDate, 1);
}
break;
case 'progress':
if (enableProgressEdit) {
const progressDelta = deltaX / taskPosition.width;
const newProgress = Math.max(0, Math.min(100, (dragState.initialProgress || 0) + progressDelta * 100));
onProgressChange?.(task.id, newProgress);
}
return;
}
// Update drag state
setDragState(prev => prev ? {
...prev,
currentPosition: { x: e.clientX, y: e.clientY },
} : null);
// Call appropriate handler
if (dragType === 'move') {
onTaskMove?.(task.id, { start: newStartDate, end: newEndDate });
} else if (dragType.startsWith('resize')) {
onTaskResize?.(task.id, { start: newStartDate, end: newEndDate });
}
}, [dragState, dayWidth, task, taskPosition.width, enableProgressEdit, onTaskMove, onTaskResize, onProgressChange, addDays]);
const handleMouseUp_Internal = useCallback(() => {
setDragState(null);
}, []);
const handleClick = useCallback((e: React.MouseEvent) => {
e.stopPropagation();
onTaskClick?.(task);
}, [task, onTaskClick]);
const handleDoubleClick = useCallback((e: React.MouseEvent) => {
e.stopPropagation();
onTaskDoubleClick?.(task);
}, [task, onTaskDoubleClick]);
// Render task bar with handles
const renderTaskBar = () => {
const isSelected = false; // TODO: Get from selection state
const isDragging = dragState?.isDragging || false;
return (
<div
ref={taskBarRef}
className={`task-bar relative cursor-pointer select-none transition-all duration-200 ${
isDragging ? 'z-10 shadow-lg' : ''
} ${isSelected ? 'ring-2 ring-blue-500 ring-opacity-50' : ''}`}
style={{
position: 'absolute',
left: taskPosition.x,
top: taskPosition.y,
width: taskPosition.width,
height: taskPosition.height,
backgroundColor: dragState?.isDragging ? colors.hover : colors.background,
border: `1px solid ${colors.border}`,
borderRadius: '4px',
transform: isDragging ? 'translateY(-2px)' : 'none',
boxShadow: isDragging ? '0 4px 12px rgba(0,0,0,0.15)' : '0 1px 3px rgba(0,0,0,0.1)',
}}
onClick={handleClick}
onDoubleClick={handleDoubleClick}
onMouseEnter={() => setHoverState('task')}
onMouseLeave={() => setHoverState(null)}
onMouseDown={(e) => handleMouseDown(e, 'move')}
>
{/* Progress bar */}
<div
className="progress-bar absolute inset-0 rounded-l"
style={{
width: `${task.progress}%`,
backgroundColor: colors.progress,
opacity: 0.7,
borderRadius: '3px 0 0 3px',
}}
/>
{/* Task content */}
<div className="task-content relative z-10 h-full flex items-center px-2">
<span
className="task-name text-xs font-medium truncate"
style={{ color: colors.text }}
>
{task.name}
</span>
{/* Duration display for smaller tasks */}
{taskPosition.width < 100 && (
<span
className="task-duration text-xs ml-auto"
style={{ color: colors.text, opacity: 0.8 }}
>
{getDaysBetween(task.startDate, task.endDate)}d
</span>
)}
</div>
{/* Resize handles */}
{enableResize && !readOnly && hoverState === 'task' && (
<>
{/* Left resize handle */}
<div
className="resize-handle-left absolute left-0 top-0 w-1 h-full cursor-ew-resize bg-white bg-opacity-50 hover:bg-opacity-80"
onMouseDown={(e) => handleMouseDown(e, 'resize-start')}
onMouseEnter={() => setHoverState('resize-start')}
/>
{/* Right resize handle */}
<div
className="resize-handle-right absolute right-0 top-0 w-1 h-full cursor-ew-resize bg-white bg-opacity-50 hover:bg-opacity-80"
onMouseDown={(e) => handleMouseDown(e, 'resize-end')}
onMouseEnter={() => setHoverState('resize-end')}
/>
</>
)}
{/* Progress handle */}
{enableProgressEdit && !readOnly && hoverState === 'task' && (
<div
className="progress-handle absolute top-0 h-full w-1 cursor-ew-resize bg-blue-500 opacity-75"
style={{ left: `${task.progress}%` }}
onMouseDown={(e) => handleMouseDown(e, 'progress')}
onMouseEnter={() => setHoverState('progress')}
/>
)}
{/* Task type indicator */}
{task.type === 'milestone' && (
<div
className="milestone-indicator absolute -top-1 -right-1 w-3 h-3 transform rotate-45"
style={{ backgroundColor: colors.border }}
/>
)}
</div>
);
};
return renderTaskBar();
};
// Helper functions
function getDefaultTaskColor(status: GanttTask['status']): string {
switch (status) {
case 'completed': return '#52c41a';
case 'in-progress': return '#1890ff';
case 'overdue': return '#ff4d4f';
case 'on-hold': return '#faad14';
default: return '#d9d9d9';
}
}
function darkenColor(color: string, amount: number): string {
// Simple color darkening - in a real app, use a proper color manipulation library
return color;
}
function lightenColor(color: string, amount: number): string {
// Simple color lightening - in a real app, use a proper color manipulation library
return color;
}
function adjustColorForDarkMode(color: string): string {
// Adjust color for dark mode - in a real app, use a proper color manipulation library
return color;
}
export default DraggableTaskBar;

View File

@@ -0,0 +1,492 @@
import React, { useMemo, useRef, useState, useCallback } from 'react';
import { GanttTask, ColumnConfig, SelectionState } from '../../types/advanced-gantt.types';
import { useAppSelector } from '../../hooks/useAppSelector';
import { themeWiseColor } from '../../utils/themeWiseColor';
import { ChevronRightIcon, ChevronDownIcon } from '@heroicons/react/24/outline';
import { CalendarIcon, UserIcon, FlagIcon } from '@heroicons/react/24/solid';
interface GanttGridProps {
tasks: GanttTask[];
columns: ColumnConfig[];
rowHeight: number;
containerHeight: number;
selection: SelectionState;
enableInlineEdit?: boolean;
enableMultiSelect?: boolean;
onTaskClick?: (task: GanttTask, event: React.MouseEvent) => void;
onTaskDoubleClick?: (task: GanttTask) => void;
onTaskExpand?: (taskId: string) => void;
onSelectionChange?: (selection: SelectionState) => void;
onColumnResize?: (columnField: string, newWidth: number) => void;
onTaskUpdate?: (taskId: string, field: string, value: any) => void;
className?: string;
}
const GanttGrid: React.FC<GanttGridProps> = ({
tasks,
columns,
rowHeight,
containerHeight,
selection,
enableInlineEdit = true,
enableMultiSelect = true,
onTaskClick,
onTaskDoubleClick,
onTaskExpand,
onSelectionChange,
onColumnResize,
onTaskUpdate,
className = '',
}) => {
const [editingCell, setEditingCell] = useState<{ taskId: string; field: string } | null>(null);
const [columnWidths, setColumnWidths] = useState<Record<string, number>>(
columns.reduce((acc, col) => ({ ...acc, [col.field]: col.width }), {})
);
const gridRef = useRef<HTMLDivElement>(null);
const themeMode = useAppSelector(state => state.themeReducer.mode);
// Theme-aware colors
const colors = useMemo(() => ({
background: themeWiseColor('#ffffff', '#1f2937', themeMode),
alternateRow: themeWiseColor('#f9fafb', '#374151', themeMode),
border: themeWiseColor('#e5e7eb', '#4b5563', themeMode),
text: themeWiseColor('#111827', '#f9fafb', themeMode),
textSecondary: themeWiseColor('#6b7280', '#d1d5db', themeMode),
selected: themeWiseColor('#eff6ff', '#1e3a8a', themeMode),
hover: themeWiseColor('#f3f4f6', '#4b5563', themeMode),
headerBg: themeWiseColor('#f8f9fa', '#374151', themeMode),
}), [themeMode]);
// Calculate total grid width
const totalWidth = useMemo(() => {
return columns.reduce((sum, col) => sum + columnWidths[col.field], 0);
}, [columns, columnWidths]);
// Handle column resize
const handleColumnResize = useCallback((columnField: string, deltaX: number) => {
const column = columns.find(col => col.field === columnField);
if (!column) return;
const currentWidth = columnWidths[columnField];
const newWidth = Math.max(column.minWidth || 60, Math.min(column.maxWidth || 400, currentWidth + deltaX));
setColumnWidths(prev => ({ ...prev, [columnField]: newWidth }));
onColumnResize?.(columnField, newWidth);
}, [columns, columnWidths, onColumnResize]);
// Handle task selection
const handleTaskSelection = useCallback((task: GanttTask, event: React.MouseEvent) => {
const { ctrlKey, shiftKey } = event;
let newSelectedTasks = [...selection.selectedTasks];
if (shiftKey && enableMultiSelect && selection.selectedTasks.length > 0) {
// Range selection
const lastSelectedIndex = tasks.findIndex(t => t.id === selection.selectedTasks[selection.selectedTasks.length - 1]);
const currentIndex = tasks.findIndex(t => t.id === task.id);
const [start, end] = [Math.min(lastSelectedIndex, currentIndex), Math.max(lastSelectedIndex, currentIndex)];
newSelectedTasks = tasks.slice(start, end + 1).map(t => t.id);
} else if (ctrlKey && enableMultiSelect) {
// Multi selection
if (newSelectedTasks.includes(task.id)) {
newSelectedTasks = newSelectedTasks.filter(id => id !== task.id);
} else {
newSelectedTasks.push(task.id);
}
} else {
// Single selection
newSelectedTasks = [task.id];
}
onSelectionChange?.({
...selection,
selectedTasks: newSelectedTasks,
focusedTask: task.id,
});
onTaskClick?.(task, event);
}, [tasks, selection, enableMultiSelect, onSelectionChange, onTaskClick]);
// Handle cell editing
const handleCellDoubleClick = useCallback((task: GanttTask, column: ColumnConfig) => {
if (!enableInlineEdit || !column.editor) return;
setEditingCell({ taskId: task.id, field: column.field });
}, [enableInlineEdit]);
const handleCellEditComplete = useCallback((value: any) => {
if (!editingCell) return;
onTaskUpdate?.(editingCell.taskId, editingCell.field, value);
setEditingCell(null);
}, [editingCell, onTaskUpdate]);
// Render cell content
const renderCellContent = useCallback((task: GanttTask, column: ColumnConfig) => {
const value = task[column.field as keyof GanttTask];
const isEditing = editingCell?.taskId === task.id && editingCell?.field === column.field;
if (isEditing) {
return renderCellEditor(value, column, handleCellEditComplete);
}
if (column.renderer) {
return column.renderer(value, task);
}
// Default renderers
switch (column.field) {
case 'name':
return (
<div className="flex items-center space-x-2">
{task.hasChildren && (
<button
onClick={(e) => {
e.stopPropagation();
onTaskExpand?.(task.id);
}}
className="p-0.5 hover:bg-gray-200 dark:hover:bg-gray-600 rounded"
>
{task.isExpanded ? (
<ChevronDownIcon className="w-3 h-3" />
) : (
<ChevronRightIcon className="w-3 h-3" />
)}
</button>
)}
<div
className="flex items-center space-x-2"
style={{ paddingLeft: `${(task.level || 0) * 16}px` }}
>
{getTaskTypeIcon(task.type)}
<span className="truncate font-medium">{task.name}</span>
</div>
</div>
);
case 'startDate':
case 'endDate':
return (
<div className="flex items-center space-x-1">
<CalendarIcon className="w-3 h-3 text-gray-400" />
<span>{(value as Date)?.toLocaleDateString() || '-'}</span>
</div>
);
case 'assignee':
return task.assignee ? (
<div className="flex items-center space-x-2">
{task.assignee.avatar ? (
<img
src={task.assignee.avatar}
alt={task.assignee.name}
className="w-6 h-6 rounded-full"
/>
) : (
<UserIcon className="w-6 h-6 text-gray-400" />
)}
<span className="truncate">{task.assignee.name}</span>
</div>
) : (
<span className="text-gray-400">Unassigned</span>
);
case 'progress':
return (
<div className="flex items-center space-x-2">
<div className="flex-1 bg-gray-200 dark:bg-gray-600 rounded-full h-2">
<div
className="bg-blue-500 h-2 rounded-full transition-all duration-300"
style={{ width: `${task.progress}%` }}
/>
</div>
<span className="text-xs w-8 text-right">{task.progress}%</span>
</div>
);
case 'status':
return (
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(task.status)}`}>
{task.status.replace('-', ' ')}
</span>
);
case 'priority':
return (
<div className="flex items-center space-x-1">
<FlagIcon className={`w-3 h-3 ${getPriorityColor(task.priority)}`} />
<span className="capitalize">{task.priority}</span>
</div>
);
case 'duration':
const duration = task.duration || Math.ceil((task.endDate.getTime() - task.startDate.getTime()) / (1000 * 60 * 60 * 24));
return <span>{duration}d</span>;
default:
return <span>{String(value || '')}</span>;
}
}, [editingCell, onTaskExpand, handleCellEditComplete]);
// Render header
const renderHeader = () => (
<div
className="grid-header flex border-b sticky top-0 z-10"
style={{
backgroundColor: colors.headerBg,
borderColor: colors.border,
height: rowHeight,
}}
>
{columns.map((column, index) => (
<div
key={column.field}
className="column-header flex items-center px-3 py-2 font-medium text-sm border-r relative group"
style={{
width: columnWidths[column.field],
borderColor: colors.border,
color: colors.text,
}}
>
<span className="truncate" title={column.title}>
{column.title}
</span>
{/* Resize handle */}
{column.resizable && (
<ResizeHandle
onResize={(deltaX) => handleColumnResize(column.field, deltaX)}
className="absolute right-0 top-0 h-full w-1 cursor-col-resize hover:bg-blue-500 opacity-0 group-hover:opacity-100"
/>
)}
</div>
))}
</div>
);
// Render task rows
const renderRows = () => (
<div className="grid-body">
{tasks.map((task, rowIndex) => {
const isSelected = selection.selectedTasks.includes(task.id);
const isFocused = selection.focusedTask === task.id;
return (
<div
key={task.id}
className={`grid-row flex border-b cursor-pointer hover:bg-opacity-75 ${
isSelected ? 'bg-blue-50 dark:bg-blue-900 bg-opacity-50' :
rowIndex % 2 === 0 ? '' : 'bg-gray-50 dark:bg-gray-800 bg-opacity-30'
}`}
style={{
height: rowHeight,
borderColor: colors.border,
backgroundColor: isSelected ? colors.selected :
rowIndex % 2 === 0 ? 'transparent' : colors.alternateRow,
}}
onClick={(e) => handleTaskSelection(task, e)}
onDoubleClick={() => onTaskDoubleClick?.(task)}
>
{columns.map((column) => (
<div
key={`${task.id}-${column.field}`}
className="grid-cell flex items-center px-3 py-1 border-r overflow-hidden"
style={{
width: columnWidths[column.field],
borderColor: colors.border,
textAlign: column.align || 'left',
}}
onDoubleClick={() => handleCellDoubleClick(task, column)}
>
{renderCellContent(task, column)}
</div>
))}
</div>
);
})}
</div>
);
return (
<div
ref={gridRef}
className={`gantt-grid border-r ${className}`}
style={{
width: totalWidth,
height: containerHeight,
backgroundColor: colors.background,
borderColor: colors.border,
}}
>
{renderHeader()}
<div
className="grid-content overflow-auto"
style={{ height: containerHeight - rowHeight }}
>
{renderRows()}
</div>
</div>
);
};
// Resize handle component
interface ResizeHandleProps {
onResize: (deltaX: number) => void;
className?: string;
}
const ResizeHandle: React.FC<ResizeHandleProps> = ({ onResize, className }) => {
const [isDragging, setIsDragging] = useState(false);
const startXRef = useRef<number>(0);
const handleMouseDown = useCallback((e: React.MouseEvent) => {
e.preventDefault();
setIsDragging(true);
startXRef.current = e.clientX;
const handleMouseMove = (moveEvent: MouseEvent) => {
const deltaX = moveEvent.clientX - startXRef.current;
onResize(deltaX);
startXRef.current = moveEvent.clientX;
};
const handleMouseUp = () => {
setIsDragging(false);
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
}, [onResize]);
return (
<div
className={`resize-handle ${className} ${isDragging ? 'bg-blue-500' : ''}`}
onMouseDown={handleMouseDown}
/>
);
};
// Cell editor component
const renderCellEditor = (value: any, column: ColumnConfig, onComplete: (value: any) => void) => {
const [editValue, setEditValue] = useState(value);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
onComplete(editValue);
} else if (e.key === 'Escape') {
onComplete(value); // Cancel editing
}
};
const handleBlur = () => {
onComplete(editValue);
};
switch (column.editor) {
case 'text':
return (
<input
type="text"
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
className="w-full px-1 py-0.5 border rounded text-sm"
autoFocus
/>
);
case 'date':
return (
<input
type="date"
value={editValue instanceof Date ? editValue.toISOString().split('T')[0] : editValue}
onChange={(e) => setEditValue(new Date(e.target.value))}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
className="w-full px-1 py-0.5 border rounded text-sm"
autoFocus
/>
);
case 'number':
return (
<input
type="number"
value={editValue}
onChange={(e) => setEditValue(parseFloat(e.target.value))}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
className="w-full px-1 py-0.5 border rounded text-sm"
autoFocus
/>
);
case 'select':
return (
<select
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
className="w-full px-1 py-0.5 border rounded text-sm"
autoFocus
>
{column.editorOptions?.map((option: any) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
);
default:
return <span>{String(value)}</span>;
}
};
// Helper functions
const getTaskTypeIcon = (type: GanttTask['type']) => {
switch (type) {
case 'project':
return <div className="w-3 h-3 bg-blue-500 rounded-sm" />;
case 'milestone':
return <div className="w-3 h-3 bg-yellow-500 rotate-45" />;
default:
return <div className="w-3 h-3 bg-gray-400 rounded-full" />;
}
};
const getStatusColor = (status: GanttTask['status']) => {
switch (status) {
case 'completed':
return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
case 'in-progress':
return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
case 'overdue':
return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200';
case 'on-hold':
return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
default:
return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200';
}
};
const getPriorityColor = (priority: GanttTask['priority']) => {
switch (priority) {
case 'critical':
return 'text-red-600';
case 'high':
return 'text-orange-500';
case 'medium':
return 'text-yellow-500';
case 'low':
return 'text-green-500';
default:
return 'text-gray-400';
}
};
export default GanttGrid;

View File

@@ -0,0 +1,295 @@
import React, { useMemo } from 'react';
import { Holiday, TimelineConfig } from '../../types/advanced-gantt.types';
import { useAppSelector } from '../../hooks/useAppSelector';
import { themeWiseColor } from '../../utils/themeWiseColor';
import { useDateCalculations } from '../../utils/gantt-performance';
interface TimelineMarkersProps {
startDate: Date;
endDate: Date;
dayWidth: number;
containerHeight: number;
timelineConfig: TimelineConfig;
holidays?: Holiday[];
showWeekends?: boolean;
showHolidays?: boolean;
showToday?: boolean;
className?: string;
}
const TimelineMarkers: React.FC<TimelineMarkersProps> = ({
startDate,
endDate,
dayWidth,
containerHeight,
timelineConfig,
holidays = [],
showWeekends = true,
showHolidays = true,
showToday = true,
className = '',
}) => {
const themeMode = useAppSelector(state => state.themeReducer.mode);
const { getDaysBetween, isWeekend, isWorkingDay } = useDateCalculations();
// Generate all dates in the timeline
const timelineDates = useMemo(() => {
const dates: Date[] = [];
const totalDays = getDaysBetween(startDate, endDate);
for (let i = 0; i <= totalDays; i++) {
const date = new Date(startDate);
date.setDate(date.getDate() + i);
dates.push(date);
}
return dates;
}, [startDate, endDate, getDaysBetween]);
// Theme-aware colors
const colors = useMemo(() => ({
weekend: themeWiseColor('rgba(0, 0, 0, 0.05)', 'rgba(255, 255, 255, 0.05)', themeMode),
nonWorkingDay: themeWiseColor('rgba(0, 0, 0, 0.03)', 'rgba(255, 255, 255, 0.03)', themeMode),
holiday: themeWiseColor('rgba(255, 107, 107, 0.1)', 'rgba(255, 107, 107, 0.15)', themeMode),
today: themeWiseColor('rgba(24, 144, 255, 0.15)', 'rgba(64, 169, 255, 0.2)', themeMode),
todayLine: themeWiseColor('#1890ff', '#40a9ff', themeMode),
holidayBorder: themeWiseColor('#ff6b6b', '#ff8787', themeMode),
}), [themeMode]);
// Check if a date is a holiday
const isHoliday = (date: Date): Holiday | undefined => {
return holidays.find(holiday => {
if (holiday.recurring) {
return holiday.date.getMonth() === date.getMonth() &&
holiday.date.getDate() === date.getDate();
}
return holiday.date.toDateString() === date.toDateString();
});
};
// Check if date is today
const isToday = (date: Date): boolean => {
const today = new Date();
return date.toDateString() === today.toDateString();
};
// Render weekend markers
const renderWeekendMarkers = () => {
if (!showWeekends) return null;
return timelineDates.map((date, index) => {
if (!isWeekend(date)) return null;
return (
<div
key={`weekend-${index}`}
className="weekend-marker absolute top-0 pointer-events-none"
style={{
left: index * dayWidth,
width: dayWidth,
height: containerHeight,
backgroundColor: colors.weekend,
zIndex: 1,
}}
/>
);
});
};
// Render non-working day markers
const renderNonWorkingDayMarkers = () => {
return timelineDates.map((date, index) => {
if (isWorkingDay(date, timelineConfig.workingDays)) return null;
return (
<div
key={`non-working-${index}`}
className="non-working-day-marker absolute top-0 pointer-events-none"
style={{
left: index * dayWidth,
width: dayWidth,
height: containerHeight,
backgroundColor: colors.nonWorkingDay,
zIndex: 1,
}}
/>
);
});
};
// Render holiday markers
const renderHolidayMarkers = () => {
if (!showHolidays) return null;
return timelineDates.map((date, index) => {
const holiday = isHoliday(date);
if (!holiday) return null;
const holidayColor = holiday.color || colors.holiday;
return (
<div
key={`holiday-${index}`}
className="holiday-marker absolute top-0 pointer-events-none group"
style={{
left: index * dayWidth,
width: dayWidth,
height: containerHeight,
backgroundColor: holidayColor,
borderLeft: `2px solid ${colors.holidayBorder}`,
zIndex: 2,
}}
>
{/* Holiday tooltip */}
<div className="holiday-tooltip absolute top-0 left-1/2 transform -translate-x-1/2 -translate-y-full bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900 text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity duration-200 whitespace-nowrap z-50">
<div className="font-medium">{holiday.name}</div>
<div className="text-xs opacity-75">{date.toLocaleDateString()}</div>
<div className="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-2 border-r-2 border-t-4 border-transparent border-t-gray-900 dark:border-t-gray-100"></div>
</div>
{/* Holiday icon */}
<div className="holiday-icon absolute top-1 left-1 w-3 h-3 rounded-full bg-red-500 opacity-75">
<div className="w-full h-full rounded-full animate-pulse"></div>
</div>
</div>
);
});
};
// Render today marker
const renderTodayMarker = () => {
if (!showToday) return null;
const todayIndex = timelineDates.findIndex(date => isToday(date));
if (todayIndex === -1) return null;
return (
<div
className="today-marker absolute top-0 pointer-events-none"
style={{
left: todayIndex * dayWidth,
width: dayWidth,
height: containerHeight,
backgroundColor: colors.today,
zIndex: 3,
}}
>
{/* Today line */}
<div
className="today-line absolute top-0 left-1/2 transform -translate-x-1/2"
style={{
width: '2px',
height: containerHeight,
backgroundColor: colors.todayLine,
zIndex: 4,
}}
/>
{/* Today label */}
<div className="today-label absolute top-2 left-1/2 transform -translate-x-1/2 bg-blue-500 text-white text-xs px-2 py-1 rounded shadow-sm">
Today
</div>
</div>
);
};
// Render time period markers (quarters, months, etc.)
const renderTimePeriodMarkers = () => {
const markers: React.ReactNode[] = [];
const currentDate = new Date(startDate);
currentDate.setDate(1); // Start of month
while (currentDate <= endDate) {
const daysSinceStart = getDaysBetween(startDate, currentDate);
const isQuarterStart = currentDate.getMonth() % 3 === 0 && currentDate.getDate() === 1;
const isYearStart = currentDate.getMonth() === 0 && currentDate.getDate() === 1;
if (isYearStart) {
markers.push(
<div
key={`year-${currentDate.getTime()}`}
className="year-marker absolute top-0 border-l-2 border-blue-600 dark:border-blue-400"
style={{
left: daysSinceStart * dayWidth,
height: containerHeight,
zIndex: 5,
}}
>
<div className="year-label absolute top-2 left-1 bg-blue-600 dark:bg-blue-400 text-white text-xs px-1 py-0.5 rounded">
{currentDate.getFullYear()}
</div>
</div>
);
} else if (isQuarterStart) {
markers.push(
<div
key={`quarter-${currentDate.getTime()}`}
className="quarter-marker absolute top-0 border-l border-green-500 dark:border-green-400 opacity-60"
style={{
left: daysSinceStart * dayWidth,
height: containerHeight,
zIndex: 4,
}}
>
<div className="quarter-label absolute top-2 left-1 bg-green-500 dark:bg-green-400 text-white text-xs px-1 py-0.5 rounded">
Q{Math.floor(currentDate.getMonth() / 3) + 1}
</div>
</div>
);
}
// Move to next month
currentDate.setMonth(currentDate.getMonth() + 1);
}
return markers;
};
return (
<div className={`timeline-markers absolute inset-0 ${className}`}>
{renderNonWorkingDayMarkers()}
{renderWeekendMarkers()}
{renderHolidayMarkers()}
{renderTodayMarker()}
{renderTimePeriodMarkers()}
</div>
);
};
// Holiday presets for common countries
export const holidayPresets = {
US: [
{ date: new Date(2024, 0, 1), name: "New Year's Day", type: 'national' as const, recurring: true },
{ date: new Date(2024, 0, 15), name: "Martin Luther King Jr. Day", type: 'national' as const, recurring: true },
{ date: new Date(2024, 1, 19), name: "Presidents' Day", type: 'national' as const, recurring: true },
{ date: new Date(2024, 4, 27), name: "Memorial Day", type: 'national' as const, recurring: true },
{ date: new Date(2024, 5, 19), name: "Juneteenth", type: 'national' as const, recurring: true },
{ date: new Date(2024, 6, 4), name: "Independence Day", type: 'national' as const, recurring: true },
{ date: new Date(2024, 8, 2), name: "Labor Day", type: 'national' as const, recurring: true },
{ date: new Date(2024, 9, 14), name: "Columbus Day", type: 'national' as const, recurring: true },
{ date: new Date(2024, 10, 11), name: "Veterans Day", type: 'national' as const, recurring: true },
{ date: new Date(2024, 10, 28), name: "Thanksgiving", type: 'national' as const, recurring: true },
{ date: new Date(2024, 11, 25), name: "Christmas Day", type: 'national' as const, recurring: true },
],
UK: [
{ date: new Date(2024, 0, 1), name: "New Year's Day", type: 'national' as const, recurring: true },
{ date: new Date(2024, 2, 29), name: "Good Friday", type: 'religious' as const, recurring: false },
{ date: new Date(2024, 3, 1), name: "Easter Monday", type: 'religious' as const, recurring: false },
{ date: new Date(2024, 4, 6), name: "Early May Bank Holiday", type: 'national' as const, recurring: true },
{ date: new Date(2024, 4, 27), name: "Spring Bank Holiday", type: 'national' as const, recurring: true },
{ date: new Date(2024, 7, 26), name: "Summer Bank Holiday", type: 'national' as const, recurring: true },
{ date: new Date(2024, 11, 25), name: "Christmas Day", type: 'religious' as const, recurring: true },
{ date: new Date(2024, 11, 26), name: "Boxing Day", type: 'national' as const, recurring: true },
],
};
// Working day presets
export const workingDayPresets = {
standard: [1, 2, 3, 4, 5], // Monday to Friday
middle_east: [0, 1, 2, 3, 4], // Sunday to Thursday
six_day: [1, 2, 3, 4, 5, 6], // Monday to Saturday
four_day: [1, 2, 3, 4], // Monday to Thursday
};
export default TimelineMarkers;

View File

@@ -0,0 +1,372 @@
import React, { useRef, useEffect, useState, useCallback, ReactNode } from 'react';
import { useThrottle, usePerformanceMonitoring } from '../../utils/gantt-performance';
import { useAppSelector } from '../../hooks/useAppSelector';
interface VirtualScrollContainerProps {
items: any[];
itemHeight: number;
containerHeight: number;
containerWidth?: number;
overscan?: number;
horizontal?: boolean;
children: (item: any, index: number, style: React.CSSProperties) => ReactNode;
onScroll?: (scrollLeft: number, scrollTop: number) => void;
className?: string;
style?: React.CSSProperties;
}
const VirtualScrollContainer: React.FC<VirtualScrollContainerProps> = ({
items,
itemHeight,
containerHeight,
containerWidth = 0,
overscan = 5,
horizontal = false,
children,
onScroll,
className = '',
style = {},
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const [scrollTop, setScrollTop] = useState(0);
const [scrollLeft, setScrollLeft] = useState(0);
const { startMeasure, endMeasure, recordMetric } = usePerformanceMonitoring();
const themeMode = useAppSelector(state => state.themeReducer.mode);
// Calculate visible range
const totalHeight = items.length * itemHeight;
const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - overscan);
const endIndex = Math.min(
items.length - 1,
Math.ceil((scrollTop + containerHeight) / itemHeight) + overscan
);
const visibleItems = items.slice(startIndex, endIndex + 1);
const offsetY = startIndex * itemHeight;
// Throttled scroll handler
const throttledScrollHandler = useThrottle(
useCallback((event: Event) => {
const target = event.target as HTMLDivElement;
const newScrollTop = target.scrollTop;
const newScrollLeft = target.scrollLeft;
setScrollTop(newScrollTop);
setScrollLeft(newScrollLeft);
onScroll?.(newScrollLeft, newScrollTop);
}, [onScroll]),
16 // ~60fps
);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
container.addEventListener('scroll', throttledScrollHandler, { passive: true });
return () => {
container.removeEventListener('scroll', throttledScrollHandler);
};
}, [throttledScrollHandler]);
// Performance monitoring
useEffect(() => {
startMeasure('virtualScroll');
recordMetric('visibleTaskCount', visibleItems.length);
recordMetric('taskCount', items.length);
endMeasure('virtualScroll');
}, [visibleItems.length, items.length, startMeasure, endMeasure, recordMetric]);
const renderVisibleItems = () => {
return visibleItems.map((item, virtualIndex) => {
const actualIndex = startIndex + virtualIndex;
const itemStyle: React.CSSProperties = {
position: 'absolute',
top: horizontal ? 0 : actualIndex * itemHeight,
left: horizontal ? actualIndex * itemHeight : 0,
height: horizontal ? '100%' : itemHeight,
width: horizontal ? itemHeight : '100%',
transform: horizontal ? 'none' : `translateY(${offsetY}px)`,
};
return (
<div key={item.id || actualIndex} style={itemStyle}>
{children(item, actualIndex, itemStyle)}
</div>
);
});
};
return (
<div
ref={containerRef}
className={`virtual-scroll-container overflow-auto ${className}`}
style={{
height: containerHeight,
width: containerWidth || '100%',
position: 'relative',
...style,
}}
>
{/* Spacer to maintain scroll height */}
<div
className="virtual-scroll-spacer"
style={{
height: horizontal ? '100%' : totalHeight,
width: horizontal ? totalHeight : '100%',
position: 'relative',
pointerEvents: 'none',
}}
>
{/* Visible items container */}
<div
className="virtual-scroll-content"
style={{
position: 'absolute',
top: 0,
left: 0,
height: '100%',
width: '100%',
pointerEvents: 'auto',
}}
>
{renderVisibleItems()}
</div>
</div>
</div>
);
};
// Grid virtual scrolling component for both rows and columns
interface VirtualGridProps {
data: any[][];
rowHeight: number;
columnWidth: number | number[];
containerHeight: number;
containerWidth: number;
overscan?: number;
children: (item: any, rowIndex: number, colIndex: number, style: React.CSSProperties) => ReactNode;
onScroll?: (scrollLeft: number, scrollTop: number) => void;
className?: string;
}
export const VirtualGrid: React.FC<VirtualGridProps> = ({
data,
rowHeight,
columnWidth,
containerHeight,
containerWidth,
overscan = 3,
children,
onScroll,
className = '',
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const [scrollTop, setScrollTop] = useState(0);
const [scrollLeft, setScrollLeft] = useState(0);
const rowCount = data.length;
const colCount = data[0]?.length || 0;
// Calculate column positions for variable width columns
const columnWidths = Array.isArray(columnWidth) ? columnWidth : new Array(colCount).fill(columnWidth);
const columnPositions = columnWidths.reduce((acc, width, index) => {
acc[index] = index === 0 ? 0 : acc[index - 1] + columnWidths[index - 1];
return acc;
}, {} as Record<number, number>);
const totalWidth = columnWidths.reduce((sum, width) => sum + width, 0);
const totalHeight = rowCount * rowHeight;
// Calculate visible ranges
const startRowIndex = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
const endRowIndex = Math.min(rowCount - 1, Math.ceil((scrollTop + containerHeight) / rowHeight) + overscan);
const startColIndex = Math.max(0, findColumnIndex(scrollLeft) - overscan);
const endColIndex = Math.min(colCount - 1, findColumnIndex(scrollLeft + containerWidth) + overscan);
function findColumnIndex(position: number): number {
for (let i = 0; i < colCount; i++) {
if (columnPositions[i] <= position && position < columnPositions[i] + columnWidths[i]) {
return i;
}
}
return colCount - 1;
}
const throttledScrollHandler = useThrottle(
useCallback((event: Event) => {
const target = event.target as HTMLDivElement;
const newScrollTop = target.scrollTop;
const newScrollLeft = target.scrollLeft;
setScrollTop(newScrollTop);
setScrollLeft(newScrollLeft);
onScroll?.(newScrollLeft, newScrollTop);
}, [onScroll]),
16
);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
container.addEventListener('scroll', throttledScrollHandler, { passive: true });
return () => {
container.removeEventListener('scroll', throttledScrollHandler);
};
}, [throttledScrollHandler]);
const renderVisibleCells = () => {
const cells: ReactNode[] = [];
for (let rowIndex = startRowIndex; rowIndex <= endRowIndex; rowIndex++) {
for (let colIndex = startColIndex; colIndex <= endColIndex; colIndex++) {
const item = data[rowIndex]?.[colIndex];
if (!item) continue;
const cellStyle: React.CSSProperties = {
position: 'absolute',
top: rowIndex * rowHeight,
left: columnPositions[colIndex],
height: rowHeight,
width: columnWidths[colIndex],
};
cells.push(
<div key={`${rowIndex}-${colIndex}`} style={cellStyle}>
{children(item, rowIndex, colIndex, cellStyle)}
</div>
);
}
}
return cells;
};
return (
<div
ref={containerRef}
className={`virtual-grid overflow-auto ${className}`}
style={{
height: containerHeight,
width: containerWidth,
position: 'relative',
}}
>
<div
style={{
height: totalHeight,
width: totalWidth,
position: 'relative',
}}
>
{renderVisibleCells()}
</div>
</div>
);
};
// Timeline virtual scrolling component
interface VirtualTimelineProps {
startDate: Date;
endDate: Date;
dayWidth: number;
containerWidth: number;
containerHeight: number;
overscan?: number;
children: (date: Date, index: number, style: React.CSSProperties) => ReactNode;
onScroll?: (scrollLeft: number) => void;
className?: string;
}
export const VirtualTimeline: React.FC<VirtualTimelineProps> = ({
startDate,
endDate,
dayWidth,
containerWidth,
containerHeight,
overscan = 10,
children,
onScroll,
className = '',
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const [scrollLeft, setScrollLeft] = useState(0);
const totalDays = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
const totalWidth = totalDays * dayWidth;
const startDayIndex = Math.max(0, Math.floor(scrollLeft / dayWidth) - overscan);
const endDayIndex = Math.min(totalDays - 1, Math.ceil((scrollLeft + containerWidth) / dayWidth) + overscan);
const throttledScrollHandler = useThrottle(
useCallback((event: Event) => {
const target = event.target as HTMLDivElement;
const newScrollLeft = target.scrollLeft;
setScrollLeft(newScrollLeft);
onScroll?.(newScrollLeft);
}, [onScroll]),
16
);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
container.addEventListener('scroll', throttledScrollHandler, { passive: true });
return () => {
container.removeEventListener('scroll', throttledScrollHandler);
};
}, [throttledScrollHandler]);
const renderVisibleDays = () => {
const days: ReactNode[] = [];
for (let dayIndex = startDayIndex; dayIndex <= endDayIndex; dayIndex++) {
const date = new Date(startDate);
date.setDate(date.getDate() + dayIndex);
const dayStyle: React.CSSProperties = {
position: 'absolute',
left: dayIndex * dayWidth,
top: 0,
width: dayWidth,
height: '100%',
};
days.push(
<div key={dayIndex} style={dayStyle}>
{children(date, dayIndex, dayStyle)}
</div>
);
}
return days;
};
return (
<div
ref={containerRef}
className={`virtual-timeline overflow-x-auto ${className}`}
style={{
height: containerHeight,
width: containerWidth,
position: 'relative',
}}
>
<div
style={{
height: '100%',
width: totalWidth,
position: 'relative',
}}
>
{renderVisibleDays()}
</div>
</div>
);
};
export default VirtualScrollContainer;

View File

@@ -0,0 +1,17 @@
// Main Components
export { default as AdvancedGanttChart } from './AdvancedGanttChart';
export { default as AdvancedGanttDemo } from './AdvancedGanttDemo';
// Core Components
export { default as GanttGrid } from './GanttGrid';
export { default as DraggableTaskBar } from './DraggableTaskBar';
export { default as TimelineMarkers, holidayPresets, workingDayPresets } from './TimelineMarkers';
// Utility Components
export { default as VirtualScrollContainer, VirtualGrid, VirtualTimeline } from './VirtualScrollContainer';
// Types
export * from '../../types/advanced-gantt.types';
// Performance Utilities
export * from '../../utils/gantt-performance';

View File

@@ -19,7 +19,6 @@ import { useAuthService } from '@/hooks/useAuth';
import { statusApiService } from '@/api/taskAttributes/status/status.api.service';
import alertService from '@/services/alerts/alertService';
import logger from '@/utils/errorLogger';
import Skeleton from 'antd/es/skeleton/Skeleton';
import { checkTaskDependencyStatus } from '@/utils/check-task-dependency-status';
import { useTaskSocketHandlers } from '@/hooks/useTaskSocketHandlers';
@@ -148,11 +147,11 @@ const EnhancedKanbanBoardNativeDnD: React.FC<{ projectId: string }> = ({ project
const targetGroup = taskGroups.find(g => g.id === targetGroupId);
if (!sourceGroup || !targetGroup) return;
const taskIdx = sourceGroup.tasks.findIndex(t => t.id === draggedTaskId);
if (taskIdx === -1) return;
const movedTask = sourceGroup.tasks[taskIdx];
let didStatusChange = false;
if (groupBy === 'status' && movedTask.id) {
if (sourceGroup.id !== targetGroup.id) {
const canContinue = await checkTaskDependencyStatus(movedTask.id, targetGroupId);
@@ -163,6 +162,7 @@ const EnhancedKanbanBoardNativeDnD: React.FC<{ projectId: string }> = ({ project
);
return;
}
didStatusChange = true;
}
}
let insertIdx = hoveredTaskIdx;
@@ -259,6 +259,18 @@ const EnhancedKanbanBoardNativeDnD: React.FC<{ projectId: string }> = ({ project
team_id: teamId,
});
// Emit progress update if status changed
if (didStatusChange) {
socket.emit(
SocketEvents.TASK_STATUS_CHANGE.toString(),
JSON.stringify({
task_id: movedTask.id,
status_id: targetGroupId,
parent_task: movedTask.parent_task_id || null,
team_id: teamId,
})
);
}
}
setDraggedTaskId(null);

View File

@@ -15,6 +15,7 @@ import { SocketEvents } from '@/shared/socket-events';
import { getUserSession } from '@/utils/session-helper';
import { themeWiseColor } from '@/utils/themeWiseColor';
import { toggleTaskExpansion, fetchBoardSubTasks } from '@/features/enhanced-kanban/enhanced-kanban.slice';
import TaskProgressCircle from './TaskProgressCircle';
// Simple Portal component
const Portal: React.FC<{ children: React.ReactNode }> = ({ children }) => {
@@ -69,7 +70,6 @@ const TaskCard: React.FC<TaskCardProps> = memo(({
const d = selectedDate || new Date();
return new Date(d.getFullYear(), d.getMonth(), 1);
});
const [showSubtasks, setShowSubtasks] = useState(false);
useEffect(() => {
setSelectedDate(task.end_date ? new Date(task.end_date) : null);
@@ -202,7 +202,11 @@ const TaskCard: React.FC<TaskCardProps> = memo(({
return (
<>
<div className="enhanced-kanban-task-card" style={{ background, color, display: 'block' }} >
<div className="enhanced-kanban-task-card" style={{ background, color, display: 'block', position: 'relative' }} >
{/* Progress circle at top right */}
<div style={{ position: 'absolute', top: 6, right: 6, zIndex: 2 }}>
<TaskProgressCircle task={task} size={20} />
</div>
<div
draggable
onDragStart={e => onTaskDragStart(e, task.id!, groupId)}
@@ -450,7 +454,7 @@ const TaskCard: React.FC<TaskCardProps> = memo(({
style={{ backgroundColor: themeMode === 'dark' ? (sub.priority_color_dark || sub.priority_color || '#d9d9d9') : (sub.priority_color || '#d9d9d9') }}
></span>
) : null}
<span className="flex-1 truncate text-xs text-gray-800 dark:text-gray-100">{sub.name}</span>
<span className="flex-1 truncate text-xs text-gray-800 dark:text-gray-100" title={sub.name}>{sub.name}</span>
<span
className="task-due-date ml-2 text-[10px] text-gray-500 dark:text-gray-400"
>

View File

@@ -0,0 +1,52 @@
import { IProjectTask } from "@/types/project/projectTasksViewModel.types";
// Add a simple circular progress component
const TaskProgressCircle: React.FC<{ task: IProjectTask; size?: number }> = ({ task, size = 28 }) => {
const progress = typeof task.complete_ratio === 'number'
? task.complete_ratio
: (typeof task.progress === 'number' ? task.progress : 0);
const strokeWidth = 1.5;
const radius = (size - strokeWidth) / 2;
const circumference = 2 * Math.PI * radius;
const offset = circumference - (progress / 100) * circumference;
return (
<svg width={size} height={size} style={{ display: 'block' }}>
<circle
cx={size / 2}
cy={size / 2}
r={radius}
stroke={progress === 100 ? "#22c55e" : "#3b82f6"}
strokeWidth={strokeWidth}
fill="none"
strokeDasharray={circumference}
strokeDashoffset={offset}
strokeLinecap="round"
style={{ transition: 'stroke-dashoffset 0.3s' }}
/>
{progress === 100 ? (
// Green checkmark icon
<g>
<circle cx={size / 2} cy={size / 2} r={radius} fill="#22c55e" opacity="0.15" />
<svg x={(size/2)-(size*0.22)} y={(size/2)-(size*0.22)} width={size*0.44} height={size*0.44} viewBox="0 0 24 24">
<path d="M5 13l4 4L19 7" stroke="#22c55e" strokeWidth="2.2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</g>
) : progress > 0 && (
<text
x="50%"
y="50%"
textAnchor="middle"
dominantBaseline="central"
fontSize={size * 0.38}
fill="#3b82f6"
fontWeight="bold"
>
{Math.round(progress)}
</text>
)}
</svg>
);
};
export default TaskProgressCircle;

View File

@@ -1,101 +0,0 @@
.performance-monitor {
position: fixed;
top: 80px;
right: 16px;
width: 280px;
z-index: 1000;
background: var(--ant-color-bg-elevated);
border: 1px solid var(--ant-color-border);
box-shadow: 0 4px 12px var(--ant-color-shadow);
}
.performance-monitor-header {
display: flex;
justify-content: space-between;
align-items: center;
font-weight: 600;
color: var(--ant-color-text);
}
.performance-status {
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.performance-metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-bottom: 12px;
}
.performance-metrics .ant-statistic {
text-align: center;
}
.performance-metrics .ant-statistic-title {
font-size: 12px;
color: var(--ant-color-text-secondary);
margin-bottom: 4px;
}
.performance-metrics .ant-statistic-content {
font-size: 14px;
color: var(--ant-color-text);
}
.virtualization-status {
grid-column: 1 / -1;
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 0;
border-top: 1px solid var(--ant-color-border);
}
.status-label {
font-size: 12px;
color: var(--ant-color-text-secondary);
font-weight: 500;
}
.performance-tips {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--ant-color-border);
}
.performance-tips h4 {
font-size: 12px;
color: var(--ant-color-text);
margin-bottom: 8px;
font-weight: 600;
}
.performance-tips ul {
margin: 0;
padding-left: 16px;
}
.performance-tips li {
font-size: 11px;
color: var(--ant-color-text-secondary);
margin-bottom: 4px;
line-height: 1.4;
}
/* Responsive design */
@media (max-width: 768px) {
.performance-monitor {
position: static;
width: 100%;
margin-bottom: 16px;
}
.performance-metrics {
grid-template-columns: 1fr;
gap: 8px;
}
}

View File

@@ -1,108 +0,0 @@
import React from 'react';
import { Card, Statistic, Tooltip, Badge } from 'antd';
import { useSelector } from 'react-redux';
import { RootState } from '@/app/store';
import './PerformanceMonitor.css';
const PerformanceMonitor: React.FC = () => {
const { performanceMetrics } = useSelector((state: RootState) => state.enhancedKanbanReducer);
// Only show if there are tasks loaded
if (performanceMetrics.totalTasks === 0) {
return null;
}
const getPerformanceStatus = () => {
if (performanceMetrics.totalTasks > 1000) return 'critical';
if (performanceMetrics.totalTasks > 500) return 'warning';
if (performanceMetrics.totalTasks > 100) return 'good';
return 'excellent';
};
const getStatusColor = (status: string) => {
switch (status) {
case 'critical':
return 'red';
case 'warning':
return 'orange';
case 'good':
return 'blue';
case 'excellent':
return 'green';
default:
return 'default';
}
};
const status = getPerformanceStatus();
const statusColor = getStatusColor(status);
return (
<Card
size="small"
className="performance-monitor"
title={
<div className="performance-monitor-header">
<span>Performance Monitor</span>
<Badge
status={statusColor as any}
text={status.toUpperCase()}
className="performance-status"
/>
</div>
}
>
<div className="performance-metrics">
<Tooltip title="Total number of tasks across all groups">
<Statistic
title="Total Tasks"
value={performanceMetrics.totalTasks}
suffix="tasks"
valueStyle={{ fontSize: '16px' }}
/>
</Tooltip>
<Tooltip title="Largest group by number of tasks">
<Statistic
title="Largest Group"
value={performanceMetrics.largestGroupSize}
suffix="tasks"
valueStyle={{ fontSize: '16px' }}
/>
</Tooltip>
<Tooltip title="Average tasks per group">
<Statistic
title="Average Group"
value={Math.round(performanceMetrics.averageGroupSize)}
suffix="tasks"
valueStyle={{ fontSize: '16px' }}
/>
</Tooltip>
<Tooltip title="Virtualization is enabled for groups with more than 50 tasks">
<div className="virtualization-status">
<span className="status-label">Virtualization:</span>
<Badge
status={performanceMetrics.virtualizationEnabled ? 'success' : 'default'}
text={performanceMetrics.virtualizationEnabled ? 'Enabled' : 'Disabled'}
/>
</div>
</Tooltip>
</div>
{performanceMetrics.totalTasks > 500 && (
<div className="performance-tips">
<h4>Performance Tips:</h4>
<ul>
<li>Use filters to reduce the number of visible tasks</li>
<li>Consider grouping by different criteria</li>
<li>Virtualization is automatically enabled for large groups</li>
</ul>
</div>
)}
</Card>
);
};
export default React.memo(PerformanceMonitor);

View File

@@ -1,60 +0,0 @@
.virtualized-task-list {
background: transparent;
border-radius: 6px;
overflow: hidden;
}
.virtualized-task-row {
padding: 4px 0;
display: flex;
align-items: stretch;
}
.virtualized-empty-state {
display: flex;
align-items: center;
justify-content: center;
background: var(--ant-color-bg-container);
border-radius: 6px;
border: 2px dashed var(--ant-color-border);
}
.empty-message {
color: var(--ant-color-text-secondary);
font-size: 14px;
font-weight: 500;
}
/* Ensure virtualized list works well with drag and drop */
.virtualized-task-list .react-window__inner {
overflow: visible !important;
}
/* Performance optimizations */
.virtualized-task-list * {
will-change: transform;
}
/* Smooth scrolling */
.virtualized-task-list {
scroll-behavior: smooth;
}
/* Custom scrollbar for better UX */
.virtualized-task-list::-webkit-scrollbar {
width: 6px;
}
.virtualized-task-list::-webkit-scrollbar-track {
background: var(--ant-color-bg-container);
border-radius: 3px;
}
.virtualized-task-list::-webkit-scrollbar-thumb {
background: var(--ant-color-border);
border-radius: 3px;
}
.virtualized-task-list::-webkit-scrollbar-thumb:hover {
background: var(--ant-color-text-tertiary);
}

View File

@@ -1,94 +0,0 @@
import React, { useMemo, useCallback } from 'react';
import { FixedSizeList as List } from 'react-window';
import { IProjectTask } from '@/types/project/projectTasksViewModel.types';
import EnhancedKanbanTaskCard from './EnhancedKanbanTaskCard';
import './VirtualizedTaskList.css';
interface VirtualizedTaskListProps {
tasks: IProjectTask[];
height: number;
itemHeight?: number;
activeTaskId?: string | null;
overId?: string | null;
onTaskRender?: (task: IProjectTask, index: number) => void;
}
const VirtualizedTaskList: React.FC<VirtualizedTaskListProps> = ({
tasks,
height,
itemHeight = 80,
activeTaskId,
overId,
onTaskRender,
}) => {
// Memoize task data to prevent unnecessary re-renders
const taskData = useMemo(
() => ({
tasks,
activeTaskId,
overId,
onTaskRender,
}),
[tasks, activeTaskId, overId, onTaskRender]
);
// Row renderer for virtualized list
const Row = useCallback(
({ index, style }: { index: number; style: React.CSSProperties }) => {
const task = tasks[index];
if (!task) return null;
// Call onTaskRender callback if provided
onTaskRender?.(task, index);
return (
<EnhancedKanbanTaskCard
task={task}
isActive={task.id === activeTaskId}
isDropTarget={overId === task.id}
sectionId={task.status || 'default'}
/>
);
},
[tasks, activeTaskId, overId, onTaskRender]
);
// Memoize the list component to prevent unnecessary re-renders
const VirtualizedList = useMemo(
() => (
<List
height={height}
width="100%"
itemCount={tasks.length}
itemSize={itemHeight}
itemData={taskData}
overscanCount={10} // Increased overscan for smoother scrolling experience
className="virtualized-task-list"
>
{Row}
</List>
),
[height, tasks.length, itemHeight, taskData, Row]
);
if (tasks.length === 0) {
return (
<div className="virtualized-empty-state" style={{ height, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<div className="empty-message" style={{
padding: '32px 24px',
color: '#8c8c8c',
fontSize: '14px',
backgroundColor: '#fafafa',
borderRadius: '8px',
border: '1px solid #f0f0f0'
}}>
No tasks in this group
</div>
</div>
);
}
return VirtualizedList;
};
export default React.memo(VirtualizedTaskList);

View File

@@ -0,0 +1,406 @@
import React, { useState } from 'react';
import {
Modal,
Tabs,
Progress,
Tag,
List,
Avatar,
Badge,
Space,
Button,
Statistic,
Row,
Col,
Timeline,
Input,
Form,
DatePicker,
Select
} from 'antd';
import {
CalendarOutlined,
TeamOutlined,
CheckCircleOutlined,
ClockCircleOutlined,
FlagOutlined,
ExclamationCircleOutlined,
EditOutlined,
SaveOutlined,
CloseOutlined
} from '@ant-design/icons';
import { PhaseModalData, ProjectPhase, PhaseTask, PhaseMilestone } from '../../types/project-roadmap.types';
import { useAppSelector } from '../../hooks/useAppSelector';
import { themeWiseColor } from '../../utils/themeWiseColor';
import dayjs from 'dayjs';
const { TabPane } = Tabs;
const { TextArea } = Input;
interface PhaseModalProps {
visible: boolean;
phase: PhaseModalData | null;
onClose: () => void;
onUpdate?: (updates: Partial<ProjectPhase>) => void;
}
const PhaseModal: React.FC<PhaseModalProps> = ({
visible,
phase,
onClose,
onUpdate,
}) => {
const [isEditing, setIsEditing] = useState(false);
const [form] = Form.useForm();
// Theme support
const themeMode = useAppSelector(state => state.themeReducer.mode);
const isDarkMode = themeMode === 'dark';
if (!phase) return null;
const handleEdit = () => {
setIsEditing(true);
form.setFieldsValue({
name: phase.name,
description: phase.description,
startDate: dayjs(phase.startDate),
endDate: dayjs(phase.endDate),
status: phase.status,
});
};
const handleSave = async () => {
try {
const values = await form.validateFields();
const updates: Partial<ProjectPhase> = {
name: values.name,
description: values.description,
startDate: values.startDate.toDate(),
endDate: values.endDate.toDate(),
status: values.status,
};
onUpdate?.(updates);
setIsEditing(false);
} catch (error) {
console.error('Validation failed:', error);
}
};
const handleCancel = () => {
setIsEditing(false);
form.resetFields();
};
const getStatusColor = (status: string) => {
switch (status) {
case 'completed': return 'success';
case 'in-progress': return 'processing';
case 'on-hold': return 'warning';
default: return 'default';
}
};
const getPriorityColor = (priority: string) => {
switch (priority) {
case 'high': return 'red';
case 'medium': return 'orange';
case 'low': return 'green';
default: return 'default';
}
};
const getTaskStatusIcon = (status: string) => {
switch (status) {
case 'done': return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
case 'in-progress': return <ClockCircleOutlined style={{ color: '#1890ff' }} />;
default: return <ExclamationCircleOutlined style={{ color: '#d9d9d9' }} />;
}
};
return (
<Modal
title={
<div className="flex justify-between items-center">
<Space>
<Badge status={getStatusColor(phase.status)} />
{isEditing ? (
<Form.Item name="name" className="mb-0">
<Input className="dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100" />
</Form.Item>
) : (
<h4 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-0">
{phase.name}
</h4>
)}
</Space>
<Space>
{isEditing ? (
<>
<Button
type="primary"
icon={<SaveOutlined />}
onClick={handleSave}
size="small"
>
Save
</Button>
<Button
icon={<CloseOutlined />}
onClick={handleCancel}
size="small"
className="dark:border-gray-600 dark:text-gray-300"
>
Cancel
</Button>
</>
) : (
<Button
type="text"
icon={<EditOutlined />}
onClick={handleEdit}
size="small"
className="dark:text-gray-300 dark:hover:bg-gray-700"
>
Edit
</Button>
)}
</Space>
</div>
}
open={visible}
onCancel={onClose}
width={800}
footer={null}
className="dark:bg-gray-800"
>
<Form form={form} layout="vertical">
<div className="mb-4">
{isEditing ? (
<Form.Item name="description" label={<span className="text-gray-700 dark:text-gray-300">Description</span>}>
<TextArea
rows={2}
className="dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100"
/>
</Form.Item>
) : (
<p className="text-gray-600 dark:text-gray-400">{phase.description}</p>
)}
</div>
{/* Phase Statistics */}
<Row gutter={16} className="mb-6">
<Col span={6}>
<div className="bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg p-4">
<Statistic
title={<span className="text-gray-600 dark:text-gray-400">Progress</span>}
value={phase.progress}
suffix="%"
valueStyle={{ color: themeWiseColor('#1890ff', '#40a9ff', themeMode) }}
/>
<Progress
percent={phase.progress}
showInfo={false}
size="small"
strokeColor={themeWiseColor('#1890ff', '#40a9ff', themeMode)}
trailColor={themeWiseColor('#f0f0f0', '#4b5563', themeMode)}
/>
</div>
</Col>
<Col span={6}>
<div className="bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg p-4">
<Statistic
title={<span className="text-gray-600 dark:text-gray-400">Tasks</span>}
value={phase.completedTaskCount}
suffix={`/ ${phase.taskCount}`}
valueStyle={{ color: themeWiseColor('#52c41a', '#34d399', themeMode) }}
/>
</div>
</Col>
<Col span={6}>
<div className="bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg p-4">
<Statistic
title={<span className="text-gray-600 dark:text-gray-400">Milestones</span>}
value={phase.completedMilestoneCount}
suffix={`/ ${phase.milestoneCount}`}
valueStyle={{ color: themeWiseColor('#722ed1', '#9f7aea', themeMode) }}
/>
</div>
</Col>
<Col span={6}>
<div className="bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg p-4">
<Statistic
title={<span className="text-gray-600 dark:text-gray-400">Team</span>}
value={phase.teamMembers.length}
suffix="members"
valueStyle={{ color: themeWiseColor('#fa8c16', '#fbbf24', themeMode) }}
/>
</div>
</Col>
</Row>
{/* Timeline */}
<Row gutter={16} className="mb-6">
<Col span={12}>
{isEditing ? (
<Form.Item name="startDate" label={<span className="text-gray-700 dark:text-gray-300">Start Date</span>}>
<DatePicker className="w-full dark:bg-gray-700 dark:border-gray-600" />
</Form.Item>
) : (
<div className="bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg p-4">
<div className="flex items-center gap-2">
<CalendarOutlined className="text-gray-600 dark:text-gray-400" />
<span className="font-medium text-gray-900 dark:text-gray-100">Start:</span>
<span className="text-gray-600 dark:text-gray-400">{phase.startDate.toLocaleDateString()}</span>
</div>
</div>
)}
</Col>
<Col span={12}>
{isEditing ? (
<Form.Item name="endDate" label={<span className="text-gray-700 dark:text-gray-300">End Date</span>}>
<DatePicker className="w-full dark:bg-gray-700 dark:border-gray-600" />
</Form.Item>
) : (
<div className="bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg p-4">
<div className="flex items-center gap-2">
<CalendarOutlined className="text-gray-600 dark:text-gray-400" />
<span className="font-medium text-gray-900 dark:text-gray-100">End:</span>
<span className="text-gray-600 dark:text-gray-400">{phase.endDate.toLocaleDateString()}</span>
</div>
</div>
)}
</Col>
</Row>
{isEditing && (
<Row gutter={16} className="mb-6">
<Col span={12}>
<Form.Item name="status" label={<span className="text-gray-700 dark:text-gray-300">Status</span>}>
<Select className="dark:bg-gray-700 dark:border-gray-600">
<Select.Option value="not-started">Not Started</Select.Option>
<Select.Option value="in-progress">In Progress</Select.Option>
<Select.Option value="completed">Completed</Select.Option>
<Select.Option value="on-hold">On Hold</Select.Option>
</Select>
</Form.Item>
</Col>
</Row>
)}
<Tabs
defaultActiveKey="tasks"
className="dark:bg-gray-800"
tabBarStyle={{
borderBottom: `1px solid ${themeWiseColor('#f0f0f0', '#4b5563', themeMode)}`
}}
>
<TabPane tab={`Tasks (${phase.taskCount})`} key="tasks">
<List
dataSource={phase.tasks}
renderItem={(task: PhaseTask) => (
<List.Item>
<List.Item.Meta
avatar={getTaskStatusIcon(task.status)}
title={
<div className="flex justify-between items-center">
<Text strong>{task.name}</Text>
<Space>
<Tag color={getPriorityColor(task.priority)}>
{task.priority}
</Tag>
<Progress
percent={task.progress}
size="small"
style={{ width: 100 }}
/>
</Space>
</div>
}
description={
<div>
<Text type="secondary">{task.description}</Text>
<div className="mt-2 flex justify-between items-center">
<Space>
<CalendarOutlined />
<Text type="secondary">
{task.startDate.toLocaleDateString()} - {task.endDate.toLocaleDateString()}
</Text>
</Space>
{task.assigneeName && (
<Space>
<TeamOutlined />
<Text type="secondary">{task.assigneeName}</Text>
</Space>
)}
</div>
</div>
}
/>
</List.Item>
)}
/>
</TabPane>
<TabPane tab={`Milestones (${phase.milestoneCount})`} key="milestones">
<Timeline>
{phase.milestones.map((milestone: PhaseMilestone) => (
<Timeline.Item
key={milestone.id}
color={milestone.isCompleted ? 'green' : milestone.criticalPath ? 'red' : 'blue'}
dot={milestone.isCompleted ? <CheckCircleOutlined /> : <FlagOutlined />}
>
<div className="flex justify-between items-start">
<div>
<Text strong>{milestone.name}</Text>
{milestone.criticalPath && (
<Tag color="red" className="ml-2">Critical Path</Tag>
)}
{milestone.description && (
<div className="mt-1">
<Text type="secondary">{milestone.description}</Text>
</div>
)}
</div>
<div className="text-right">
<div>
<CalendarOutlined />
<span className="ml-1">{milestone.dueDate.toLocaleDateString()}</span>
</div>
<Badge
status={milestone.isCompleted ? 'success' : 'processing'}
text={milestone.isCompleted ? 'Completed' : 'Pending'}
/>
</div>
</div>
</Timeline.Item>
))}
</Timeline>
</TabPane>
<TabPane tab={`Team (${phase.teamMembers.length})`} key="team">
<List
dataSource={phase.teamMembers}
renderItem={(member: string) => (
<List.Item>
<List.Item.Meta
avatar={<Avatar>{member.charAt(0).toUpperCase()}</Avatar>}
title={member}
description={
<Text type="secondary">
{phase.tasks.filter(task => task.assigneeName === member).length} tasks assigned
</Text>
}
/>
</List.Item>
)}
/>
</TabPane>
</Tabs>
</Form>
</Modal>
);
};
export default PhaseModal;

View File

@@ -0,0 +1,333 @@
import React, { useState, useMemo } from 'react';
import { Gantt, Task, ViewMode } from 'gantt-task-react';
import { Button, Space, Badge } from 'antd';
import { CalendarOutlined, TeamOutlined, CheckCircleOutlined } from '@ant-design/icons';
import { ProjectPhase, ProjectRoadmap, GanttViewOptions, PhaseModalData } from '../../types/project-roadmap.types';
import PhaseModal from './PhaseModal';
import { useAppSelector } from '../../hooks/useAppSelector';
import { themeWiseColor } from '../../utils/themeWiseColor';
import 'gantt-task-react/dist/index.css';
import './gantt-theme.css';
interface ProjectRoadmapGanttProps {
roadmap: ProjectRoadmap;
viewOptions?: Partial<GanttViewOptions>;
onPhaseUpdate?: (phaseId: string, updates: Partial<ProjectPhase>) => void;
onTaskUpdate?: (phaseId: string, taskId: string, updates: any) => void;
}
const ProjectRoadmapGantt: React.FC<ProjectRoadmapGanttProps> = ({
roadmap,
viewOptions = {},
onPhaseUpdate,
onTaskUpdate,
}) => {
const [selectedPhase, setSelectedPhase] = useState<PhaseModalData | null>(null);
const [isModalVisible, setIsModalVisible] = useState(false);
const [viewMode, setViewMode] = useState<ViewMode>(ViewMode.Month);
// Theme support
const themeMode = useAppSelector(state => state.themeReducer.mode);
const isDarkMode = themeMode === 'dark';
const defaultViewOptions: GanttViewOptions = {
viewMode: 'month',
showTasks: true,
showMilestones: true,
groupByPhase: true,
...viewOptions,
};
// Theme-aware colors
const ganttColors = useMemo(() => {
return {
background: themeWiseColor('#ffffff', '#1f2937', themeMode),
surface: themeWiseColor('#f8f9fa', '#374151', themeMode),
border: themeWiseColor('#e5e7eb', '#4b5563', themeMode),
taskBar: themeWiseColor('#3b82f6', '#60a5fa', themeMode),
taskBarHover: themeWiseColor('#2563eb', '#93c5fd', themeMode),
progressBar: themeWiseColor('#10b981', '#34d399', themeMode),
milestone: themeWiseColor('#f59e0b', '#fbbf24', themeMode),
criticalPath: themeWiseColor('#ef4444', '#f87171', themeMode),
text: {
primary: themeWiseColor('#111827', '#f9fafb', themeMode),
secondary: themeWiseColor('#6b7280', '#d1d5db', themeMode),
},
grid: themeWiseColor('#f3f4f6', '#4b5563', themeMode),
today: themeWiseColor('rgba(59, 130, 246, 0.1)', 'rgba(96, 165, 250, 0.2)', themeMode),
};
}, [themeMode]);
// Convert phases to Gantt tasks
const ganttTasks = useMemo(() => {
const tasks: Task[] = [];
roadmap.phases.forEach((phase, phaseIndex) => {
// Add phase as main task with theme-aware colors
const phaseTask: Task = {
id: phase.id,
name: phase.name,
start: phase.startDate,
end: phase.endDate,
progress: phase.progress,
type: 'project',
styles: {
progressColor: themeWiseColor(phase.color, phase.color, themeMode),
progressSelectedColor: themeWiseColor(phase.color, phase.color, themeMode),
backgroundColor: themeWiseColor(`${phase.color}20`, `${phase.color}30`, themeMode),
},
};
tasks.push(phaseTask);
// Add phase tasks if enabled
if (defaultViewOptions.showTasks) {
phase.tasks.forEach((task) => {
const ganttTask: Task = {
id: task.id,
name: task.name,
start: task.startDate,
end: task.endDate,
progress: task.progress,
type: 'task',
project: phase.id,
dependencies: task.dependencies,
styles: {
progressColor: ganttColors.taskBar,
progressSelectedColor: ganttColors.taskBarHover,
backgroundColor: themeWiseColor('rgba(59, 130, 246, 0.1)', 'rgba(96, 165, 250, 0.2)', themeMode),
},
};
tasks.push(ganttTask);
});
}
// Add milestones if enabled
if (defaultViewOptions.showMilestones) {
phase.milestones.forEach((milestone) => {
const milestoneTask: Task = {
id: milestone.id,
name: milestone.name,
start: milestone.dueDate,
end: milestone.dueDate,
progress: milestone.isCompleted ? 100 : 0,
type: 'milestone',
project: phase.id,
styles: {
progressColor: milestone.criticalPath ? ganttColors.criticalPath : ganttColors.progressBar,
progressSelectedColor: milestone.criticalPath ? ganttColors.criticalPath : ganttColors.progressBar,
backgroundColor: milestone.criticalPath ?
themeWiseColor('rgba(239, 68, 68, 0.1)', 'rgba(248, 113, 113, 0.2)', themeMode) :
themeWiseColor('rgba(16, 185, 129, 0.1)', 'rgba(52, 211, 153, 0.2)', themeMode),
},
};
tasks.push(milestoneTask);
});
}
});
return tasks;
}, [roadmap.phases, defaultViewOptions, ganttColors, themeMode]);
const handlePhaseClick = (phase: ProjectPhase) => {
const taskCount = phase.tasks.length;
const completedTaskCount = phase.tasks.filter(task => task.status === 'done').length;
const milestoneCount = phase.milestones.length;
const completedMilestoneCount = phase.milestones.filter(m => m.isCompleted).length;
const teamMembers = [...new Set(phase.tasks.map(task => task.assigneeName).filter(Boolean))];
const phaseModalData: PhaseModalData = {
...phase,
taskCount,
completedTaskCount,
milestoneCount,
completedMilestoneCount,
teamMembers,
};
setSelectedPhase(phaseModalData);
setIsModalVisible(true);
};
const handleTaskClick = (task: Task) => {
// Find the phase this task belongs to
const phase = roadmap.phases.find(p =>
p.tasks.some(t => t.id === task.id) || p.milestones.some(m => m.id === task.id)
);
if (phase) {
handlePhaseClick(phase);
}
};
const handleDateChange = (task: Task) => {
const phase = roadmap.phases.find(p => p.id === task.id);
if (phase && onPhaseUpdate) {
onPhaseUpdate(phase.id, {
startDate: task.start,
endDate: task.end,
});
} else if (onTaskUpdate) {
const parentPhase = roadmap.phases.find(p =>
p.tasks.some(t => t.id === task.id)
);
if (parentPhase) {
onTaskUpdate(parentPhase.id, task.id, {
startDate: task.start,
endDate: task.end,
});
}
}
};
const handleProgressChange = (task: Task) => {
const phase = roadmap.phases.find(p => p.id === task.id);
if (phase && onPhaseUpdate) {
onPhaseUpdate(phase.id, { progress: task.progress });
} else if (onTaskUpdate) {
const parentPhase = roadmap.phases.find(p =>
p.tasks.some(t => t.id === task.id)
);
if (parentPhase) {
onTaskUpdate(parentPhase.id, task.id, { progress: task.progress });
}
}
};
const getStatusColor = (status: string) => {
switch (status) {
case 'completed': return '#52c41a';
case 'in-progress': return '#1890ff';
case 'on-hold': return '#faad14';
default: return '#d9d9d9';
}
};
const columnWidth = viewMode === ViewMode.Year ? 350 :
viewMode === ViewMode.Month ? 300 :
viewMode === ViewMode.Week ? 250 : 60;
return (
<div className="project-roadmap-gantt w-full">
{/* Header */}
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-sm mb-4">
<div className="p-6">
<div className="flex justify-between items-center mb-4">
<div>
<h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-2">
{roadmap.name}
</h3>
{roadmap.description && (
<p className="text-gray-600 dark:text-gray-400 mb-0">
{roadmap.description}
</p>
)}
</div>
<Space>
<Button
type={viewMode === ViewMode.Week ? 'primary' : 'default'}
onClick={() => setViewMode(ViewMode.Week)}
className="dark:border-gray-600 dark:text-gray-300"
>
Week
</Button>
<Button
type={viewMode === ViewMode.Month ? 'primary' : 'default'}
onClick={() => setViewMode(ViewMode.Month)}
className="dark:border-gray-600 dark:text-gray-300"
>
Month
</Button>
<Button
type={viewMode === ViewMode.Year ? 'primary' : 'default'}
onClick={() => setViewMode(ViewMode.Year)}
className="dark:border-gray-600 dark:text-gray-300"
>
Year
</Button>
</Space>
</div>
{/* Phase Overview */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
{roadmap.phases.map((phase) => (
<div
key={phase.id}
className="bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg p-4 cursor-pointer hover:shadow-md hover:bg-gray-100 dark:hover:bg-gray-600 transition-all duration-200"
onClick={() => handlePhaseClick(phase)}
>
<div className="flex items-center justify-between mb-3">
<Badge
color={getStatusColor(phase.status)}
text={
<span className="font-medium text-gray-900 dark:text-gray-100">
{phase.name}
</span>
}
/>
</div>
<div className="space-y-2 text-sm">
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<CalendarOutlined className="w-4 h-4" />
<span>{phase.startDate.toLocaleDateString()} - {phase.endDate.toLocaleDateString()}</span>
</div>
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<TeamOutlined className="w-4 h-4" />
<span>{phase.tasks.length} tasks</span>
</div>
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<CheckCircleOutlined className="w-4 h-4" />
<span>{phase.progress}% complete</span>
</div>
</div>
</div>
))}
</div>
</div>
</div>
{/* Gantt Chart */}
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-sm">
<div className="p-4">
<div className="w-full overflow-x-auto">
<div
className="gantt-container"
style={{
'--gantt-background': ganttColors.background,
'--gantt-grid': ganttColors.grid,
'--gantt-text': ganttColors.text.primary,
'--gantt-border': ganttColors.border,
} as React.CSSProperties}
>
<Gantt
tasks={ganttTasks}
viewMode={viewMode}
onDateChange={handleDateChange}
onProgressChange={handleProgressChange}
onDoubleClick={handleTaskClick}
listCellWidth=""
columnWidth={columnWidth}
todayColor={ganttColors.today}
projectProgressColor={ganttColors.progressBar}
projectBackgroundColor={themeWiseColor('rgba(82, 196, 26, 0.1)', 'rgba(52, 211, 153, 0.2)', themeMode)}
/>
</div>
</div>
</div>
</div>
{/* Phase Modal */}
<PhaseModal
visible={isModalVisible}
phase={selectedPhase}
onClose={() => setIsModalVisible(false)}
onUpdate={(updates) => {
if (selectedPhase && onPhaseUpdate) {
onPhaseUpdate(selectedPhase.id, updates);
}
}}
/>
</div>
);
};
export default ProjectRoadmapGantt;

View File

@@ -0,0 +1,112 @@
import React, { useState } from 'react';
import { Button, Space, message } from 'antd';
import ProjectRoadmapGantt from './ProjectRoadmapGantt';
import { sampleProjectRoadmap } from './sample-data';
import { ProjectPhase, ProjectRoadmap } from '../../types/project-roadmap.types';
import { useAppSelector } from '../../hooks/useAppSelector';
const RoadmapDemo: React.FC = () => {
const [roadmap, setRoadmap] = useState<ProjectRoadmap>(sampleProjectRoadmap);
const themeMode = useAppSelector(state => state.themeReducer.mode);
const handlePhaseUpdate = (phaseId: string, updates: Partial<ProjectPhase>) => {
setRoadmap(prevRoadmap => ({
...prevRoadmap,
phases: prevRoadmap.phases.map(phase =>
phase.id === phaseId
? { ...phase, ...updates }
: phase
)
}));
message.success('Phase updated successfully!');
};
const handleTaskUpdate = (phaseId: string, taskId: string, updates: any) => {
setRoadmap(prevRoadmap => ({
...prevRoadmap,
phases: prevRoadmap.phases.map(phase =>
phase.id === phaseId
? {
...phase,
tasks: phase.tasks.map(task =>
task.id === taskId
? { ...task, ...updates }
: task
)
}
: phase
)
}));
message.success('Task updated successfully!');
};
const resetToSampleData = () => {
setRoadmap(sampleProjectRoadmap);
message.info('Roadmap reset to sample data');
};
return (
<div className="roadmap-demo p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-sm mb-4">
<div className="p-6">
<div className="flex justify-between items-center">
<div>
<h2 className="text-2xl font-bold text-gray-900 dark:text-gray-100 mb-2">
Project Roadmap Gantt Chart Demo
</h2>
<p className="text-gray-600 dark:text-gray-400 mb-0">
Interactive Gantt chart showing project phases as milestones/epics.
Click on any phase card or Gantt bar to view detailed information in a modal.
</p>
</div>
<Space>
<Button
onClick={resetToSampleData}
className="dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700"
>
Reset to Sample Data
</Button>
</Space>
</div>
</div>
</div>
<ProjectRoadmapGantt
roadmap={roadmap}
viewOptions={{
viewMode: 'month',
showTasks: true,
showMilestones: true,
groupByPhase: true,
}}
onPhaseUpdate={handlePhaseUpdate}
onTaskUpdate={handleTaskUpdate}
/>
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-sm mt-4">
<div className="p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-3">
Features Demonstrated:
</h3>
<ul className="space-y-2 text-gray-700 dark:text-gray-300">
<li> <strong className="text-gray-900 dark:text-gray-100">Phase-based Grouping:</strong> Projects organized by phases (Planning, Development, Testing, Deployment)</li>
<li> <strong className="text-gray-900 dark:text-gray-100">Interactive Phase Cards:</strong> Click on phase cards for detailed view</li>
<li> <strong className="text-gray-900 dark:text-gray-100">Gantt Chart Visualization:</strong> Timeline view with tasks, milestones, and dependencies</li>
<li> <strong className="text-gray-900 dark:text-gray-100">Modal Details:</strong> Comprehensive phase information with tasks, milestones, and team members</li>
<li> <strong className="text-gray-900 dark:text-gray-100">Progress Tracking:</strong> Visual progress indicators and completion statistics</li>
<li> <strong className="text-gray-900 dark:text-gray-100">Multiple View Modes:</strong> Week, Month, and Year timeline views</li>
<li> <strong className="text-gray-900 dark:text-gray-100">Task Management:</strong> Task assignments, priorities, and status tracking</li>
<li> <strong className="text-gray-900 dark:text-gray-100">Milestone Tracking:</strong> Critical path milestones and completion status</li>
<li> <strong className="text-gray-900 dark:text-gray-100">Team Overview:</strong> Team member assignments and workload distribution</li>
<li> <strong className="text-gray-900 dark:text-gray-100">Editable Fields:</strong> In-modal editing for phase attributes (name, description, dates, status)</li>
<li> <strong className="text-gray-900 dark:text-gray-100">Theme Support:</strong> Automatic light/dark theme adaptation with consistent styling</li>
</ul>
</div>
</div>
</div>
);
};
export default RoadmapDemo;

View File

@@ -0,0 +1,221 @@
/* Custom Gantt Chart Theme Overrides */
/* Light theme styles */
.gantt-container {
font-family: inherit;
}
.gantt-container .gantt-header {
background-color: var(--gantt-background, #ffffff);
border-bottom: 1px solid var(--gantt-border, #e5e7eb);
color: var(--gantt-text, #111827);
}
.gantt-container .gantt-task-list-wrapper {
background-color: var(--gantt-background, #ffffff);
border-right: 1px solid var(--gantt-border, #e5e7eb);
}
.gantt-container .gantt-task-list-table {
background-color: var(--gantt-background, #ffffff);
}
.gantt-container .gantt-task-list-table-row {
color: var(--gantt-text, #111827);
border-bottom: 1px solid var(--gantt-grid, #f3f4f6);
}
.gantt-container .gantt-task-list-table-row:hover {
background-color: var(--gantt-grid, #f3f4f6);
}
.gantt-container .gantt-gantt {
background-color: var(--gantt-background, #ffffff);
}
.gantt-container .gantt-vertical-container {
background-color: var(--gantt-background, #ffffff);
}
.gantt-container .gantt-horizontal-container {
background-color: var(--gantt-background, #ffffff);
}
.gantt-container .gantt-calendar {
background-color: var(--gantt-background, #ffffff);
border-bottom: 1px solid var(--gantt-border, #e5e7eb);
}
.gantt-container .gantt-calendar-row {
color: var(--gantt-text, #111827);
background-color: var(--gantt-background, #ffffff);
border-bottom: 1px solid var(--gantt-grid, #f3f4f6);
}
.gantt-container .gantt-grid-body {
background-color: var(--gantt-background, #ffffff);
}
.gantt-container .gantt-grid-row {
border-bottom: 1px solid var(--gantt-grid, #f3f4f6);
}
.gantt-container .gantt-grid-row-line {
border-left: 1px solid var(--gantt-grid, #f3f4f6);
}
/* Dark theme overrides */
html.dark .gantt-container .gantt-header {
background-color: #1f2937;
border-bottom-color: #4b5563;
color: #f9fafb;
}
html.dark .gantt-container .gantt-task-list-wrapper {
background-color: #1f2937;
border-right-color: #4b5563;
}
html.dark .gantt-container .gantt-task-list-table {
background-color: #1f2937;
}
html.dark .gantt-container .gantt-task-list-table-row {
color: #f9fafb;
border-bottom-color: #4b5563;
}
html.dark .gantt-container .gantt-task-list-table-row:hover {
background-color: #374151;
}
html.dark .gantt-container .gantt-gantt {
background-color: #1f2937;
}
html.dark .gantt-container .gantt-vertical-container {
background-color: #1f2937;
}
html.dark .gantt-container .gantt-horizontal-container {
background-color: #1f2937;
}
html.dark .gantt-container .gantt-calendar {
background-color: #1f2937;
border-bottom-color: #4b5563;
}
html.dark .gantt-container .gantt-calendar-row {
color: #f9fafb;
background-color: #1f2937;
border-bottom-color: #4b5563;
}
html.dark .gantt-container .gantt-grid-body {
background-color: #1f2937;
}
html.dark .gantt-container .gantt-grid-row {
border-bottom-color: #4b5563;
}
html.dark .gantt-container .gantt-grid-row-line {
border-left-color: #4b5563;
}
/* Tooltip theming */
.gantt-container .gantt-tooltip {
background-color: var(--gantt-background, #ffffff);
border: 1px solid var(--gantt-border, #e5e7eb);
color: var(--gantt-text, #111827);
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
html.dark .gantt-container .gantt-tooltip {
background-color: #374151;
border-color: #4b5563;
color: #f9fafb;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3);
}
/* Task bar styling improvements */
.gantt-container .gantt-task-progress {
border-radius: 2px;
}
.gantt-container .gantt-task-background {
border-radius: 4px;
border: 1px solid var(--gantt-border, #e5e7eb);
}
html.dark .gantt-container .gantt-task-background {
border-color: #4b5563;
}
/* Milestone styling */
.gantt-container .gantt-milestone {
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1));
}
html.dark .gantt-container .gantt-milestone {
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3));
}
/* Selection and hover states */
.gantt-container .gantt-task:hover .gantt-task-background {
opacity: 0.9;
transform: translateY(-1px);
transition: all 0.2s ease;
}
.gantt-container .gantt-task-selected .gantt-task-background {
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
}
html.dark .gantt-container .gantt-task-selected .gantt-task-background {
box-shadow: 0 0 0 2px rgba(96, 165, 250, 0.3);
}
/* Responsive improvements */
@media (max-width: 768px) {
.gantt-container {
font-size: 14px;
}
.gantt-container .gantt-task-list-wrapper {
min-width: 200px;
}
}
/* Scrollbar theming */
.gantt-container ::-webkit-scrollbar {
width: 8px;
height: 8px;
}
.gantt-container ::-webkit-scrollbar-track {
background: var(--gantt-grid, #f3f4f6);
border-radius: 4px;
}
.gantt-container ::-webkit-scrollbar-thumb {
background: var(--gantt-border, #e5e7eb);
border-radius: 4px;
}
.gantt-container ::-webkit-scrollbar-thumb:hover {
background: #9ca3af;
}
html.dark .gantt-container ::-webkit-scrollbar-track {
background: #4b5563;
}
html.dark .gantt-container ::-webkit-scrollbar-thumb {
background: #6b7280;
}
html.dark .gantt-container ::-webkit-scrollbar-thumb:hover {
background: #9ca3af;
}

View File

@@ -0,0 +1,5 @@
export { default as ProjectRoadmapGantt } from './ProjectRoadmapGantt';
export { default as PhaseModal } from './PhaseModal';
export { default as RoadmapDemo } from './RoadmapDemo';
export { sampleProjectRoadmap } from './sample-data';
export * from '../../types/project-roadmap.types';

View File

@@ -0,0 +1,317 @@
import { ProjectRoadmap, ProjectPhase, PhaseTask, PhaseMilestone } from '../../types/project-roadmap.types';
// Sample tasks for Planning Phase
const planningTasks: PhaseTask[] = [
{
id: 'task-planning-1',
name: 'Project Requirements Analysis',
description: 'Gather and analyze project requirements from stakeholders',
startDate: new Date(2024, 11, 1), // December 1, 2024
endDate: new Date(2024, 11, 5),
progress: 100,
assigneeId: 'user-1',
assigneeName: 'Alice Johnson',
priority: 'high',
status: 'done',
},
{
id: 'task-planning-2',
name: 'Technical Architecture Design',
description: 'Design the technical architecture and system components',
startDate: new Date(2024, 11, 6),
endDate: new Date(2024, 11, 12),
progress: 75,
assigneeId: 'user-2',
assigneeName: 'Bob Smith',
priority: 'high',
status: 'in-progress',
},
{
id: 'task-planning-3',
name: 'Resource Allocation Planning',
description: 'Plan and allocate team resources for the project',
startDate: new Date(2024, 11, 8),
endDate: new Date(2024, 11, 15),
progress: 50,
assigneeId: 'user-3',
assigneeName: 'Carol Davis',
priority: 'medium',
status: 'in-progress',
dependencies: ['task-planning-1'],
}
];
// Sample milestones for Planning Phase
const planningMilestones: PhaseMilestone[] = [
{
id: 'milestone-planning-1',
name: 'Requirements Approved',
description: 'All project requirements have been reviewed and approved by stakeholders',
dueDate: new Date(2024, 11, 5),
isCompleted: true,
criticalPath: true,
},
{
id: 'milestone-planning-2',
name: 'Architecture Review Complete',
description: 'Technical architecture has been reviewed and approved',
dueDate: new Date(2024, 11, 15),
isCompleted: false,
criticalPath: true,
}
];
// Sample tasks for Development Phase
const developmentTasks: PhaseTask[] = [
{
id: 'task-dev-1',
name: 'Frontend Component Development',
description: 'Develop core frontend components using React',
startDate: new Date(2024, 11, 16),
endDate: new Date(2025, 0, 31), // January 31, 2025
progress: 30,
assigneeId: 'user-4',
assigneeName: 'David Wilson',
priority: 'high',
status: 'in-progress',
dependencies: ['task-planning-2'],
},
{
id: 'task-dev-2',
name: 'Backend API Development',
description: 'Develop REST APIs and database models',
startDate: new Date(2024, 11, 16),
endDate: new Date(2025, 0, 25),
progress: 45,
assigneeId: 'user-5',
assigneeName: 'Eva Brown',
priority: 'high',
status: 'in-progress',
dependencies: ['task-planning-2'],
},
{
id: 'task-dev-3',
name: 'Database Setup and Migration',
description: 'Set up production database and create migration scripts',
startDate: new Date(2024, 11, 20),
endDate: new Date(2025, 0, 15),
progress: 80,
assigneeId: 'user-6',
assigneeName: 'Frank Miller',
priority: 'medium',
status: 'in-progress',
}
];
// Sample milestones for Development Phase
const developmentMilestones: PhaseMilestone[] = [
{
id: 'milestone-dev-1',
name: 'Core Components Complete',
description: 'All core frontend components have been developed and tested',
dueDate: new Date(2025, 0, 20),
isCompleted: false,
criticalPath: false,
},
{
id: 'milestone-dev-2',
name: 'API Development Complete',
description: 'All backend APIs are developed and documented',
dueDate: new Date(2025, 0, 25),
isCompleted: false,
criticalPath: true,
}
];
// Sample tasks for Testing Phase
const testingTasks: PhaseTask[] = [
{
id: 'task-test-1',
name: 'Unit Testing Implementation',
description: 'Write and execute comprehensive unit tests',
startDate: new Date(2025, 1, 1), // February 1, 2025
endDate: new Date(2025, 1, 15),
progress: 0,
assigneeId: 'user-7',
assigneeName: 'Grace Lee',
priority: 'high',
status: 'todo',
dependencies: ['task-dev-1', 'task-dev-2'],
},
{
id: 'task-test-2',
name: 'Integration Testing',
description: 'Perform integration testing between frontend and backend',
startDate: new Date(2025, 1, 10),
endDate: new Date(2025, 1, 25),
progress: 0,
assigneeId: 'user-8',
assigneeName: 'Henry Clark',
priority: 'high',
status: 'todo',
dependencies: ['task-test-1'],
},
{
id: 'task-test-3',
name: 'User Acceptance Testing',
description: 'Conduct user acceptance testing with stakeholders',
startDate: new Date(2025, 1, 20),
endDate: new Date(2025, 2, 5), // March 5, 2025
progress: 0,
assigneeId: 'user-9',
assigneeName: 'Ivy Taylor',
priority: 'medium',
status: 'todo',
dependencies: ['task-test-2'],
}
];
// Sample milestones for Testing Phase
const testingMilestones: PhaseMilestone[] = [
{
id: 'milestone-test-1',
name: 'All Tests Passing',
description: 'All unit and integration tests are passing',
dueDate: new Date(2025, 1, 25),
isCompleted: false,
criticalPath: true,
},
{
id: 'milestone-test-2',
name: 'UAT Sign-off',
description: 'User acceptance testing completed and signed off',
dueDate: new Date(2025, 2, 5),
isCompleted: false,
criticalPath: true,
}
];
// Sample tasks for Deployment Phase
const deploymentTasks: PhaseTask[] = [
{
id: 'task-deploy-1',
name: 'Production Environment Setup',
description: 'Configure and set up production environment',
startDate: new Date(2025, 2, 6), // March 6, 2025
endDate: new Date(2025, 2, 12),
progress: 0,
assigneeId: 'user-10',
assigneeName: 'Jack Anderson',
priority: 'high',
status: 'todo',
dependencies: ['task-test-3'],
},
{
id: 'task-deploy-2',
name: 'Application Deployment',
description: 'Deploy application to production environment',
startDate: new Date(2025, 2, 13),
endDate: new Date(2025, 2, 15),
progress: 0,
assigneeId: 'user-11',
assigneeName: 'Kelly White',
priority: 'high',
status: 'todo',
dependencies: ['task-deploy-1'],
},
{
id: 'task-deploy-3',
name: 'Post-Deployment Monitoring',
description: 'Monitor application performance post-deployment',
startDate: new Date(2025, 2, 16),
endDate: new Date(2025, 2, 20),
progress: 0,
assigneeId: 'user-12',
assigneeName: 'Liam Garcia',
priority: 'medium',
status: 'todo',
dependencies: ['task-deploy-2'],
}
];
// Sample milestones for Deployment Phase
const deploymentMilestones: PhaseMilestone[] = [
{
id: 'milestone-deploy-1',
name: 'Production Go-Live',
description: 'Application is live in production environment',
dueDate: new Date(2025, 2, 15),
isCompleted: false,
criticalPath: true,
},
{
id: 'milestone-deploy-2',
name: 'Project Handover',
description: 'Project handed over to maintenance team',
dueDate: new Date(2025, 2, 20),
isCompleted: false,
criticalPath: false,
}
];
// Sample project phases
const samplePhases: ProjectPhase[] = [
{
id: 'phase-planning',
name: 'Planning & Analysis',
description: 'Initial project planning, requirements gathering, and technical analysis',
startDate: new Date(2024, 11, 1),
endDate: new Date(2024, 11, 15),
progress: 75,
color: '#1890ff',
status: 'in-progress',
tasks: planningTasks,
milestones: planningMilestones,
},
{
id: 'phase-development',
name: 'Development',
description: 'Core development of frontend, backend, and database components',
startDate: new Date(2024, 11, 16),
endDate: new Date(2025, 0, 31),
progress: 40,
color: '#52c41a',
status: 'in-progress',
tasks: developmentTasks,
milestones: developmentMilestones,
},
{
id: 'phase-testing',
name: 'Testing & QA',
description: 'Comprehensive testing including unit, integration, and user acceptance testing',
startDate: new Date(2025, 1, 1),
endDate: new Date(2025, 2, 5),
progress: 0,
color: '#faad14',
status: 'not-started',
tasks: testingTasks,
milestones: testingMilestones,
},
{
id: 'phase-deployment',
name: 'Deployment & Launch',
description: 'Production deployment and project launch activities',
startDate: new Date(2025, 2, 6),
endDate: new Date(2025, 2, 20),
progress: 0,
color: '#722ed1',
status: 'not-started',
tasks: deploymentTasks,
milestones: deploymentMilestones,
}
];
// Sample project roadmap
export const sampleProjectRoadmap: ProjectRoadmap = {
id: 'roadmap-sample-project',
projectId: 'project-web-platform',
name: 'Web Platform Development Roadmap',
description: 'Comprehensive roadmap for developing a new web-based platform with modern technologies and agile methodologies',
startDate: new Date(2024, 11, 1),
endDate: new Date(2025, 2, 20),
phases: samplePhases,
createdAt: new Date(2024, 10, 15),
updatedAt: new Date(2024, 11, 1),
};
export default sampleProjectRoadmap;

View File

@@ -1,6 +1,5 @@
import { useSocket } from '@/socket/socketContext';
import { ITaskPhase } from '@/types/tasks/taskPhase.types';
import { IProjectTask } from '@/types/project/projectTasksViewModel.types';
import { Select } from 'antd';
import { Form } from 'antd';
@@ -27,12 +26,6 @@ const TaskDrawerPhaseSelector = ({ phases, task }: TaskDrawerPhaseSelectorProps)
phase_id: value,
parent_task: task.parent_task_id || null,
});
// socket?.once(SocketEvents.TASK_PHASE_CHANGE.toString(), () => {
// if(list.getCurrentGroup().value === this.list.GROUP_BY_PHASE_VALUE && this.list.isSubtasksIncluded) {
// this.list.emitRefreshSubtasksIncluded();
// }
// });
};
return (
@@ -41,8 +34,11 @@ const TaskDrawerPhaseSelector = ({ phases, task }: TaskDrawerPhaseSelectorProps)
allowClear
placeholder="Select Phase"
options={phaseMenuItems}
style={{ width: 'fit-content' }}
dropdownStyle={{ width: 'fit-content' }}
styles={{
root: {
width: 'fit-content',
},
}}
onChange={handlePhaseChange}
/>
</Form.Item>

View File

@@ -7,3 +7,28 @@
outline: 1px solid #d9d9d9;
border-radius: 4px;
}
/* Task name display styles */
.task-name-display {
margin: 0;
padding: 2px 8px;
font-size: 16px;
cursor: pointer;
width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-height: 20px;
line-height: 1.4;
display: flex;
align-items: center;
}
.task-name-display:hover {
background-color: rgba(0, 0, 0, 0.02);
border-radius: 4px;
}
[data-theme='dark'] .task-name-display:hover {
background-color: rgba(255, 255, 255, 0.05);
}

View File

@@ -1,4 +1,4 @@
import { Button, Dropdown, Flex, Input, InputRef, MenuProps } from 'antd';
import { Button, Dropdown, Flex, Input, InputRef, MenuProps, Tooltip } from 'antd';
import React, { ChangeEvent, useEffect, useRef, useState } from 'react';
import { EllipsisOutlined } from '@ant-design/icons';
import { TFunction } from 'i18next';
@@ -21,12 +21,19 @@ import { deleteBoardTask } from '@/features/board/board-slice';
import { deleteTask as deleteKanbanTask, updateEnhancedKanbanSubtask } from '@/features/enhanced-kanban/enhanced-kanban.slice';
import useTabSearchParam from '@/hooks/useTabSearchParam';
import { ITaskViewModel } from '@/types/tasks/task.types';
import TaskHierarchyBreadcrumb from '../task-hierarchy-breadcrumb/task-hierarchy-breadcrumb';
type TaskDrawerHeaderProps = {
inputRef: React.RefObject<InputRef | null>;
t: TFunction;
};
// Utility function to truncate text
const truncateText = (text: string, maxLength: number = 50): string => {
if (!text || text.length <= maxLength) return text;
return `${text.substring(0, maxLength)}...`;
};
const TaskDrawerHeader = ({ inputRef, t }: TaskDrawerHeaderProps) => {
const dispatch = useAppDispatch();
const { socket, connected } = useSocket();
@@ -38,6 +45,9 @@ const TaskDrawerHeader = ({ inputRef, t }: TaskDrawerHeaderProps) => {
const [taskName, setTaskName] = useState<string>(taskFormViewModel?.task?.name ?? '');
const currentSession = useAuthService().getCurrentSession();
// Check if current task is a sub-task
const isSubTask = taskFormViewModel?.task?.is_sub_task || !!taskFormViewModel?.task?.parent_task_id;
useEffect(() => {
setTaskName(taskFormViewModel?.task?.name ?? '');
}, [taskFormViewModel?.task?.name]);
@@ -126,9 +136,17 @@ const TaskDrawerHeader = ({ inputRef, t }: TaskDrawerHeaderProps) => {
// No need for local socket listeners that could interfere with global handlers
};
const displayTaskName = taskName || t('taskHeader.taskNamePlaceholder');
const truncatedTaskName = truncateText(displayTaskName, 50);
const shouldShowTooltip = displayTaskName.length > 50;
return (
<Flex gap={12} align="center" style={{ marginBlockEnd: 6 }}>
<Flex style={{ position: 'relative', width: '100%' }}>
<div>
{/* Show breadcrumb for sub-tasks */}
{isSubTask && <TaskHierarchyBreadcrumb t={t} />}
<Flex gap={8} align="center" style={{ marginBlockEnd: 2 }}>
<Flex style={{ position: 'relative', width: '100%', alignItems: 'center' }}>
{isEditing ? (
<Input
ref={inputRef}
@@ -147,20 +165,14 @@ const TaskDrawerHeader = ({ inputRef, t }: TaskDrawerHeaderProps) => {
autoFocus
/>
) : (
<Tooltip title={shouldShowTooltip ? displayTaskName : ''} trigger="hover">
<p
onClick={() => setIsEditing(true)}
style={{
margin: 0,
padding: '4px 11px',
fontSize: '16px',
cursor: 'pointer',
wordWrap: 'break-word',
overflowWrap: 'break-word',
width: '100%',
}}
className="task-name-display"
>
{taskName || t('taskHeader.taskNamePlaceholder')}
{truncatedTaskName}
</p>
</Tooltip>
)}
</Flex>
@@ -174,6 +186,7 @@ const TaskDrawerHeader = ({ inputRef, t }: TaskDrawerHeaderProps) => {
<Button type="text" icon={<EllipsisOutlined />} />
</Dropdown>
</Flex>
</div>
);
};

View File

@@ -3,7 +3,7 @@ import Drawer from 'antd/es/drawer';
import { InputRef } from 'antd/es/input';
import { useTranslation } from 'react-i18next';
import { useEffect, useRef, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { PlusOutlined, CloseOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useAppSelector } from '@/hooks/useAppSelector';
import { useAppDispatch } from '@/hooks/useAppDispatch';
@@ -13,6 +13,7 @@ import {
setTaskFormViewModel,
setTaskSubscribers,
setTimeLogEditing,
fetchTask,
} from '@/features/task-drawer/task-drawer.slice';
import './task-drawer.css';
@@ -33,6 +34,7 @@ const TaskDrawer = () => {
const { showTaskDrawer, timeLogEditing } = useAppSelector(state => state.taskDrawerReducer);
const { taskFormViewModel, selectedTaskId } = useAppSelector(state => state.taskDrawerReducer);
const { projectId } = useAppSelector(state => state.projectReducer);
const taskNameInputRef = useRef<InputRef>(null);
const isClosingManually = useRef(false);
@@ -54,6 +56,17 @@ const TaskDrawer = () => {
dispatch(setTaskSubscribers([]));
};
const handleBackToParent = () => {
if (taskFormViewModel?.task?.parent_task_id && projectId) {
// Navigate to parent task
dispatch(setSelectedTaskId(taskFormViewModel.task.parent_task_id));
dispatch(fetchTask({
taskId: taskFormViewModel.task.parent_task_id,
projectId
}));
}
};
const handleOnClose = (
e?: React.MouseEvent<Element, MouseEvent> | React.KeyboardEvent<Element>
) => {
@@ -68,10 +81,8 @@ const TaskDrawer = () => {
if (isClickOutsideDrawer || !taskFormViewModel?.task?.is_sub_task) {
resetTaskState();
} else {
dispatch(setSelectedTaskId(null));
dispatch(setTaskFormViewModel({}));
dispatch(setTaskSubscribers([]));
dispatch(setSelectedTaskId(taskFormViewModel?.task?.parent_task_id || null));
// For sub-tasks, navigate to parent instead of closing
handleBackToParent();
}
// Reset the flag after a short delay
setTimeout(() => {
@@ -205,6 +216,17 @@ const TaskDrawer = () => {
};
};
// Check if current task is a sub-task
const isSubTask = taskFormViewModel?.task?.is_sub_task || !!taskFormViewModel?.task?.parent_task_id;
// Custom close icon based on whether it's a sub-task
const getCloseIcon = () => {
if (isSubTask) {
return <ArrowLeftOutlined />;
}
return <CloseOutlined />;
};
const drawerProps = {
open: showTaskDrawer,
onClose: handleOnClose,
@@ -215,6 +237,7 @@ const TaskDrawer = () => {
footer: renderFooter(),
bodyStyle: getBodyStyle(),
footerStyle: getFooterStyle(),
closeIcon: getCloseIcon(),
};
return (

View File

@@ -0,0 +1,88 @@
.task-hierarchy-breadcrumb {
margin-bottom: 4px;
}
.task-hierarchy-breadcrumb .ant-breadcrumb {
font-size: 14px;
line-height: 1;
}
.task-hierarchy-breadcrumb .ant-breadcrumb-link {
color: inherit;
}
.task-hierarchy-breadcrumb .ant-breadcrumb-separator {
color: #8c8c8c;
margin: 0 4px;
}
/* Dark mode styles */
[data-theme='dark'] .task-hierarchy-breadcrumb .ant-breadcrumb-separator {
color: #595959;
}
/* Back button styles */
.task-hierarchy-breadcrumb .ant-btn-link {
padding: 0;
height: auto;
font-size: 14px;
line-height: 1.3;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
display: flex;
align-items: center;
}
.task-hierarchy-breadcrumb .ant-btn-link .anticon {
margin-right: 0; /* Remove default margin */
}
.task-hierarchy-breadcrumb .ant-btn-link:hover {
color: #40a9ff;
}
[data-theme='dark'] .task-hierarchy-breadcrumb .ant-btn-link:hover {
color: #40a9ff;
}
/* Current task name styles */
.task-hierarchy-breadcrumb .current-task-name {
font-size: 14px;
color: #000000d9;
font-weight: 500;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
display: inline-block;
line-height: 1.3;
}
[data-theme='dark'] .task-hierarchy-breadcrumb .current-task-name {
color: #ffffffd9;
}
/* Breadcrumb item container */
.task-hierarchy-breadcrumb .ant-breadcrumb-item {
max-width: 220px;
overflow: hidden;
display: flex;
align-items: center;
}
/* Ensure breadcrumb items don't break the layout */
.task-hierarchy-breadcrumb .ant-breadcrumb ol {
display: flex;
flex-wrap: wrap;
align-items: center;
margin: 0;
padding: 0;
}
/* Better alignment for breadcrumb items */
.task-hierarchy-breadcrumb .ant-breadcrumb-item .ant-breadcrumb-link {
display: flex;
align-items: center;
}

View File

@@ -0,0 +1,189 @@
import React, { useState, useEffect } from 'react';
import { Breadcrumb, Button, Typography, Tooltip } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { useAppSelector } from '@/hooks/useAppSelector';
import { useAppDispatch } from '@/hooks/useAppDispatch';
import { fetchTask, setSelectedTaskId } from '@/features/task-drawer/task-drawer.slice';
import { tasksApiService } from '@/api/tasks/tasks.api.service';
import { TFunction } from 'i18next';
import './task-hierarchy-breadcrumb.css';
interface TaskHierarchyBreadcrumbProps {
t: TFunction;
onBackClick?: () => void;
}
interface TaskHierarchyItem {
id: string;
name: string;
parent_task_id?: string;
}
// Utility function to truncate text
const truncateText = (text: string, maxLength: number = 25): string => {
if (!text || text.length <= maxLength) return text;
return `${text.substring(0, maxLength)}...`;
};
const TaskHierarchyBreadcrumb: React.FC<TaskHierarchyBreadcrumbProps> = ({ t, onBackClick }) => {
const dispatch = useAppDispatch();
const { taskFormViewModel } = useAppSelector(state => state.taskDrawerReducer);
const { projectId } = useAppSelector(state => state.projectReducer);
const themeMode = useAppSelector(state => state.themeReducer.mode);
const [hierarchyPath, setHierarchyPath] = useState<TaskHierarchyItem[]>([]);
const [loading, setLoading] = useState(false);
const task = taskFormViewModel?.task;
const isSubTask = task?.is_sub_task || !!task?.parent_task_id;
// Recursively fetch the complete hierarchy path
const fetchHierarchyPath = async (currentTaskId: string): Promise<TaskHierarchyItem[]> => {
if (!projectId) return [];
const path: TaskHierarchyItem[] = [];
let taskId = currentTaskId;
// Traverse up the hierarchy until we reach the root
while (taskId) {
try {
const response = await tasksApiService.getFormViewModel(taskId, projectId);
if (response.done && response.body.task) {
const taskData = response.body.task;
path.unshift({
id: taskData.id,
name: taskData.name || '',
parent_task_id: taskData.parent_task_id || undefined
});
// Move to parent task
taskId = taskData.parent_task_id || '';
} else {
break;
}
} catch (error) {
console.error('Error fetching task in hierarchy:', error);
break;
}
}
return path;
};
// Fetch the complete hierarchy when component mounts or task changes
useEffect(() => {
const loadHierarchy = async () => {
if (!isSubTask || !task?.parent_task_id || !projectId) {
setHierarchyPath([]);
return;
}
setLoading(true);
try {
const path = await fetchHierarchyPath(task.parent_task_id);
setHierarchyPath(path);
} catch (error) {
console.error('Error loading task hierarchy:', error);
setHierarchyPath([]);
} finally {
setLoading(false);
}
};
loadHierarchy();
}, [task?.parent_task_id, projectId, isSubTask]);
const handleNavigateToTask = (taskId: string) => {
if (projectId) {
if (onBackClick) {
onBackClick();
}
// Navigate to the selected task
dispatch(setSelectedTaskId(taskId));
dispatch(fetchTask({ taskId, projectId }));
}
};
if (!isSubTask || hierarchyPath.length === 0) {
return null;
}
// Create breadcrumb items from the hierarchy path
const breadcrumbItems = [
// Add all parent tasks in the hierarchy
...hierarchyPath.map((hierarchyTask, index) => {
const truncatedName = truncateText(hierarchyTask.name, 25);
const shouldShowTooltip = hierarchyTask.name.length > 25;
return {
title: (
<Tooltip title={shouldShowTooltip ? hierarchyTask.name : ''} trigger="hover">
<Button
type="link"
icon={index === 0 ? <HomeOutlined /> : undefined}
onClick={() => handleNavigateToTask(hierarchyTask.id)}
style={{
padding: 0,
height: 'auto',
color: themeMode === 'dark' ? '#1890ff' : '#1890ff',
fontSize: '14px',
marginRight: '0px',
maxWidth: '200px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
display: 'flex',
alignItems: 'center',
gap: index === 0 ? '6px' : '0px', // Add gap between icon and text for root task
}}
>
{truncatedName}
</Button>
</Tooltip>
),
};
}),
// Add the current task as the last item (non-clickable)
{
title: (() => {
const currentTaskName = task?.name || t('taskHeader.currentTask', 'Current Task');
const truncatedCurrentName = truncateText(currentTaskName, 25);
const shouldShowCurrentTooltip = currentTaskName.length > 25;
return (
<Tooltip title={shouldShowCurrentTooltip ? currentTaskName : ''} trigger="hover">
<Typography.Text
className="current-task-name"
style={{
color: themeMode === 'dark' ? '#ffffffd9' : '#000000d9',
fontSize: '14px',
fontWeight: 500,
maxWidth: '200px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
display: 'inline-block',
}}
>
{truncatedCurrentName}
</Typography.Text>
</Tooltip>
);
})(),
},
];
return (
<div className="task-hierarchy-breadcrumb">
{loading ? (
<Typography.Text style={{ color: themeMode === 'dark' ? '#ffffffd9' : '#000000d9' }}>
{t('taskHeader.loadingHierarchy', 'Loading hierarchy...')}
</Typography.Text>
) : (
<Breadcrumb items={breadcrumbItems} />
)}
</div>
);
};
export default TaskHierarchyBreadcrumb;

View File

@@ -9,6 +9,7 @@ import {
KeyboardSensor,
TouchSensor,
closestCenter,
useDroppable,
} from '@dnd-kit/core';
import {
SortableContext,
@@ -67,6 +68,101 @@ import { AddCustomColumnButton, CustomColumnHeader } from './components/CustomCo
import TaskListSkeleton from './components/TaskListSkeleton';
import ConvertToSubtaskDrawer from '@/components/task-list-common/convert-to-subtask-drawer/convert-to-subtask-drawer';
// Empty Group Drop Zone Component
const EmptyGroupDropZone: React.FC<{
groupId: string;
visibleColumns: any[];
t: (key: string) => string;
}> = ({ groupId, visibleColumns, t }) => {
const { setNodeRef, isOver, active } = useDroppable({
id: `empty-group-${groupId}`,
data: {
type: 'group',
groupId: groupId,
isEmpty: true,
},
});
return (
<div
ref={setNodeRef}
className={`relative w-full transition-colors duration-200 ${
isOver && active ? 'bg-blue-50 dark:bg-blue-900/20' : ''
}`}
>
<div className="flex items-center min-w-max px-1 py-6">
{visibleColumns.map((column, index) => {
const emptyColumnStyle = {
width: column.width,
flexShrink: 0,
};
return (
<div
key={`empty-${column.id}`}
className="border-r border-gray-200 dark:border-gray-700"
style={emptyColumnStyle}
/>
);
})}
</div>
<div className="absolute left-4 top-1/2 transform -translate-y-1/2 flex items-center">
<div
className={`text-sm px-4 py-3 rounded-md border shadow-sm transition-colors duration-200 ${
isOver && active
? 'text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/30 border-blue-300 dark:border-blue-600'
: 'text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-700'
}`}
>
{isOver && active ? t('dropTaskHere') || 'Drop task here' : t('noTasksInGroup')}
</div>
</div>
{isOver && active && (
<div className="absolute inset-0 border-2 border-dashed border-blue-400 dark:border-blue-500 rounded-md pointer-events-none" />
)}
</div>
);
};
// Placeholder Drop Indicator Component
const PlaceholderDropIndicator: React.FC<{
isVisible: boolean;
visibleColumns: any[];
}> = ({ isVisible, visibleColumns }) => {
if (!isVisible) return null;
return (
<div
className="flex items-center min-w-max px-1 border-2 border-dashed border-blue-400 dark:border-blue-500 bg-blue-50 dark:bg-blue-900/20 rounded-md mx-1 my-1 transition-all duration-200 ease-in-out"
style={{ minWidth: 'max-content', height: '40px' }}
>
{visibleColumns.map((column, index) => {
const columnStyle = {
width: column.width,
flexShrink: 0,
};
return (
<div
key={`placeholder-${column.id}`}
className="flex items-center justify-center h-full"
style={columnStyle}
>
{/* Show "Drop task here" message in the title column */}
{column.id === 'title' && (
<div className="text-xs text-blue-600 dark:text-blue-400 font-medium opacity-75">
Drop task here
</div>
)}
{/* Show subtle placeholder content in other columns */}
{column.id !== 'title' && column.id !== 'dragHandle' && (
<div className="w-full h-4 mx-1 bg-white dark:bg-gray-700 rounded opacity-50" />
)}
</div>
);
})}
</div>
);
};
// Hooks and utilities
import { useTaskSocketHandlers } from '@/hooks/useTaskSocketHandlers';
import { useSocket } from '@/socket/socketContext';
@@ -127,7 +223,7 @@ const TaskListV2Section: React.FC = () => {
);
// Custom hooks
const { activeId, handleDragStart, handleDragOver, handleDragEnd } = useDragAndDrop(
const { activeId, overId, handleDragStart, handleDragOver, handleDragEnd } = useDragAndDrop(
allTasks,
groups
);
@@ -465,31 +561,11 @@ const TaskListV2Section: React.FC = () => {
projectId={urlProjectId || ''}
/>
{isGroupEmpty && !isGroupCollapsed && (
<div className="relative w-full">
<div className="flex items-center min-w-max px-1 py-6">
{visibleColumns.map((column, index) => {
const emptyColumnStyle = {
width: column.width,
flexShrink: 0,
...(column.id === 'labels' && column.width === 'auto'
? { minWidth: '200px', flexGrow: 1 }
: {}),
};
return (
<div
key={`empty-${column.id}`}
className="border-r border-gray-200 dark:border-gray-700"
style={emptyColumnStyle}
<EmptyGroupDropZone
groupId={group.id}
visibleColumns={visibleColumns}
t={t}
/>
);
})}
</div>
<div className="absolute left-4 top-1/2 transform -translate-y-1/2 flex items-center">
<div className="text-sm text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-900 px-4 py-3 rounded-md border border-gray-200 dark:border-gray-700 shadow-sm">
{t('noTasksInGroup')}
</div>
</div>
</div>
)}
</div>
);
@@ -546,12 +622,6 @@ const TaskListV2Section: React.FC = () => {
const columnStyle: ColumnStyle = {
width: column.width,
flexShrink: 0,
...(column.id === 'labels' && column.width === 'auto'
? {
minWidth: '200px',
flexGrow: 1,
}
: {}),
...((column as any).minWidth && { minWidth: (column as any).minWidth }),
...((column as any).maxWidth && { maxWidth: (column as any).maxWidth }),
};
@@ -687,7 +757,8 @@ const TaskListV2Section: React.FC = () => {
{renderGroup(groupIndex)}
{/* Group Tasks */}
{!collapsedGroups.has(group.id) &&
{!collapsedGroups.has(group.id) && (
group.tasks.length > 0 ? (
group.tasks.map((task, taskIndex) => {
const globalTaskIndex =
virtuosoGroups.slice(0, groupIndex).reduce((sum, g) => sum + g.count, 0) +
@@ -696,12 +767,41 @@ const TaskListV2Section: React.FC = () => {
// Check if this is the first actual task in the group (not AddTaskRow)
const isFirstTaskInGroup = taskIndex === 0 && !('isAddTaskRow' in task);
// Check if we should show drop indicators
const isTaskBeingDraggedOver = overId === task.id;
const isGroupBeingDraggedOver = overId === group.id;
const isFirstTaskInGroupBeingDraggedOver = isFirstTaskInGroup && isTaskBeingDraggedOver;
return (
<div key={task.id || `add-task-${group.id}-${taskIndex}`}>
{/* Placeholder drop indicator before first task in group */}
{isFirstTaskInGroupBeingDraggedOver && (
<PlaceholderDropIndicator isVisible={true} visibleColumns={visibleColumns} />
)}
{/* Placeholder drop indicator between tasks */}
{isTaskBeingDraggedOver && !isFirstTaskInGroup && (
<PlaceholderDropIndicator isVisible={true} visibleColumns={visibleColumns} />
)}
{renderTask(globalTaskIndex, isFirstTaskInGroup)}
{/* Placeholder drop indicator at end of group when dragging over group */}
{isGroupBeingDraggedOver && taskIndex === group.tasks.length - 1 && (
<PlaceholderDropIndicator isVisible={true} visibleColumns={visibleColumns} />
)}
</div>
);
})}
})
) : (
// Handle empty groups with placeholder drop indicator
overId === group.id && (
<div style={{ minWidth: 'max-content' }}>
<PlaceholderDropIndicator isVisible={true} visibleColumns={visibleColumns} />
</div>
)
)
)}
</div>
))}
</div>
@@ -710,12 +810,12 @@ const TaskListV2Section: React.FC = () => {
</div>
{/* Drag Overlay */}
<DragOverlay dropAnimation={null}>
<DragOverlay dropAnimation={{ duration: 200, easing: 'ease-in-out' }}>
{activeId ? (
<div className="bg-white dark:bg-gray-800 shadow-xl rounded-md border-2 border-blue-400 opacity-95">
<div className="bg-white dark:bg-gray-800 shadow-2xl rounded-lg border-2 border-blue-500 dark:border-blue-400 scale-105">
<div className="px-4 py-3">
<div className="flex items-center gap-3">
<HolderOutlined className="text-blue-500" />
<HolderOutlined className="text-blue-500 dark:text-blue-400" />
<div>
<div className="text-sm font-medium text-gray-900 dark:text-white">
{allTasks.find(task => task.id === activeId)?.name ||

View File

@@ -24,6 +24,7 @@ interface TaskRowProps {
isSubtask?: boolean;
isFirstInGroup?: boolean;
updateTaskCustomColumnValue?: (taskId: string, columnKey: string, value: string) => void;
depth?: number;
}
const TaskRow: React.FC<TaskRowProps> = memo(({
@@ -32,7 +33,8 @@ const TaskRow: React.FC<TaskRowProps> = memo(({
visibleColumns,
isSubtask = false,
isFirstInGroup = false,
updateTaskCustomColumnValue
updateTaskCustomColumnValue,
depth = 0
}) => {
// Get task data and selection state from Redux
const task = useAppSelector(state => selectTaskById(state, taskId));
@@ -107,13 +109,14 @@ const TaskRow: React.FC<TaskRowProps> = memo(({
handleTaskNameEdit,
attributes,
listeners,
depth,
});
// Memoize style object to prevent unnecessary re-renders
const style = useMemo(() => ({
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
opacity: isDragging ? 0 : 1, // Completely hide the original task while dragging
}), [transform, transition, isDragging]);
return (

View File

@@ -22,6 +22,8 @@ interface TaskRowWithSubtasksProps {
}>;
isFirstInGroup?: boolean;
updateTaskCustomColumnValue?: (taskId: string, columnKey: string, value: string) => void;
depth?: number; // Add depth prop to track nesting level
maxDepth?: number; // Add maxDepth prop to limit nesting
}
interface AddSubtaskRowProps {
@@ -32,11 +34,12 @@ interface AddSubtaskRowProps {
width: string;
isSticky?: boolean;
}>;
onSubtaskAdded: () => void; // Simplified - no rowId needed
rowId: string; // Unique identifier for this add subtask row
autoFocus?: boolean; // Whether this row should auto-focus on mount
isActive?: boolean; // Whether this row should show the input/button
onActivate?: () => void; // Simplified - no rowId needed
onSubtaskAdded: () => void;
rowId: string;
autoFocus?: boolean;
isActive?: boolean;
onActivate?: () => void;
depth?: number; // Add depth prop for proper indentation
}
const AddSubtaskRow: React.FC<AddSubtaskRowProps> = memo(({
@@ -47,25 +50,20 @@ const AddSubtaskRow: React.FC<AddSubtaskRowProps> = memo(({
rowId,
autoFocus = false,
isActive = true,
onActivate
onActivate,
depth = 0
}) => {
const [isAdding, setIsAdding] = useState(autoFocus);
const { t } = useTranslation('task-list-table');
const [isAdding, setIsAdding] = useState(false);
const [subtaskName, setSubtaskName] = useState('');
const inputRef = useRef<any>(null);
const { socket, connected } = useSocket();
const { t } = useTranslation('task-list-table');
const dispatch = useAppDispatch();
// Get session data for reporter_id and team_id
const { socket, connected } = useSocket();
const currentSession = useAuthService().getCurrentSession();
// Auto-focus when autoFocus prop is true
useEffect(() => {
if (autoFocus && inputRef.current) {
setIsAdding(true);
setTimeout(() => {
inputRef.current?.focus();
}, 100);
inputRef.current.focus();
}
}, [autoFocus]);
@@ -141,9 +139,13 @@ const AddSubtaskRow: React.FC<AddSubtaskRowProps> = memo(({
return (
<div className="flex items-center h-full" style={baseStyle}>
<div className="flex items-center w-full h-full">
{/* Match subtask indentation pattern - tighter spacing */}
<div className="w-4" />
{/* Match subtask indentation pattern - reduced spacing for level 1 */}
<div className="w-2" />
{/* Add additional indentation for deeper levels - increased spacing for level 2+ */}
{Array.from({ length: depth }).map((_, i) => (
<div key={i} className="w-6" />
))}
<div className="w-1" />
{isActive ? (
!isAdding ? (
@@ -188,7 +190,7 @@ const AddSubtaskRow: React.FC<AddSubtaskRowProps> = memo(({
default:
return <div style={baseStyle} />;
}
}, [isAdding, subtaskName, handleAddSubtask, handleCancel, handleBlur, handleKeyDown, t, isActive, onActivate]);
}, [isAdding, subtaskName, handleAddSubtask, handleCancel, handleBlur, handleKeyDown, t, isActive, onActivate, depth]);
return (
<div className="flex items-center min-w-max px-1 py-0.5 hover:bg-gray-50 dark:hover:bg-gray-800 min-h-[36px] border-b border-gray-200 dark:border-gray-700">
@@ -203,12 +205,42 @@ const AddSubtaskRow: React.FC<AddSubtaskRowProps> = memo(({
AddSubtaskRow.displayName = 'AddSubtaskRow';
// Helper function to get background color based on depth
const getSubtaskBackgroundColor = (depth: number) => {
switch (depth) {
case 1:
return 'bg-gray-50 dark:bg-gray-800/50';
case 2:
return 'bg-blue-50 dark:bg-blue-900/20';
case 3:
return 'bg-green-50 dark:bg-green-900/20';
default:
return 'bg-gray-50 dark:bg-gray-800/50';
}
};
// Helper function to get border color based on depth
const getBorderColor = (depth: number) => {
switch (depth) {
case 1:
return 'border-blue-200 dark:border-blue-700';
case 2:
return 'border-green-200 dark:border-green-700';
case 3:
return 'border-purple-200 dark:border-purple-700';
default:
return 'border-blue-200 dark:border-blue-700';
}
};
const TaskRowWithSubtasks: React.FC<TaskRowWithSubtasksProps> = memo(({
taskId,
projectId,
visibleColumns,
isFirstInGroup = false,
updateTaskCustomColumnValue
updateTaskCustomColumnValue,
depth = 0,
maxDepth = 3
}) => {
const task = useAppSelector(state => selectTaskById(state, taskId));
const isLoadingSubtasks = useAppSelector(state => selectSubtaskLoading(state, taskId));
@@ -223,6 +255,9 @@ const TaskRowWithSubtasks: React.FC<TaskRowWithSubtasksProps> = memo(({
return null;
}
// Don't render subtasks if we've reached the maximum depth
const canHaveSubtasks = depth < maxDepth;
return (
<>
{/* Main task row */}
@@ -232,10 +267,12 @@ const TaskRowWithSubtasks: React.FC<TaskRowWithSubtasksProps> = memo(({
visibleColumns={visibleColumns}
isFirstInGroup={isFirstInGroup}
updateTaskCustomColumnValue={updateTaskCustomColumnValue}
isSubtask={depth > 0}
depth={depth}
/>
{/* Subtasks and add subtask row when expanded */}
{task.show_sub_tasks && (
{canHaveSubtasks && task.show_sub_tasks && (
<>
{/* Show loading skeleton while fetching subtasks */}
{isLoadingSubtasks && (
@@ -244,22 +281,23 @@ const TaskRowWithSubtasks: React.FC<TaskRowWithSubtasksProps> = memo(({
</>
)}
{/* Render existing subtasks when not loading */}
{/* Render existing subtasks when not loading - RECURSIVELY */}
{!isLoadingSubtasks && task.sub_tasks?.map((subtask: Task) => (
<div key={subtask.id} className="bg-gray-50 dark:bg-gray-800/50 border-l-2 border-blue-200 dark:border-blue-700">
<TaskRow
<div key={subtask.id} className={`${getSubtaskBackgroundColor(depth + 1)} border-l-2 ${getBorderColor(depth + 1)}`}>
<TaskRowWithSubtasks
taskId={subtask.id}
projectId={projectId}
visibleColumns={visibleColumns}
isSubtask={true}
updateTaskCustomColumnValue={updateTaskCustomColumnValue}
depth={depth + 1}
maxDepth={maxDepth}
/>
</div>
))}
{/* Add subtask row - only show when not loading */}
{!isLoadingSubtasks && (
<div className="bg-gray-50 dark:bg-gray-800/50 border-l-2 border-blue-200 dark:border-blue-700">
<div className={`${getSubtaskBackgroundColor(depth + 1)} border-l-2 ${getBorderColor(depth + 1)}`}>
<AddSubtaskRow
parentTaskId={taskId}
projectId={projectId}
@@ -267,8 +305,9 @@ const TaskRowWithSubtasks: React.FC<TaskRowWithSubtasksProps> = memo(({
onSubtaskAdded={handleSubtaskAdded}
rowId={`add-subtask-${taskId}`}
autoFocus={false}
isActive={true} // Always show the add subtask row
onActivate={undefined} // Not needed anymore
isActive={true}
onActivate={undefined}
depth={depth + 1}
/>
</div>
)}

View File

@@ -252,10 +252,9 @@ interface LabelsColumnProps {
}
export const LabelsColumn: React.FC<LabelsColumnProps> = memo(({ width, task, labelsAdapter, isDarkMode, visibleColumns }) => {
const labelsColumn = visibleColumns.find(col => col.id === 'labels');
const labelsStyle = {
width,
...(labelsColumn?.width === 'auto' ? { minWidth: '200px', flexGrow: 1 } : {})
flexShrink: 0
};
return (

View File

@@ -24,6 +24,7 @@ interface TitleColumnProps {
onEditTaskName: (editing: boolean) => void;
onTaskNameChange: (name: string) => void;
onTaskNameSave: () => void;
depth?: number;
}
export const TitleColumn: React.FC<TitleColumnProps> = memo(({
@@ -36,7 +37,8 @@ export const TitleColumn: React.FC<TitleColumnProps> = memo(({
taskName,
onEditTaskName,
onTaskNameChange,
onTaskNameSave
onTaskNameSave,
depth = 0
}) => {
const dispatch = useAppDispatch();
const { socket, connected } = useSocket();
@@ -150,11 +152,16 @@ export const TitleColumn: React.FC<TitleColumnProps> = memo(({
/* Normal layout when not editing */
<>
<div className="flex items-center flex-1 min-w-0">
{/* Indentation for subtasks - tighter spacing */}
{isSubtask && <div className="w-4 flex-shrink-0" />}
{/* Indentation for subtasks - reduced spacing for level 1 */}
{isSubtask && <div className="w-2 flex-shrink-0" />}
{/* Expand/Collapse button - only show for parent tasks */}
{!isSubtask && (
{/* Additional indentation for deeper levels - increased spacing for level 2+ */}
{Array.from({ length: depth }).map((_, i) => (
<div key={i} className="w-6 flex-shrink-0" />
))}
{/* Expand/Collapse button - show for any task that can have sub-tasks */}
{depth < 2 && ( // Only show if not at maximum depth (can still have children)
<button
onClick={handleToggleExpansion}
className={`flex h-4 w-4 items-center justify-center rounded-sm text-xs mr-1 hover:border hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 hover:scale-110 transition-all duration-300 ease-out flex-shrink-0 ${
@@ -175,8 +182,8 @@ export const TitleColumn: React.FC<TitleColumnProps> = memo(({
</button>
)}
{/* Additional indentation for subtasks after the expand button space */}
{isSubtask && <div className="w-2 flex-shrink-0" />}
{/* Additional indentation for subtasks after the expand button space - reduced for level 1 */}
{isSubtask && <div className="w-1 flex-shrink-0" />}
<div className="flex items-center gap-2 flex-1 min-w-0">
{/* Task name with dynamic width */}
@@ -202,8 +209,8 @@ export const TitleColumn: React.FC<TitleColumnProps> = memo(({
{/* Indicators container - flex-shrink-0 to prevent compression */}
<div className="flex items-center gap-1 flex-shrink-0">
{/* Subtask count indicator - only show if count > 0 */}
{!isSubtask && task.sub_tasks_count != null && task.sub_tasks_count > 0 && (
{/* Subtask count indicator - show for any task that can have sub-tasks */}
{depth < 2 && task.sub_tasks_count != null && task.sub_tasks_count > 0 && (
<Tooltip title={t(`indicators.tooltips.subtasks${task.sub_tasks_count === 1 ? '' : '_plural'}`, { count: task.sub_tasks_count })}>
<div className="flex items-center gap-1 px-1.5 py-0.5 bg-blue-50 dark:bg-blue-900/20 rounded text-xs">
<span className="text-blue-600 dark:text-blue-400 font-medium">

View File

@@ -19,10 +19,10 @@ export const BASE_COLUMNS = [
{ id: 'title', label: 'taskColumn', width: '470px', isSticky: true, key: COLUMN_KEYS.NAME },
{ id: 'description', label: 'descriptionColumn', width: '260px', key: COLUMN_KEYS.DESCRIPTION },
{ id: 'progress', label: 'progressColumn', width: '120px', key: COLUMN_KEYS.PROGRESS },
{ id: 'assignees', label: 'assigneesColumn', width: '150px', key: COLUMN_KEYS.ASSIGNEES },
{ id: 'labels', label: 'labelsColumn', width: 'auto', key: COLUMN_KEYS.LABELS },
{ id: 'phase', label: 'phaseColumn', width: '120px', key: COLUMN_KEYS.PHASE },
{ id: 'status', label: 'statusColumn', width: '120px', key: COLUMN_KEYS.STATUS },
{ id: 'assignees', label: 'assigneesColumn', width: '150px', key: COLUMN_KEYS.ASSIGNEES },
{ id: 'labels', label: 'labelsColumn', width: '250px', key: COLUMN_KEYS.LABELS },
{ id: 'phase', label: 'phaseColumn', width: '120px', key: COLUMN_KEYS.PHASE },
{ id: 'priority', label: 'priorityColumn', width: '120px', key: COLUMN_KEYS.PRIORITY },
{ id: 'timeTracking', label: 'timeTrackingColumn', width: '120px', key: COLUMN_KEYS.TIME_TRACKING },
{ id: 'estimation', label: 'estimationColumn', width: '120px', key: COLUMN_KEYS.ESTIMATION },

View File

@@ -1,12 +1,142 @@
import { useState, useCallback } from 'react';
import { DragEndEvent, DragOverEvent, DragStartEvent } from '@dnd-kit/core';
import { useAppDispatch } from '@/hooks/useAppDispatch';
import { reorderTasksInGroup, moveTaskBetweenGroups } from '@/features/task-management/task-management.slice';
import { Task, TaskGroup } from '@/types/task-management.types';
import { useAppSelector } from '@/hooks/useAppSelector';
import { reorderTasksInGroup } from '@/features/task-management/task-management.slice';
import { selectCurrentGrouping } from '@/features/task-management/grouping.slice';
import { Task, TaskGroup, getSortOrderField } from '@/types/task-management.types';
import { useSocket } from '@/socket/socketContext';
import { SocketEvents } from '@/shared/socket-events';
import { useParams } from 'react-router-dom';
import { useAuthService } from '@/hooks/useAuth';
import logger from '@/utils/errorLogger';
export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
const dispatch = useAppDispatch();
const { socket, connected } = useSocket();
const { projectId } = useParams();
const currentGrouping = useAppSelector(selectCurrentGrouping);
const currentSession = useAuthService().getCurrentSession();
const [activeId, setActiveId] = useState<string | null>(null);
const [overId, setOverId] = useState<string | null>(null);
// Helper function to emit socket event for persistence
const emitTaskSortChange = useCallback(
(taskId: string, sourceGroup: TaskGroup, targetGroup: TaskGroup, insertIndex: number) => {
if (!socket || !connected || !projectId) {
logger.warning('Socket not connected or missing project ID');
return;
}
const task = allTasks.find(t => t.id === taskId);
if (!task) {
logger.error('Task not found for socket emission:', taskId);
return;
}
// Get team_id from current session
const teamId = currentSession?.team_id || '';
// Use new bulk update approach - recalculate ALL task orders to prevent duplicates
const taskUpdates: any[] = [];
// Create a copy of all groups and perform the move operation
const updatedGroups = groups.map(group => ({
...group,
taskIds: [...group.taskIds]
}));
// Find the source and target groups in our copy
const sourceGroupCopy = updatedGroups.find(g => g.id === sourceGroup.id)!;
const targetGroupCopy = updatedGroups.find(g => g.id === targetGroup.id)!;
if (sourceGroup.id === targetGroup.id) {
// Same group - reorder within the group
const sourceIndex = sourceGroupCopy.taskIds.indexOf(taskId);
// Remove task from old position
sourceGroupCopy.taskIds.splice(sourceIndex, 1);
// Insert at new position
sourceGroupCopy.taskIds.splice(insertIndex, 0, taskId);
} else {
// Different groups - move task between groups
// Remove from source group
const sourceIndex = sourceGroupCopy.taskIds.indexOf(taskId);
sourceGroupCopy.taskIds.splice(sourceIndex, 1);
// Add to target group
targetGroupCopy.taskIds.splice(insertIndex, 0, taskId);
}
// Now assign sequential sort orders to ALL tasks across ALL groups
let currentSortOrder = 0;
updatedGroups.forEach(group => {
group.taskIds.forEach(id => {
const update: any = {
task_id: id,
sort_order: currentSortOrder
};
// Add group-specific fields for the moved task if it changed groups
if (id === taskId && sourceGroup.id !== targetGroup.id) {
if (currentGrouping === 'status') {
update.status_id = targetGroup.id;
} else if (currentGrouping === 'priority') {
update.priority_id = targetGroup.id;
} else if (currentGrouping === 'phase') {
update.phase_id = targetGroup.id;
}
}
taskUpdates.push(update);
currentSortOrder++;
});
});
const socketData = {
project_id: projectId,
group_by: currentGrouping || 'status',
task_updates: taskUpdates,
from_group: sourceGroup.id,
to_group: targetGroup.id,
task: {
id: task.id,
project_id: projectId,
status: task.status || '',
priority: task.priority || '',
},
team_id: teamId,
};
socket.emit(SocketEvents.TASK_SORT_ORDER_CHANGE.toString(), socketData);
// Also emit the specific grouping field change event for the moved task
if (sourceGroup.id !== targetGroup.id) {
if (currentGrouping === 'phase') {
// Emit phase change event
socket.emit(SocketEvents.TASK_PHASE_CHANGE.toString(), {
task_id: taskId,
phase_id: targetGroup.id,
parent_task: task.parent_task_id || null,
});
} else if (currentGrouping === 'priority') {
// Emit priority change event
socket.emit(SocketEvents.TASK_PRIORITY_CHANGE.toString(), JSON.stringify({
task_id: taskId,
priority_id: targetGroup.id,
team_id: teamId,
}));
} else if (currentGrouping === 'status') {
// Emit status change event
socket.emit(SocketEvents.TASK_STATUS_CHANGE.toString(), JSON.stringify({
task_id: taskId,
status_id: targetGroup.id,
team_id: teamId,
}));
}
}
},
[socket, connected, projectId, allTasks, groups, currentGrouping, currentSession]
);
const handleDragStart = useCallback((event: DragStartEvent) => {
setActiveId(event.active.id as string);
@@ -16,11 +146,17 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
(event: DragOverEvent) => {
const { active, over } = event;
if (!over) return;
if (!over) {
setOverId(null);
return;
}
const activeId = active.id;
const overId = over.id;
// Set the overId for drop indicators
setOverId(overId as string);
// Find the active task and the item being dragged over
const activeTask = allTasks.find(task => task.id === activeId);
if (!activeTask) return;
@@ -38,15 +174,6 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
}
if (!activeGroup || !targetGroup) return;
// If dragging to a different group, we need to handle cross-group movement
if (activeGroup.id !== targetGroup.id) {
console.log('Cross-group drag detected:', {
activeTask: activeTask.id,
fromGroup: activeGroup.id,
toGroup: targetGroup.id,
});
}
},
[allTasks, groups]
);
@@ -55,6 +182,7 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
(event: DragEndEvent) => {
const { active, over } = event;
setActiveId(null);
setOverId(null);
if (!over || active.id === over.id) {
return;
@@ -66,22 +194,27 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
// Find the active task
const activeTask = allTasks.find(task => task.id === activeId);
if (!activeTask) {
console.error('Active task not found:', activeId);
logger.error('Active task not found:', activeId);
return;
}
// Find the groups
const activeGroup = groups.find(group => group.taskIds.includes(activeTask.id));
if (!activeGroup) {
console.error('Could not find active group for task:', activeId);
logger.error('Could not find active group for task:', activeId);
return;
}
// Check if we're dropping on a task or a group
// Check if we're dropping on a task, group, or empty group
const overTask = allTasks.find(task => task.id === overId);
const overGroup = groups.find(group => group.id === overId);
let targetGroup = overGroup;
// Check if dropping on empty group drop zone
const isEmptyGroupDrop = typeof overId === 'string' && overId.startsWith('empty-group-');
const emptyGroupId = isEmptyGroupDrop ? overId.replace('empty-group-', '') : null;
const emptyGroup = emptyGroupId ? groups.find(group => group.id === emptyGroupId) : null;
let targetGroup = overGroup || emptyGroup;
let insertIndex = 0;
if (overTask) {
@@ -94,27 +227,20 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
// Dropping on a group (at the end)
targetGroup = overGroup;
insertIndex = targetGroup.taskIds.length;
} else if (emptyGroup) {
// Dropping on an empty group
targetGroup = emptyGroup;
insertIndex = 0; // First position in empty group
}
if (!targetGroup) {
console.error('Could not find target group');
logger.error('Could not find target group');
return;
}
const isCrossGroup = activeGroup.id !== targetGroup.id;
const activeIndex = activeGroup.taskIds.indexOf(activeTask.id);
console.log('Drag operation:', {
activeId,
overId,
activeTask: activeTask.name || activeTask.title,
activeGroup: activeGroup.id,
targetGroup: targetGroup.id,
activeIndex,
insertIndex,
isCrossGroup,
});
if (isCrossGroup) {
// Moving task between groups
console.log('Moving task between groups:', {
@@ -124,16 +250,8 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
newPosition: insertIndex,
});
// Move task to the target group
dispatch(
moveTaskBetweenGroups({
taskId: activeId as string,
sourceGroupId: activeGroup.id,
targetGroupId: targetGroup.id,
})
);
// Reorder task within target group at drop position
// reorderTasksInGroup handles both same-group and cross-group moves
// No need for separate moveTaskBetweenGroups call
dispatch(
reorderTasksInGroup({
sourceTaskId: activeId as string,
@@ -142,15 +260,10 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
destinationGroupId: targetGroup.id,
})
);
} else {
// Reordering within the same group
console.log('Reordering task within same group:', {
task: activeTask.name || activeTask.title,
group: activeGroup.title,
from: activeIndex,
to: insertIndex,
});
// Emit socket event for persistence
emitTaskSortChange(activeId as string, activeGroup, targetGroup, insertIndex);
} else {
if (activeIndex !== insertIndex) {
// Reorder task within same group at drop position
dispatch(
@@ -161,14 +274,18 @@ export const useDragAndDrop = (allTasks: Task[], groups: TaskGroup[]) => {
destinationGroupId: activeGroup.id,
})
);
// Emit socket event for persistence
emitTaskSortChange(activeId as string, activeGroup, targetGroup, insertIndex);
}
}
},
[allTasks, groups, dispatch]
[allTasks, groups, dispatch, emitTaskSortChange]
);
return {
activeId,
overId,
handleDragStart,
handleDragOver,
handleDragEnd,

View File

@@ -58,6 +58,9 @@ interface UseTaskRowColumnsProps {
// Drag and drop
attributes: any;
listeners: any;
// Depth for nested subtasks
depth?: number;
}
export const useTaskRowColumns = ({
@@ -84,6 +87,7 @@ export const useTaskRowColumns = ({
handleTaskNameEdit,
attributes,
listeners,
depth = 0,
}: UseTaskRowColumnsProps) => {
const renderColumn = useCallback((columnId: string, width: string, isSticky?: boolean, index?: number) => {
@@ -128,6 +132,7 @@ export const useTaskRowColumns = ({
onEditTaskName={setEditTaskName}
onTaskNameChange={setTaskName}
onTaskNameSave={handleTaskNameSave}
depth={depth}
/>
);

View File

@@ -7,7 +7,7 @@ import {
EntityId,
createSelector,
} from '@reduxjs/toolkit';
import { Task, TaskManagementState, TaskGroup, TaskGrouping } from '@/types/task-management.types';
import { Task, TaskManagementState, TaskGroup, TaskGrouping, getSortOrderField } from '@/types/task-management.types';
import { ITaskListColumn } from '@/types/tasks/taskList.types';
import { RootState } from '@/app/store';
import {
@@ -661,11 +661,11 @@ const taskManagementSlice = createSlice({
newTasks.splice(newTasks.indexOf(destinationTaskId), 0, removed);
group.taskIds = newTasks;
// Update order for affected tasks. Assuming simple reordering affects order.
// This might need more sophisticated logic based on how `order` is used.
// Update order for affected tasks using the appropriate sort field
const sortField = getSortOrderField(state.grouping?.id);
newTasks.forEach((id, index) => {
if (newEntities[id]) {
newEntities[id] = { ...newEntities[id], order: index };
newEntities[id] = { ...newEntities[id], [sortField]: index };
}
});
}
@@ -686,49 +686,16 @@ const taskManagementSlice = createSlice({
destinationGroup.taskIds.push(sourceTaskId); // Add to end if destination task not found
}
// Update task's grouping field to reflect new group (e.g., status, priority, phase)
// This assumes the group ID directly corresponds to the task's field value
if (sourceTask) {
let updatedTask = { ...sourceTask };
switch (state.grouping?.id) {
case IGroupBy.STATUS:
updatedTask.status = destinationGroup.id;
break;
case IGroupBy.PRIORITY:
updatedTask.priority = destinationGroup.id;
break;
case IGroupBy.PHASE:
// Handle unmapped group specially
if (destinationGroup.id === 'Unmapped' || destinationGroup.title === 'Unmapped') {
updatedTask.phase = ''; // Clear phase for unmapped group
} else {
updatedTask.phase = destinationGroup.id;
}
break;
case IGroupBy.MEMBERS:
// If moving to a member group, ensure task is assigned to that member
// This assumes the group ID is the member ID
if (!updatedTask.assignees) {
updatedTask.assignees = [];
}
if (!updatedTask.assignees.includes(destinationGroup.id)) {
updatedTask.assignees.push(destinationGroup.id);
}
// If moving from a member group, and the task is no longer in any member group,
// consider removing the assignment (more complex logic might be needed here)
break;
default:
break;
}
newEntities[sourceTaskId] = updatedTask;
}
// Do NOT update the task's grouping field (priority, phase, status) here.
// This will be handled by the socket event handler after backend confirmation.
// Update order for affected tasks in both groups if necessary
// Update order for affected tasks in both groups using the appropriate sort field
const sortField = getSortOrderField(state.grouping?.id);
sourceGroup.taskIds.forEach((id, index) => {
if (newEntities[id]) newEntities[id] = { ...newEntities[id], order: index };
if (newEntities[id]) newEntities[id] = { ...newEntities[id], [sortField]: index };
});
destinationGroup.taskIds.forEach((id, index) => {
if (newEntities[id]) newEntities[id] = { ...newEntities[id], order: index };
if (newEntities[id]) newEntities[id] = { ...newEntities[id], [sortField]: index };
});
}
}
@@ -958,8 +925,26 @@ const taskManagementSlice = createSlice({
.addCase(fetchTasksV3.fulfilled, (state, action) => {
state.loading = false;
const { allTasks, groups, grouping } = action.payload;
tasksAdapter.setAll(state as EntityState<Task, string>, allTasks || []); // Ensure allTasks is an array
state.ids = (allTasks || []).map(task => task.id); // Also update ids
// Preserve existing timer state from old tasks before replacing
const oldTasks = state.entities;
const tasksWithTimers = (allTasks || []).map(task => {
const oldTask = oldTasks[task.id];
if (oldTask?.timeTracking?.activeTimer) {
// Preserve the timer state from the old task
return {
...task,
timeTracking: {
...task.timeTracking,
activeTimer: oldTask.timeTracking.activeTimer
}
};
}
return task;
});
tasksAdapter.setAll(state as EntityState<Task, string>, tasksWithTimers); // Ensure allTasks is an array
state.ids = tasksWithTimers.map(task => task.id); // Also update ids
state.groups = groups;
state.grouping = grouping;
})
@@ -1010,7 +995,7 @@ const taskManagementSlice = createSlice({
order: subtask.sort_order || subtask.order || 0,
parent_task_id: parentTaskId,
is_sub_task: true,
sub_tasks_count: 0,
sub_tasks_count: subtask.sub_tasks_count || 0, // Use actual count from backend
show_sub_tasks: false,
}));

View File

@@ -14,10 +14,10 @@ const DEFAULT_FIELDS: TaskListField[] = [
{ key: 'KEY', label: 'Key', visible: false, order: 1 },
{ key: 'DESCRIPTION', label: 'Description', visible: false, order: 2 },
{ key: 'PROGRESS', label: 'Progress', visible: true, order: 3 },
{ key: 'ASSIGNEES', label: 'Assignees', visible: true, order: 4 },
{ key: 'LABELS', label: 'Labels', visible: true, order: 5 },
{ key: 'PHASE', label: 'Phase', visible: true, order: 6 },
{ key: 'STATUS', label: 'Status', visible: true, order: 7 },
{ key: 'STATUS', label: 'Status', visible: true, order: 4 },
{ key: 'ASSIGNEES', label: 'Assignees', visible: true, order: 5 },
{ key: 'LABELS', label: 'Labels', visible: true, order: 6 },
{ key: 'PHASE', label: 'Phase', visible: true, order: 7 },
{ key: 'PRIORITY', label: 'Priority', visible: true, order: 8 },
{ key: 'TIME_TRACKING', label: 'Time Tracking', visible: true, order: 9 },
{ key: 'ESTIMATION', label: 'Estimation', visible: false, order: 10 },

View File

@@ -33,6 +33,7 @@ import {
updateTaskDescription,
updateSubTasks,
updateTaskProgress,
updateTaskTimeTracking,
} from '@/features/tasks/tasks.slice';
import {
addTask,
@@ -936,6 +937,8 @@ export const useTaskSocketHandlers = () => {
const { task_id, start_time } = typeof data === 'string' ? JSON.parse(data) : data;
if (!task_id) return;
const timerTimestamp = start_time ? (typeof start_time === 'number' ? start_time : parseInt(start_time)) : Date.now();
// Update the task-management slice to include timer state
const currentTask = store.getState().taskManagement.entities[task_id];
if (currentTask) {
@@ -943,13 +946,16 @@ export const useTaskSocketHandlers = () => {
...currentTask,
timeTracking: {
...currentTask.timeTracking,
activeTimer: start_time ? (typeof start_time === 'number' ? start_time : parseInt(start_time)) : Date.now(),
activeTimer: timerTimestamp,
},
updatedAt: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
dispatch(updateTask(updatedTask));
}
// Also update the tasks slice activeTimers to keep both slices in sync
dispatch(updateTaskTimeTracking({ taskId: task_id, timeTracking: timerTimestamp }));
} catch (error) {
logger.error('Error handling timer start event:', error);
}
@@ -975,11 +981,79 @@ export const useTaskSocketHandlers = () => {
};
dispatch(updateTask(updatedTask));
}
// Also update the tasks slice activeTimers to keep both slices in sync
dispatch(updateTaskTimeTracking({ taskId: task_id, timeTracking: null }));
} catch (error) {
logger.error('Error handling timer stop event:', error);
}
}, [dispatch]);
// Handler for task sort order change events
const handleTaskSortOrderChange = useCallback((data: any[]) => {
try {
if (!Array.isArray(data) || data.length === 0) return;
// DEBUG: Log the data received from the backend
console.log('[TASK_SORT_ORDER_CHANGE] Received data:', data);
// Get canonical lists from Redux
const state = store.getState();
const priorityList = state.priorityReducer?.priorities || [];
const phaseList = state.phaseReducer?.phaseList || [];
const statusList = state.taskStatusReducer?.status || [];
// The backend sends an array of tasks with updated sort orders and possibly grouping fields
data.forEach((taskData: any) => {
const currentTask = state.taskManagement.entities[taskData.id];
if (currentTask) {
let updatedTask: Task = {
...currentTask,
order: taskData.sort_order || taskData.current_sort_order || currentTask.order,
updatedAt: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
// Update grouping fields if present
if (typeof taskData.priority_id !== 'undefined') {
const found = priorityList.find(p => p.id === taskData.priority_id);
if (found) {
updatedTask.priority = found.name;
// updatedTask.priority_id = found.id; // Only if Task type has priority_id
} else {
updatedTask.priority = taskData.priority_id || '';
// updatedTask.priority_id = taskData.priority_id;
}
}
if (typeof taskData.phase_id !== 'undefined') {
const found = phaseList.find(p => p.id === taskData.phase_id);
if (found) {
updatedTask.phase = found.name;
// updatedTask.phase_id = found.id; // Only if Task type has phase_id
} else {
updatedTask.phase = taskData.phase_id || '';
// updatedTask.phase_id = taskData.phase_id;
}
}
if (typeof taskData.status_id !== 'undefined') {
const found = statusList.find(s => s.id === taskData.status_id);
if (found) {
updatedTask.status = found.name;
// updatedTask.status_id = found.id; // Only if Task type has status_id
} else {
updatedTask.status = taskData.status_id || '';
// updatedTask.status_id = taskData.status_id;
}
}
dispatch(updateTask(updatedTask));
}
});
} catch (error) {
logger.error('Error handling task sort order change event:', error);
}
}, [dispatch]);
// Register socket event listeners
useEffect(() => {
if (!socket) return;
@@ -1013,6 +1087,7 @@ export const useTaskSocketHandlers = () => {
{ event: SocketEvents.TASK_CUSTOM_COLUMN_UPDATE.toString(), handler: handleCustomColumnUpdate },
{ event: SocketEvents.TASK_TIMER_START.toString(), handler: handleTimerStart },
{ event: SocketEvents.TASK_TIMER_STOP.toString(), handler: handleTimerStop },
{ event: SocketEvents.TASK_SORT_ORDER_CHANGE.toString(), handler: handleTaskSortOrderChange },
];
@@ -1047,6 +1122,7 @@ export const useTaskSocketHandlers = () => {
handleCustomColumnUpdate,
handleTimerStart,
handleTimerStop,
handleTaskSortOrderChange,
]);
};

View File

@@ -50,7 +50,11 @@ export const useTaskTimer = (taskId: string, initialStartTime: number | null) =>
// Timer management effect
useEffect(() => {
if (started && localStarted && reduxStartTime) {
if (started && reduxStartTime) {
// Sync local state with Redux state
if (!localStarted) {
setLocalStarted(true);
}
clearTimerInterval();
timerTick();
intervalRef.current = setInterval(timerTick, 1000);

View File

@@ -0,0 +1,79 @@
import { useEffect, useRef } from 'react';
import { useAppDispatch } from '@/hooks/useAppDispatch';
import { updateTaskTimeTracking } from '@/features/tasks/tasks.slice';
import { updateTask } from '@/features/task-management/task-management.slice';
import { taskTimeLogsApiService } from '@/api/tasks/task-time-logs.api.service';
import { store } from '@/app/store';
import { Task } from '@/types/task-management.types';
import logger from '@/utils/errorLogger';
import moment from 'moment';
export const useTimerInitialization = () => {
const dispatch = useAppDispatch();
const hasInitialized = useRef(false);
useEffect(() => {
const initializeTimers = async () => {
// Prevent duplicate initialization
if (hasInitialized.current) {
return;
}
try {
hasInitialized.current = true;
// Fetch running timers from backend
const response = await taskTimeLogsApiService.getRunningTimers();
if (response && response.done && Array.isArray(response.body)) {
const runningTimers = response.body;
// Update Redux state for each running timer
runningTimers.forEach(timer => {
if (timer.task_id && timer.start_time) {
try {
// Convert start_time to timestamp
const startTime = moment(timer.start_time);
if (startTime.isValid()) {
const timestamp = startTime.valueOf();
// Update the tasks slice activeTimers
dispatch(updateTaskTimeTracking({
taskId: timer.task_id,
timeTracking: timestamp
}));
// Update the task-management slice if the task exists
const currentTask = store.getState().taskManagement.entities[timer.task_id];
if (currentTask) {
const updatedTask: Task = {
...currentTask,
timeTracking: {
...currentTask.timeTracking,
activeTimer: timestamp,
},
updatedAt: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
dispatch(updateTask(updatedTask));
}
}
} catch (error) {
logger.error(`Error initializing timer for task ${timer.task_id}:`, error);
}
}
});
if (runningTimers.length > 0) {
logger.info(`Initialized ${runningTimers.length} running timers from backend`);
}
}
} catch (error) {
logger.error('Error initializing timers from backend:', error);
}
};
// Initialize timers when the hook mounts
initializeTimers();
}, [dispatch]);
};

View File

@@ -0,0 +1,8 @@
import React from 'react';
import { AdvancedGanttDemo } from '../components/advanced-gantt';
const GanttDemoPage: React.FC = () => {
return <AdvancedGanttDemo />;
};
export default GanttDemoPage;

View File

@@ -1,5 +1,5 @@
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { Space, Steps, Button, Typography } from 'antd/es';
@@ -26,6 +26,7 @@ import { validateEmail } from '@/utils/validateEmail';
import { sanitizeInput } from '@/utils/sanitizeInput';
import logo from '@/assets/images/worklenz-light-mode.png';
import logoDark from '@/assets/images/worklenz-dark-mode.png';
import { useAppDispatch } from '@/hooks/useAppDispatch';
import './account-setup.css';
import { IAccountSetupRequest } from '@/types/project-templates/project-templates.types';
@@ -34,7 +35,7 @@ import { profileSettingsApiService } from '@/api/settings/profile/profile-settin
const { Title } = Typography;
const AccountSetup: React.FC = () => {
const dispatch = useDispatch();
const dispatch = useAppDispatch();
const { t } = useTranslation('account-setup');
useDocumentTitle(t('setupYourAccount', 'Account Setup'));
const navigate = useNavigate();
@@ -52,8 +53,7 @@ const AccountSetup: React.FC = () => {
trackMixpanelEvent(evt_account_setup_visit);
const verifyAuthStatus = async () => {
try {
const response = (await dispatch(verifyAuthentication()).unwrap())
.payload as IAuthorizeResponse;
const response = await dispatch(verifyAuthentication()).unwrap() as IAuthorizeResponse;
if (response?.authenticated) {
setSession(response.user);
dispatch(setUser(response.user));
@@ -163,6 +163,18 @@ const AccountSetup: React.FC = () => {
const res = await profileSettingsApiService.setupAccount(model);
if (res.done && res.body.id) {
trackMixpanelEvent(skip ? evt_account_setup_skip_invite : evt_account_setup_complete);
// Refresh user session to update setup_completed status
try {
const authResponse = await dispatch(verifyAuthentication()).unwrap() as IAuthorizeResponse;
if (authResponse?.authenticated && authResponse?.user) {
setSession(authResponse.user);
dispatch(setUser(authResponse.user));
}
} catch (error) {
logger.error('Failed to refresh user session after setup completion', error);
}
navigate(`/worklenz/projects/${res.body.id}?tab=tasks-list&pinned_tab=tasks-list`);
}
} catch (error) {

View File

@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { useAuthService } from '@/hooks/useAuth';
import { useMediaQuery } from 'react-responsive';
import { authApiService } from '@/api/auth/auth.api.service';
import CacheCleanup from '@/utils/cache-cleanup';
const LoggingOutPage = () => {
const navigate = useNavigate();
@@ -14,14 +15,30 @@ const LoggingOutPage = () => {
useEffect(() => {
const logout = async () => {
try {
// Clear local session
await auth.signOut();
// Call backend logout
await authApiService.logout();
// Clear all caches using the utility
await CacheCleanup.clearAllCaches();
// Force a hard reload to ensure fresh state
setTimeout(() => {
window.location.href = '/';
}, 1500);
CacheCleanup.forceReload('/auth/login');
}, 1000);
} catch (error) {
console.error('Logout error:', error);
// Fallback: force reload to login page
CacheCleanup.forceReload('/auth/login');
}
};
void logout();
}, [auth, navigate]);
}, [auth]);
const cardStyles = {
width: '100%',

View File

@@ -0,0 +1,63 @@
import React, { useMemo } from 'react';
import { useParams } from 'react-router-dom';
import { AdvancedGanttChart } from '../../components/advanced-gantt';
import { useAppSelector } from '../../hooks/useAppSelector';
import { GanttTask } from '../../types/advanced-gantt.types';
const ProjectGanttView: React.FC = () => {
const { projectId } = useParams<{ projectId: string }>();
// Get tasks from your Redux store (adjust based on your actual state structure)
const tasks = useAppSelector(state => state.tasksReducer?.tasks || []);
// Transform your tasks to GanttTask format
const ganttTasks = useMemo((): GanttTask[] => {
return tasks.map(task => ({
id: task.id,
name: task.name,
startDate: task.start_date ? new Date(task.start_date) : new Date(),
endDate: task.end_date ? new Date(task.end_date) : new Date(),
progress: task.progress || 0,
type: 'task',
status: task.status || 'not-started',
priority: task.priority || 'medium',
assignee: task.assignee ? {
id: task.assignee.id,
name: task.assignee.name,
avatar: task.assignee.avatar,
} : undefined,
parent: task.parent_task_id,
level: task.level || 0,
// Map other fields as needed
}));
}, [tasks]);
const handleTaskUpdate = (taskId: string, updates: Partial<GanttTask>) => {
// Implement your task update logic here
console.log('Update task:', taskId, updates);
// Dispatch Redux action to update task
};
const handleTaskMove = (taskId: string, newDates: { start: Date; end: Date }) => {
// Implement your task move logic here
console.log('Move task:', taskId, newDates);
// Dispatch Redux action to update task dates
};
return (
<div className="project-gantt-view h-full">
<AdvancedGanttChart
tasks={ganttTasks}
onTaskUpdate={handleTaskUpdate}
onTaskMove={handleTaskMove}
enableDragDrop={true}
enableResize={true}
enableProgressEdit={true}
enableInlineEdit={true}
className="h-full"
/>
</div>
);
};
export default ProjectGanttView;

View File

@@ -39,6 +39,7 @@ import { resetState as resetEnhancedKanbanState } from '@/features/enhanced-kanb
import { setProjectId as setInsightsProjectId } from '@/features/projects/insights/project-insights.slice';
import { SuspenseFallback } from '@/components/suspense-fallback/suspense-fallback';
import { useTranslation } from 'react-i18next';
import { useTimerInitialization } from '@/hooks/useTimerInitialization';
// Import critical components synchronously to avoid suspense interruptions
@@ -89,6 +90,9 @@ const ProjectView = React.memo(() => {
const [taskid, setTaskId] = useState<string>(urlParams.taskId);
const [isInitialized, setIsInitialized] = useState(false);
// Initialize timer state from backend when project view loads
useTimerInitialization();
// Update local state when URL params change
useEffect(() => {
setActiveTab(urlParams.tab);

View File

@@ -0,0 +1,307 @@
import { ReactNode } from 'react';
// Core Task Interface
export interface GanttTask {
id: string;
name: string;
startDate: Date;
endDate: Date;
progress: number;
duration?: number; // in days
parent?: string;
type: 'task' | 'milestone' | 'project';
status: 'not-started' | 'in-progress' | 'completed' | 'on-hold' | 'overdue';
priority: 'low' | 'medium' | 'high' | 'critical';
assignee?: {
id: string;
name: string;
avatar?: string;
};
dependencies?: string[];
description?: string;
tags?: string[];
color?: string;
isCollapsed?: boolean;
level?: number; // for hierarchical display
hasChildren?: boolean;
isExpanded?: boolean;
}
// Column Configuration
export interface ColumnConfig {
field: keyof GanttTask | string;
title: string;
width: number;
minWidth?: number;
maxWidth?: number;
resizable: boolean;
sortable: boolean;
fixed: boolean;
align?: 'left' | 'center' | 'right';
renderer?: (value: any, task: GanttTask) => ReactNode;
editor?: 'text' | 'date' | 'select' | 'number' | 'progress';
editorOptions?: any;
}
// Timeline Configuration
export interface TimelineConfig {
topTier: {
unit: 'year' | 'month' | 'week' | 'day';
format: string;
height?: number;
};
bottomTier: {
unit: 'month' | 'week' | 'day' | 'hour';
format: string;
height?: number;
};
showWeekends: boolean;
showNonWorkingDays: boolean;
holidays: Holiday[];
workingDays: number[]; // 0-6, Sunday-Saturday
workingHours: {
start: number; // 0-23
end: number; // 0-23
};
minDate?: Date;
maxDate?: Date;
dayWidth: number; // pixels per day
}
// Holiday Interface
export interface Holiday {
date: Date;
name: string;
type: 'national' | 'company' | 'religious' | 'custom';
recurring?: boolean;
color?: string;
}
// Virtual Scrolling Configuration
export interface VirtualScrollConfig {
enableRowVirtualization: boolean;
enableTimelineVirtualization: boolean;
bufferSize: number;
itemHeight: number;
overscan?: number;
}
// Drag and Drop State
export interface DragState {
isDragging: boolean;
dragType: 'move' | 'resize-start' | 'resize-end' | 'progress' | 'link';
taskId: string;
initialPosition: { x: number; y: number };
currentPosition?: { x: number; y: number };
initialDates: { start: Date; end: Date };
initialProgress?: number;
snapToGrid?: boolean;
constraints?: {
minDate?: Date;
maxDate?: Date;
minDuration?: number;
maxDuration?: number;
};
}
// Zoom Levels
export interface ZoomLevel {
name: string;
dayWidth: number;
topTier: TimelineConfig['topTier'];
bottomTier: TimelineConfig['bottomTier'];
scale: number;
}
// Selection State
export interface SelectionState {
selectedTasks: string[];
selectedRows: number[];
selectionRange?: {
start: { row: number; col: number };
end: { row: number; col: number };
};
focusedTask?: string;
}
// Gantt View State
export interface GanttViewState {
zoomLevel: number;
scrollPosition: { x: number; y: number };
viewportSize: { width: number; height: number };
splitterPosition: number; // percentage for grid/timeline split
showCriticalPath: boolean;
showBaseline: boolean;
showProgress: boolean;
showDependencies: boolean;
autoSchedule: boolean;
readOnly: boolean;
}
// Performance Metrics
export interface PerformanceMetrics {
renderTime: number;
taskCount: number;
visibleTaskCount: number;
memoryUsage?: number;
fps?: number;
}
// Event Handlers
export type TaskEventHandler<T = void> = (task: GanttTask, event: MouseEvent | TouchEvent) => T;
export type DragEventHandler = (taskId: string, newDates: { start: Date; end: Date }) => void;
export type ResizeEventHandler = (taskId: string, newDates: { start: Date; end: Date }) => void;
export type ProgressEventHandler = (taskId: string, progress: number) => void;
export type SelectionEventHandler = (selectedTasks: string[]) => void;
export type ColumnResizeHandler = (columnField: string, newWidth: number) => void;
// Gantt Actions (for useReducer)
export type GanttAction =
| { type: 'SET_TASKS'; payload: GanttTask[] }
| { type: 'UPDATE_TASK'; payload: { id: string; updates: Partial<GanttTask> } }
| { type: 'ADD_TASK'; payload: GanttTask }
| { type: 'DELETE_TASK'; payload: string }
| { type: 'SET_SELECTION'; payload: string[] }
| { type: 'SET_DRAG_STATE'; payload: DragState | null }
| { type: 'SET_ZOOM_LEVEL'; payload: number }
| { type: 'SET_SCROLL_POSITION'; payload: { x: number; y: number } }
| { type: 'SET_SPLITTER_POSITION'; payload: number }
| { type: 'TOGGLE_TASK_EXPANSION'; payload: string }
| { type: 'SET_VIEW_STATE'; payload: Partial<GanttViewState> }
| { type: 'UPDATE_COLUMN_WIDTH'; payload: { field: string; width: number } };
// Main Gantt State
export interface GanttState {
tasks: GanttTask[];
columns: ColumnConfig[];
timelineConfig: TimelineConfig;
virtualScrollConfig: VirtualScrollConfig;
dragState: DragState | null;
selectionState: SelectionState;
viewState: GanttViewState;
zoomLevels: ZoomLevel[];
performanceMetrics: PerformanceMetrics;
}
// Gantt Chart Props
export interface AdvancedGanttProps {
// Data
tasks: GanttTask[];
columns?: ColumnConfig[];
// Configuration
timelineConfig?: Partial<TimelineConfig>;
virtualScrollConfig?: Partial<VirtualScrollConfig>;
zoomLevels?: ZoomLevel[];
// Initial State
initialViewState?: Partial<GanttViewState>;
initialSelection?: string[];
// Event Handlers
onTaskUpdate?: (taskId: string, updates: Partial<GanttTask>) => void;
onTaskCreate?: (task: Omit<GanttTask, 'id'>) => void;
onTaskDelete?: (taskId: string) => void;
onTaskMove?: DragEventHandler;
onTaskResize?: ResizeEventHandler;
onProgressChange?: ProgressEventHandler;
onSelectionChange?: SelectionEventHandler;
onColumnResize?: ColumnResizeHandler;
onDependencyCreate?: (fromTaskId: string, toTaskId: string) => void;
onDependencyDelete?: (fromTaskId: string, toTaskId: string) => void;
// UI Customization
className?: string;
style?: React.CSSProperties;
theme?: 'light' | 'dark' | 'auto';
locale?: string;
// Feature Flags
enableDragDrop?: boolean;
enableResize?: boolean;
enableProgressEdit?: boolean;
enableInlineEdit?: boolean;
enableContextMenu?: boolean;
enableTooltips?: boolean;
enableExport?: boolean;
enablePrint?: boolean;
// Performance Options
enableVirtualScrolling?: boolean;
enableDebouncing?: boolean;
debounceDelay?: number;
maxVisibleTasks?: number;
}
// Context Menu Options
export interface ContextMenuOption {
id: string;
label: string;
icon?: ReactNode;
disabled?: boolean;
separator?: boolean;
children?: ContextMenuOption[];
onClick?: (task?: GanttTask) => void;
}
// Export Options
export interface ExportOptions {
format: 'png' | 'pdf' | 'svg' | 'json' | 'csv' | 'xlsx';
includeColumns?: string[];
dateRange?: { start: Date; end: Date };
filename?: string;
paperSize?: 'A4' | 'A3' | 'Letter' | 'Legal';
orientation?: 'portrait' | 'landscape';
scale?: number;
}
// Filter and Search
export interface FilterConfig {
field: string;
operator: 'equals' | 'contains' | 'startsWith' | 'endsWith' | 'greaterThan' | 'lessThan' | 'between';
value: any;
logic?: 'and' | 'or';
}
export interface SearchConfig {
query: string;
fields: string[];
caseSensitive?: boolean;
wholeWord?: boolean;
regex?: boolean;
}
// Baseline and Critical Path
export interface TaskBaseline {
taskId: string;
baselineStart: Date;
baselineEnd: Date;
baselineDuration: number;
baselineProgress: number;
variance?: number; // days
}
export interface CriticalPath {
taskIds: string[];
totalDuration: number;
slack: number; // days of buffer
}
// Undo/Redo
export interface HistoryState {
past: GanttState[];
present: GanttState;
future: GanttState[];
maxHistorySize: number;
}
// Keyboard Shortcuts
export interface KeyboardShortcut {
key: string;
ctrl?: boolean;
shift?: boolean;
alt?: boolean;
action: string;
description: string;
handler: (event: KeyboardEvent) => void;
}

View File

@@ -0,0 +1,62 @@
export interface ProjectPhase {
id: string;
name: string;
description: string;
startDate: Date;
endDate: Date;
progress: number;
color: string;
status: 'not-started' | 'in-progress' | 'completed' | 'on-hold';
tasks: PhaseTask[];
milestones: PhaseMilestone[];
}
export interface PhaseTask {
id: string;
name: string;
description?: string;
startDate: Date;
endDate: Date;
progress: number;
assigneeId?: string;
assigneeName?: string;
priority: 'low' | 'medium' | 'high';
status: 'todo' | 'in-progress' | 'done';
dependencies?: string[];
}
export interface PhaseMilestone {
id: string;
name: string;
description?: string;
dueDate: Date;
isCompleted: boolean;
criticalPath: boolean;
}
export interface ProjectRoadmap {
id: string;
projectId: string;
name: string;
description?: string;
startDate: Date;
endDate: Date;
phases: ProjectPhase[];
createdAt: Date;
updatedAt: Date;
}
export interface GanttViewOptions {
viewMode: 'day' | 'week' | 'month' | 'year';
showTasks: boolean;
showMilestones: boolean;
groupByPhase: boolean;
}
export interface PhaseModalData extends ProjectPhase {
taskCount: number;
completedTaskCount: number;
milestoneCount: number;
completedMilestoneCount: number;
teamMembers: string[];
}

View File

@@ -41,6 +41,10 @@ export interface Task {
has_subscribers?: boolean;
schedule_id?: string | null;
order?: number;
status_sort_order?: number; // Sort order when grouped by status
priority_sort_order?: number; // Sort order when grouped by priority
phase_sort_order?: number; // Sort order when grouped by phase
member_sort_order?: number; // Sort order when grouped by members
reporter?: string; // Reporter field
timeTracking?: { // Time tracking information
logged?: number;
@@ -173,3 +177,21 @@ export interface BulkAction {
value?: any;
taskIds: string[];
}
// Helper function to get the appropriate sort order field based on grouping
export function getSortOrderField(grouping: string | undefined): keyof Task {
switch (grouping) {
case 'status':
return 'status_sort_order';
case 'priority':
return 'priority_sort_order';
case 'phase':
return 'phase_sort_order';
case 'members':
return 'member_sort_order';
case 'general':
return 'order'; // explicit general sorting
default:
return 'status_sort_order'; // Default to status sorting to match backend
}
}

View File

@@ -0,0 +1,163 @@
/**
* Cache cleanup utilities for logout operations
* Handles clearing of various caches to prevent stale data issues
*/
export class CacheCleanup {
/**
* Clear all caches including service worker, browser cache, and storage
*/
static async clearAllCaches(): Promise<void> {
try {
console.log('CacheCleanup: Starting cache clearing process...');
// Clear browser caches
if ('caches' in window) {
const cacheNames = await caches.keys();
console.log('CacheCleanup: Found caches:', cacheNames);
await Promise.all(
cacheNames.map(async cacheName => {
const deleted = await caches.delete(cacheName);
console.log(`CacheCleanup: Deleted cache "${cacheName}":`, deleted);
return deleted;
})
);
console.log('CacheCleanup: Browser caches cleared');
} else {
console.log('CacheCleanup: Cache API not supported');
}
// Clear service worker cache
if ('serviceWorker' in navigator) {
const registration = await navigator.serviceWorker.getRegistration();
if (registration) {
console.log('CacheCleanup: Found service worker registration');
// Send logout message to service worker to clear its caches and unregister
if (registration.active) {
try {
console.log('CacheCleanup: Sending LOGOUT message to service worker...');
await this.sendMessageToServiceWorker('LOGOUT');
console.log('CacheCleanup: LOGOUT message sent successfully');
} catch (error) {
console.warn('CacheCleanup: Failed to send logout message to service worker:', error);
// Fallback: try to clear cache manually
try {
console.log('CacheCleanup: Trying fallback CLEAR_CACHE message...');
await this.sendMessageToServiceWorker('CLEAR_CACHE');
console.log('CacheCleanup: CLEAR_CACHE message sent successfully');
} catch (fallbackError) {
console.warn('CacheCleanup: Failed to clear service worker cache:', fallbackError);
}
}
}
// If service worker is still registered, unregister it
if (registration.active) {
console.log('CacheCleanup: Unregistering service worker...');
await registration.unregister();
console.log('CacheCleanup: Service worker unregistered');
}
} else {
console.log('CacheCleanup: No service worker registration found');
}
} else {
console.log('CacheCleanup: Service Worker not supported');
}
// Clear localStorage and sessionStorage
const localStorageKeys = Object.keys(localStorage);
const sessionStorageKeys = Object.keys(sessionStorage);
console.log('CacheCleanup: Clearing localStorage keys:', localStorageKeys);
console.log('CacheCleanup: Clearing sessionStorage keys:', sessionStorageKeys);
localStorage.clear();
sessionStorage.clear();
console.log('CacheCleanup: Local storage cleared');
console.log('CacheCleanup: Cache clearing process completed successfully');
} catch (error) {
console.error('CacheCleanup: Error clearing caches:', error);
throw error;
}
}
/**
* Send message to service worker
*/
private static async sendMessageToServiceWorker(type: string, payload?: any): Promise<any> {
if (!('serviceWorker' in navigator)) {
throw new Error('Service Worker not supported');
}
const registration = await navigator.serviceWorker.getRegistration();
if (!registration || !registration.active) {
throw new Error('Service Worker not active');
}
return new Promise((resolve, reject) => {
const messageChannel = new MessageChannel();
messageChannel.port1.onmessage = (event) => {
if (event.data.error) {
reject(event.data.error);
} else {
resolve(event.data);
}
};
registration.active!.postMessage(
{ type, payload },
[messageChannel.port2]
);
// Timeout after 5 seconds
setTimeout(() => {
reject(new Error('Service Worker message timeout'));
}, 5000);
});
}
/**
* Force reload the page to ensure fresh state
*/
static forceReload(url: string = '/auth/login'): void {
// Use replace to prevent back button issues
window.location.replace(url);
}
/**
* Clear specific cache types
*/
static async clearSpecificCaches(cacheTypes: string[]): Promise<void> {
if (!('caches' in window)) return;
const cacheNames = await caches.keys();
const cachesToDelete = cacheNames.filter(name =>
cacheTypes.some(type => name.includes(type))
);
await Promise.all(
cachesToDelete.map(cacheName => caches.delete(cacheName))
);
}
/**
* Clear API cache specifically
*/
static async clearAPICache(): Promise<void> {
await this.clearSpecificCaches(['api', 'dynamic']);
}
/**
* Clear static asset cache
*/
static async clearStaticCache(): Promise<void> {
await this.clearSpecificCaches(['static', 'images']);
}
}
export default CacheCleanup;

View File

@@ -0,0 +1,408 @@
import { useMemo, useCallback, useRef, useEffect } from 'react';
import { GanttTask, PerformanceMetrics } from '../types/advanced-gantt.types';
// Debounce utility for drag operations
export function useDebounce<T extends (...args: any[]) => any>(
callback: T,
delay: number
): T {
const timeoutRef = useRef<NodeJS.Timeout>();
return useCallback((...args: Parameters<T>) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
callback(...args);
}, delay);
}, [callback, delay]) as T;
}
// Throttle utility for scroll events
export function useThrottle<T extends (...args: any[]) => any>(
callback: T,
delay: number
): T {
const lastCall = useRef<number>(0);
return useCallback((...args: Parameters<T>) => {
const now = Date.now();
if (now - lastCall.current >= delay) {
lastCall.current = now;
callback(...args);
}
}, [callback, delay]) as T;
}
// Memoized task calculations
export const useTaskCalculations = (tasks: GanttTask[]) => {
return useMemo(() => {
const taskMap = new Map<string, GanttTask>();
const parentChildMap = new Map<string, string[]>();
const dependencyMap = new Map<string, string[]>();
// Build maps for efficient lookups
tasks.forEach(task => {
taskMap.set(task.id, task);
if (task.parent) {
if (!parentChildMap.has(task.parent)) {
parentChildMap.set(task.parent, []);
}
parentChildMap.get(task.parent)!.push(task.id);
}
if (task.dependencies) {
dependencyMap.set(task.id, task.dependencies);
}
});
return {
taskMap,
parentChildMap,
dependencyMap,
totalTasks: tasks.length,
projectTasks: tasks.filter(t => t.type === 'project'),
milestones: tasks.filter(t => t.type === 'milestone'),
regularTasks: tasks.filter(t => t.type === 'task'),
};
}, [tasks]);
};
// Virtual scrolling calculations
export interface VirtualScrollData {
startIndex: number;
endIndex: number;
visibleItems: GanttTask[];
totalHeight: number;
offsetY: number;
}
export const useVirtualScrolling = (
tasks: GanttTask[],
containerHeight: number,
itemHeight: number,
scrollTop: number,
overscan: number = 5
): VirtualScrollData => {
return useMemo(() => {
const totalHeight = tasks.length * itemHeight;
const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - overscan);
const endIndex = Math.min(
tasks.length - 1,
Math.ceil((scrollTop + containerHeight) / itemHeight) + overscan
);
const visibleItems = tasks.slice(startIndex, endIndex + 1);
const offsetY = startIndex * itemHeight;
return {
startIndex,
endIndex,
visibleItems,
totalHeight,
offsetY,
};
}, [tasks, containerHeight, itemHeight, scrollTop, overscan]);
};
// Timeline virtual scrolling
export interface TimelineVirtualData {
startDate: Date;
endDate: Date;
visibleDays: Date[];
totalWidth: number;
offsetX: number;
}
export const useTimelineVirtualScrolling = (
projectStartDate: Date,
projectEndDate: Date,
dayWidth: number,
containerWidth: number,
scrollLeft: number,
overscan: number = 10
): TimelineVirtualData => {
return useMemo(() => {
const totalDays = Math.ceil((projectEndDate.getTime() - projectStartDate.getTime()) / (1000 * 60 * 60 * 24));
const totalWidth = totalDays * dayWidth;
const startDayIndex = Math.max(0, Math.floor(scrollLeft / dayWidth) - overscan);
const endDayIndex = Math.min(
totalDays - 1,
Math.ceil((scrollLeft + containerWidth) / dayWidth) + overscan
);
const visibleDays: Date[] = [];
for (let i = startDayIndex; i <= endDayIndex; i++) {
const date = new Date(projectStartDate);
date.setDate(date.getDate() + i);
visibleDays.push(date);
}
const offsetX = startDayIndex * dayWidth;
const startDate = new Date(projectStartDate);
startDate.setDate(startDate.getDate() + startDayIndex);
const endDate = new Date(projectStartDate);
endDate.setDate(endDate.getDate() + endDayIndex);
return {
startDate,
endDate,
visibleDays,
totalWidth,
offsetX,
};
}, [projectStartDate, projectEndDate, dayWidth, containerWidth, scrollLeft, overscan]);
};
// Performance monitoring hook
export const usePerformanceMonitoring = (): {
metrics: PerformanceMetrics;
startMeasure: (name: string) => void;
endMeasure: (name: string) => void;
recordMetric: (name: string, value: number) => void;
} => {
const metricsRef = useRef<PerformanceMetrics>({
renderTime: 0,
taskCount: 0,
visibleTaskCount: 0,
});
const measurementsRef = useRef<Map<string, number>>(new Map());
const startMeasure = useCallback((name: string) => {
measurementsRef.current.set(name, performance.now());
}, []);
const endMeasure = useCallback((name: string) => {
const startTime = measurementsRef.current.get(name);
if (startTime) {
const duration = performance.now() - startTime;
measurementsRef.current.delete(name);
if (name === 'render') {
metricsRef.current.renderTime = duration;
}
}
}, []);
const recordMetric = useCallback((name: string, value: number) => {
switch (name) {
case 'taskCount':
metricsRef.current.taskCount = value;
break;
case 'visibleTaskCount':
metricsRef.current.visibleTaskCount = value;
break;
case 'memoryUsage':
metricsRef.current.memoryUsage = value;
break;
case 'fps':
metricsRef.current.fps = value;
break;
}
}, []);
return {
metrics: metricsRef.current,
startMeasure,
endMeasure,
recordMetric,
};
};
// Intersection Observer for lazy loading
export const useIntersectionObserver = (
callback: (entries: IntersectionObserverEntry[]) => void,
options?: IntersectionObserverInit
) => {
const targetRef = useRef<HTMLElement>(null);
const observerRef = useRef<IntersectionObserver>();
useEffect(() => {
if (!targetRef.current) return;
observerRef.current = new IntersectionObserver(callback, {
root: null,
rootMargin: '100px',
threshold: 0.1,
...options,
});
observerRef.current.observe(targetRef.current);
return () => {
if (observerRef.current) {
observerRef.current.disconnect();
}
};
}, [callback, options]);
return targetRef;
};
// Date calculations optimization
export const useDateCalculations = () => {
return useMemo(() => {
const cache = new Map<string, number>();
const getDaysBetween = (start: Date, end: Date): number => {
const key = `${start.getTime()}-${end.getTime()}`;
if (cache.has(key)) {
return cache.get(key)!;
}
const days = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
cache.set(key, days);
return days;
};
const addDays = (date: Date, days: number): Date => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
const isWeekend = (date: Date): boolean => {
const day = date.getDay();
return day === 0 || day === 6; // Sunday or Saturday
};
const isWorkingDay = (date: Date, workingDays: number[]): boolean => {
return workingDays.includes(date.getDay());
};
const getWorkingDaysBetween = (start: Date, end: Date, workingDays: number[]): number => {
let count = 0;
const current = new Date(start);
while (current <= end) {
if (isWorkingDay(current, workingDays)) {
count++;
}
current.setDate(current.getDate() + 1);
}
return count;
};
return {
getDaysBetween,
addDays,
isWeekend,
isWorkingDay,
getWorkingDaysBetween,
clearCache: () => cache.clear(),
};
}, []);
};
// Task position calculations
export const useTaskPositions = (
tasks: GanttTask[],
timelineStart: Date,
dayWidth: number
) => {
return useMemo(() => {
const positions = new Map<string, { x: number; width: number; y: number }>();
tasks.forEach((task, index) => {
const startDays = Math.floor((task.startDate.getTime() - timelineStart.getTime()) / (1000 * 60 * 60 * 24));
const endDays = Math.floor((task.endDate.getTime() - timelineStart.getTime()) / (1000 * 60 * 60 * 24));
positions.set(task.id, {
x: startDays * dayWidth,
width: Math.max(1, (endDays - startDays) * dayWidth),
y: index * 40, // Assuming 40px row height
});
});
return positions;
}, [tasks, timelineStart, dayWidth]);
};
// Memory management utilities
export const useMemoryManagement = () => {
const cleanupFunctions = useRef<Array<() => void>>([]);
const addCleanup = useCallback((cleanup: () => void) => {
cleanupFunctions.current.push(cleanup);
}, []);
const runCleanup = useCallback(() => {
cleanupFunctions.current.forEach(cleanup => cleanup());
cleanupFunctions.current = [];
}, []);
useEffect(() => {
return runCleanup;
}, [runCleanup]);
return { addCleanup, runCleanup };
};
// Batch update utility for multiple task changes
export const useBatchUpdates = <T>(
updateFunction: (updates: T[]) => void,
delay: number = 100
) => {
const batchRef = useRef<T[]>([]);
const timeoutRef = useRef<NodeJS.Timeout>();
const addUpdate = useCallback((update: T) => {
batchRef.current.push(update);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
if (batchRef.current.length > 0) {
updateFunction([...batchRef.current]);
batchRef.current = [];
}
}, delay);
}, [updateFunction, delay]);
const flushUpdates = useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
if (batchRef.current.length > 0) {
updateFunction([...batchRef.current]);
batchRef.current = [];
}
}, [updateFunction]);
return { addUpdate, flushUpdates };
};
// FPS monitoring
export const useFPSMonitoring = () => {
const fpsRef = useRef<number>(0);
const frameCountRef = useRef<number>(0);
const lastTimeRef = useRef<number>(performance.now());
const measureFPS = useCallback(() => {
frameCountRef.current++;
const now = performance.now();
if (now - lastTimeRef.current >= 1000) {
fpsRef.current = Math.round((frameCountRef.current * 1000) / (now - lastTimeRef.current));
frameCountRef.current = 0;
lastTimeRef.current = now;
}
requestAnimationFrame(measureFPS);
}, []);
useEffect(() => {
const rafId = requestAnimationFrame(measureFPS);
return () => cancelAnimationFrame(rafId);
}, [measureFPS]);
return fpsRef.current;
};