feat: implement 8 OpenSpec proposals for security, reliability, and UX improvements

## Security Enhancements (P0)
- Add input validation with max_length and numeric range constraints
- Implement WebSocket token authentication via first message
- Add path traversal prevention in file storage service

## Permission Enhancements (P0)
- Add project member management for cross-department access
- Implement is_department_manager flag for workload visibility

## Cycle Detection (P0)
- Add DFS-based cycle detection for task dependencies
- Add formula field circular reference detection
- Display user-friendly cycle path visualization

## Concurrency & Reliability (P1)
- Implement optimistic locking with version field (409 Conflict on mismatch)
- Add trigger retry mechanism with exponential backoff (1s, 2s, 4s)
- Implement cascade restore for soft-deleted tasks

## Rate Limiting (P1)
- Add tiered rate limits: standard (60/min), sensitive (20/min), heavy (5/min)
- Apply rate limits to tasks, reports, attachments, and comments

## Frontend Improvements (P1)
- Add responsive sidebar with hamburger menu for mobile
- Improve touch-friendly UI with proper tap target sizes
- Complete i18n translations for all components

## Backend Reliability (P2)
- Configure database connection pool (size=10, overflow=20)
- Add Redis fallback mechanism with message queue
- Add blocker check before task deletion

## API Enhancements (P3)
- Add standardized response wrapper utility
- Add /health/ready and /health/live endpoints
- Implement project templates with status/field copying

## Tests Added
- test_input_validation.py - Schema and path traversal tests
- test_concurrency_reliability.py - Optimistic locking and retry tests
- test_backend_reliability.py - Connection pool and Redis tests
- test_api_enhancements.py - Health check and template tests

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
beabigegg
2026-01-10 22:13:43 +08:00
parent 96210c7ad4
commit 3bdc6ff1c9
106 changed files with 9704 additions and 429 deletions

View File

@@ -53,7 +53,10 @@
"searchUsers": "Search users...",
"noUsersFound": "No users found",
"typeToSearch": "Type to search users",
"task": "Task"
"task": "Task",
"admin": "Admin",
"live": "Live",
"offline": "Offline"
},
"messages": {
"success": "Operation successful",
@@ -81,7 +84,9 @@
"health": "Project Health",
"audit": "Audit Log",
"settings": "Settings",
"logout": "Logout"
"logout": "Logout",
"toggleMenu": "Toggle Menu",
"menu": "Menu"
},
"language": {
"switch": "Switch language",

View File

@@ -64,5 +64,16 @@
"empty": {
"title": "No Projects",
"description": "Create your first project to start managing tasks"
},
"template": {
"label": "Template",
"selectTemplate": "Select a template",
"blankProject": "Blank Project",
"blankProjectDescription": "Start with a clean slate",
"loadingTemplates": "Loading templates...",
"loadFailed": "Failed to load templates",
"statusCount": "{{count}} statuses",
"fieldCount": "{{count}} custom fields",
"publicTemplate": "Public"
}
}

View File

@@ -39,13 +39,39 @@
},
"members": {
"title": "Member Management",
"description": "Manage users who can access this project. Project members can view and edit project content.",
"addMember": "Add Member",
"invite": "Invite Member",
"inviteByEmail": "Invite by email",
"emailPlaceholder": "Enter email address",
"selectUser": "Select User",
"searchUserPlaceholder": "Search users...",
"user": "User",
"role": "Role",
"joinedAt": "Joined",
"changeRole": "Change Role",
"remove": "Remove Member",
"confirmRemove": "Are you sure you want to remove this member?"
"remove": "Remove",
"confirmRemove": "Are you sure you want to remove this member?",
"removeConfirmTitle": "Remove Member",
"removeConfirmMessage": "Are you sure you want to remove {{name}} from this project? They will no longer have access.",
"empty": "No members in this project yet.",
"emptyHint": "Click \"Add Member\" to add project members.",
"loadError": "Failed to load member list",
"addError": "Failed to add member",
"removeError": "Failed to remove member",
"roleChangeError": "Failed to change role",
"memberAdded": "Member added successfully",
"adding": "Adding...",
"selectUserRequired": "Please select a user to add",
"alreadyMember": "This user is already a project member",
"roles": {
"member": "Member",
"admin": "Admin"
},
"roleHelp": {
"member": "Members can view and edit tasks in this project.",
"admin": "Admins can manage project settings and members."
}
},
"customFields": {
"title": "Custom Fields",
@@ -104,6 +130,12 @@
},
"validation": {
"nameRequired": "Field name is required"
},
"circularError": {
"title": "Circular Reference Detected",
"description": "This formula creates a circular reference, which is not allowed.",
"cyclePath": "Reference Cycle",
"helpText": "To resolve this issue, modify the formula to avoid referencing fields that directly or indirectly reference this field."
}
},
"notifications": {

View File

@@ -181,5 +181,33 @@
"title": "No Tasks",
"description": "There are no tasks yet. Create your first task to get started!",
"filtered": "No tasks match your filters"
},
"dependencies": {
"title": "Task Dependencies",
"add": "Add Dependency",
"remove": "Remove Dependency",
"predecessor": "Predecessor",
"successor": "Successor",
"type": "Dependency Type",
"types": {
"FS": "Finish-to-Start",
"SS": "Start-to-Start",
"FF": "Finish-to-Finish",
"SF": "Start-to-Finish"
},
"circularError": {
"title": "Circular Dependency Detected",
"description": "Adding this dependency would create a circular reference, which is not allowed.",
"cyclePath": "Dependency Cycle",
"helpText": "To resolve this issue, choose a different task as a dependency, or remove one of the existing dependencies in the cycle."
},
"error": {
"addFailed": "Failed to add dependency",
"removeFailed": "Failed to remove dependency"
}
},
"conflict": {
"title": "Update Conflict",
"message": "This task has been modified by another user. Please refresh to see the latest version and try again."
}
}

View File

@@ -53,7 +53,10 @@
"searchUsers": "搜尋使用者...",
"noUsersFound": "找不到使用者",
"typeToSearch": "輸入以搜尋使用者",
"task": "任務"
"task": "任務",
"admin": "管理員",
"live": "即時",
"offline": "離線"
},
"messages": {
"success": "操作成功",
@@ -81,7 +84,9 @@
"health": "專案健康度",
"audit": "稽核日誌",
"settings": "設定",
"logout": "登出"
"logout": "登出",
"toggleMenu": "切換選單",
"menu": "選單"
},
"language": {
"switch": "切換語言",

View File

@@ -64,5 +64,16 @@
"empty": {
"title": "沒有專案",
"description": "建立您的第一個專案來開始管理任務"
},
"template": {
"label": "模板",
"selectTemplate": "選擇模板",
"blankProject": "空白專案",
"blankProjectDescription": "從頭開始建立",
"loadingTemplates": "載入模板中...",
"loadFailed": "載入模板失敗",
"statusCount": "{{count}} 個狀態",
"fieldCount": "{{count}} 個自訂欄位",
"publicTemplate": "公開"
}
}

View File

@@ -39,13 +39,39 @@
},
"members": {
"title": "成員管理",
"description": "管理可以存取此專案的使用者。專案成員可以檢視和編輯專案內容。",
"addMember": "新增成員",
"invite": "邀請成員",
"inviteByEmail": "透過電子郵件邀請",
"emailPlaceholder": "輸入電子郵件地址",
"selectUser": "選擇使用者",
"searchUserPlaceholder": "搜尋使用者...",
"user": "使用者",
"role": "角色",
"joinedAt": "加入時間",
"changeRole": "變更角色",
"remove": "移除成員",
"confirmRemove": "確定要移除此成員嗎?"
"remove": "移除",
"confirmRemove": "確定要移除此成員嗎?",
"removeConfirmTitle": "移除成員",
"removeConfirmMessage": "確定要將 {{name}} 從此專案移除嗎?移除後該成員將無法存取此專案。",
"empty": "此專案尚無成員。",
"emptyHint": "點擊「新增成員」來添加專案成員。",
"loadError": "載入成員列表失敗",
"addError": "新增成員失敗",
"removeError": "移除成員失敗",
"roleChangeError": "變更角色失敗",
"memberAdded": "成員已新增",
"adding": "新增中...",
"selectUserRequired": "請選擇要新增的使用者",
"alreadyMember": "此使用者已經是專案成員",
"roles": {
"member": "成員",
"admin": "管理員"
},
"roleHelp": {
"member": "成員可以檢視和編輯專案中的任務。",
"admin": "管理員可以管理專案設定和成員。"
}
},
"customFields": {
"title": "自訂欄位",
@@ -104,6 +130,12 @@
},
"validation": {
"nameRequired": "欄位名稱為必填"
},
"circularError": {
"title": "偵測到循環參照",
"description": "此公式會產生循環參照,這是不被允許的。",
"cyclePath": "參照循環路徑",
"helpText": "要解決此問題,請修改公式以避免參照直接或間接參照此欄位的其他欄位。"
}
},
"notifications": {

View File

@@ -181,5 +181,33 @@
"title": "沒有任務",
"description": "目前沒有任務。建立您的第一個任務開始吧!",
"filtered": "沒有符合篩選條件的任務"
},
"dependencies": {
"title": "任務相依性",
"add": "新增相依性",
"remove": "移除相依性",
"predecessor": "前置任務",
"successor": "後續任務",
"type": "相依性類型",
"types": {
"FS": "完成後開始",
"SS": "同時開始",
"FF": "同時完成",
"SF": "開始後完成"
},
"circularError": {
"title": "偵測到循環相依",
"description": "新增此相依性會產生循環參照,這是不被允許的。",
"cyclePath": "相依性循環路徑",
"helpText": "要解決此問題,請選擇不同的任務作為相依項,或移除循環中現有的某個相依關係。"
},
"error": {
"addFailed": "新增相依性失敗",
"removeFailed": "移除相依性失敗"
}
},
"conflict": {
"title": "更新衝突",
"message": "此任務已被其他使用者修改。請重新整理頁面以取得最新版本,然後再試一次。"
}
}

View File

@@ -0,0 +1,240 @@
import { useState, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { UserSelect } from './UserSelect'
import { UserSearchResult } from '../services/collaboration'
interface AddMemberModalProps {
isOpen: boolean
onClose: () => void
onAdd: (userId: string, role: 'member' | 'admin') => void
existingMemberIds: string[]
loading?: boolean
}
export function AddMemberModal({
isOpen,
onClose,
onAdd,
existingMemberIds,
loading = false,
}: AddMemberModalProps) {
const { t } = useTranslation('settings')
const [selectedUserId, setSelectedUserId] = useState<string | null>(null)
const [selectedRole, setSelectedRole] = useState<'member' | 'admin'>('member')
const [error, setError] = useState<string | null>(null)
const modalOverlayRef = useRef<HTMLDivElement>(null)
// Reset state when modal opens/closes
useEffect(() => {
if (isOpen) {
setSelectedUserId(null)
setSelectedRole('member')
setError(null)
}
}, [isOpen])
// Handle Escape key to close modal
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isOpen && !loading) {
onClose()
}
}
if (isOpen) {
document.addEventListener('keydown', handleKeyDown)
}
return () => {
document.removeEventListener('keydown', handleKeyDown)
}
}, [isOpen, loading, onClose])
if (!isOpen) return null
const handleOverlayClick = (e: React.MouseEvent) => {
if (e.target === e.currentTarget && !loading) {
onClose()
}
}
const handleUserChange = (userId: string | null, _user: UserSearchResult | null) => {
setSelectedUserId(userId)
setError(null)
// Check if user is already a member
if (userId && existingMemberIds.includes(userId)) {
setError(t('members.alreadyMember'))
}
}
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!selectedUserId) {
setError(t('members.selectUserRequired'))
return
}
if (existingMemberIds.includes(selectedUserId)) {
setError(t('members.alreadyMember'))
return
}
onAdd(selectedUserId, selectedRole)
}
return (
<div
ref={modalOverlayRef}
style={styles.overlay}
onClick={handleOverlayClick}
role="dialog"
aria-modal="true"
aria-labelledby="add-member-modal-title"
>
<div style={styles.modal}>
<h2 id="add-member-modal-title" style={styles.title}>
{t('members.addMember')}
</h2>
<form onSubmit={handleSubmit}>
<div style={styles.formGroup}>
<label style={styles.label}>{t('members.selectUser')}</label>
<UserSelect
value={selectedUserId}
onChange={handleUserChange}
placeholder={t('members.searchUserPlaceholder')}
disabled={loading}
/>
{error && <span style={styles.errorText}>{error}</span>}
</div>
<div style={styles.formGroup}>
<label style={styles.label}>{t('members.role')}</label>
<select
value={selectedRole}
onChange={(e) => setSelectedRole(e.target.value as 'member' | 'admin')}
style={styles.select}
disabled={loading}
>
<option value="member">{t('members.roles.member')}</option>
<option value="admin">{t('members.roles.admin')}</option>
</select>
<p style={styles.helpText}>
{selectedRole === 'admin'
? t('members.roleHelp.admin')
: t('members.roleHelp.member')}
</p>
</div>
<div style={styles.actions}>
<button
type="button"
onClick={onClose}
style={styles.cancelButton}
disabled={loading}
>
{t('common:buttons.cancel')}
</button>
<button
type="submit"
style={styles.submitButton}
disabled={loading || !selectedUserId || !!error}
>
{loading ? t('members.adding') : t('members.addMember')}
</button>
</div>
</form>
</div>
</div>
)
}
const styles: Record<string, React.CSSProperties> = {
overlay: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
zIndex: 1200,
},
modal: {
backgroundColor: 'white',
borderRadius: '8px',
padding: '24px',
width: '450px',
maxWidth: '90%',
boxShadow: '0 8px 32px rgba(0, 0, 0, 0.2)',
},
title: {
margin: '0 0 24px 0',
fontSize: '18px',
fontWeight: 600,
color: '#212529',
},
formGroup: {
marginBottom: '20px',
},
label: {
display: 'block',
marginBottom: '8px',
fontSize: '14px',
fontWeight: 500,
color: '#495057',
},
select: {
width: '100%',
padding: '10px',
fontSize: '14px',
border: '1px solid #ddd',
borderRadius: '6px',
backgroundColor: 'white',
cursor: 'pointer',
boxSizing: 'border-box',
},
helpText: {
margin: '8px 0 0 0',
fontSize: '13px',
color: '#6c757d',
lineHeight: 1.4,
},
errorText: {
display: 'block',
marginTop: '8px',
fontSize: '13px',
color: '#c92a2a',
},
actions: {
display: 'flex',
justifyContent: 'flex-end',
gap: '12px',
marginTop: '24px',
},
cancelButton: {
padding: '10px 20px',
backgroundColor: '#f8f9fa',
color: '#495057',
border: '1px solid #dee2e6',
borderRadius: '6px',
fontSize: '14px',
cursor: 'pointer',
},
submitButton: {
padding: '10px 20px',
backgroundColor: '#0066cc',
color: 'white',
border: 'none',
borderRadius: '6px',
fontSize: '14px',
fontWeight: 500,
cursor: 'pointer',
},
}
export default AddMemberModal

View File

@@ -24,6 +24,7 @@ interface Task {
time_estimate: number | null
subtask_count: number
parent_task_id: string | null
version?: number
}
interface TaskStatus {
@@ -257,12 +258,25 @@ export function CalendarView({
const newDueDate = `${year}-${month}-${day}`
try {
await api.patch(`/tasks/${task.id}`, {
const payload: Record<string, unknown> = {
due_date: newDueDate,
})
}
// Include version for optimistic locking
if (task.version) {
payload.version = task.version
}
await api.patch(`/tasks/${task.id}`, payload)
// Refresh to get updated data
onTaskUpdate()
} catch (err) {
} catch (err: unknown) {
// Handle 409 Conflict - version mismatch
if (err && typeof err === 'object' && 'response' in err) {
const axiosError = err as { response?: { status?: number } }
if (axiosError.response?.status === 409) {
// Refresh to get latest data on conflict
onTaskUpdate()
}
}
console.error('Failed to update task date:', err)
// Rollback on error
dropInfo.revert()

View File

@@ -0,0 +1,268 @@
import { useTranslation } from 'react-i18next'
interface CycleDetails {
cycle: string[]
cycle_description: string
cycle_task_titles?: string[]
cycle_field_names?: string[]
}
interface CircularDependencyErrorProps {
errorType: 'task' | 'formula'
cycleDetails: CycleDetails
onDismiss?: () => void
}
/**
* Component to display circular dependency errors with a user-friendly
* visualization of the cycle path.
*/
export function CircularDependencyError({
errorType,
cycleDetails,
onDismiss,
}: CircularDependencyErrorProps) {
const { t } = useTranslation(['tasks', 'settings', 'common'])
// Get display names for the cycle - prefer titles/names over IDs
const cycleDisplayNames =
errorType === 'task'
? cycleDetails.cycle_task_titles || cycleDetails.cycle
: cycleDetails.cycle_field_names || cycleDetails.cycle
return (
<div style={styles.container}>
<div style={styles.header}>
<div style={styles.iconContainer}>
<svg
style={styles.icon}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="8" x2="12" y2="12" />
<line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
</div>
<div style={styles.titleContainer}>
<h4 style={styles.title}>
{errorType === 'task'
? t('tasks:dependencies.circularError.title')
: t('settings:customFields.circularError.title')}
</h4>
<p style={styles.description}>
{errorType === 'task'
? t('tasks:dependencies.circularError.description')
: t('settings:customFields.circularError.description')}
</p>
</div>
{onDismiss && (
<button
onClick={onDismiss}
style={styles.dismissButton}
aria-label={t('common:buttons.close')}
>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
)}
</div>
<div style={styles.cycleVisualization}>
<div style={styles.cycleLabel}>
{errorType === 'task'
? t('tasks:dependencies.circularError.cyclePath')
: t('settings:customFields.circularError.cyclePath')}
</div>
<div style={styles.cyclePathContainer}>
{cycleDisplayNames.map((name, index) => (
<div key={index} style={styles.cycleItem}>
<div
style={{
...styles.cycleNode,
...(index === 0 || index === cycleDisplayNames.length - 1
? styles.cycleNodeHighlight
: {}),
}}
>
{name}
</div>
{index < cycleDisplayNames.length - 1 && (
<div style={styles.cycleArrow}>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<line x1="5" y1="12" x2="19" y2="12" />
<polyline points="12 5 19 12 12 19" />
</svg>
</div>
)}
</div>
))}
</div>
</div>
<div style={styles.helpSection}>
<p style={styles.helpText}>
{errorType === 'task'
? t('tasks:dependencies.circularError.helpText')
: t('settings:customFields.circularError.helpText')}
</p>
</div>
</div>
)
}
/**
* Parse circular dependency error from API response
*/
export function parseCircularError(
errorDetail: unknown
): { isCircular: boolean; cycleDetails?: CycleDetails } {
if (!errorDetail || typeof errorDetail !== 'object') {
return { isCircular: false }
}
const detail = errorDetail as Record<string, unknown>
// Check if this is a circular dependency error
if (detail.error_type === 'circular') {
const details = detail.details as CycleDetails | undefined
if (details) {
return {
isCircular: true,
cycleDetails: {
cycle: details.cycle || [],
cycle_description: details.cycle_description || '',
cycle_task_titles: details.cycle_task_titles,
cycle_field_names: details.cycle_field_names,
},
}
}
}
return { isCircular: false }
}
const styles: Record<string, React.CSSProperties> = {
container: {
backgroundColor: '#fff8e1',
border: '1px solid #ffc107',
borderRadius: '8px',
padding: '16px',
marginBottom: '16px',
},
header: {
display: 'flex',
alignItems: 'flex-start',
gap: '12px',
marginBottom: '16px',
},
iconContainer: {
flexShrink: 0,
},
icon: {
width: '24px',
height: '24px',
color: '#f57c00',
},
titleContainer: {
flex: 1,
},
title: {
margin: 0,
fontSize: '16px',
fontWeight: 600,
color: '#e65100',
},
description: {
margin: '4px 0 0 0',
fontSize: '14px',
color: '#5d4037',
},
dismissButton: {
padding: '4px',
backgroundColor: 'transparent',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
color: '#795548',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
cycleVisualization: {
backgroundColor: '#fff3e0',
borderRadius: '6px',
padding: '12px',
marginBottom: '12px',
},
cycleLabel: {
fontSize: '12px',
fontWeight: 500,
color: '#bf360c',
textTransform: 'uppercase',
marginBottom: '8px',
},
cyclePathContainer: {
display: 'flex',
flexWrap: 'wrap',
alignItems: 'center',
gap: '4px',
},
cycleItem: {
display: 'flex',
alignItems: 'center',
gap: '4px',
},
cycleNode: {
padding: '6px 12px',
backgroundColor: 'white',
border: '1px solid #ffcc80',
borderRadius: '4px',
fontSize: '13px',
fontWeight: 500,
color: '#5d4037',
whiteSpace: 'nowrap',
},
cycleNodeHighlight: {
backgroundColor: '#ffecb3',
borderColor: '#ffa726',
color: '#e65100',
},
cycleArrow: {
color: '#ff9800',
display: 'flex',
alignItems: 'center',
},
helpSection: {
borderTop: '1px solid #ffe082',
paddingTop: '12px',
},
helpText: {
margin: 0,
fontSize: '13px',
color: '#6d4c41',
lineHeight: 1.5,
},
}
export default CircularDependencyError

View File

@@ -7,6 +7,13 @@ import {
CustomFieldUpdate,
FieldType,
} from '../services/customFields'
import { CircularDependencyError, parseCircularError } from './CircularDependencyError'
interface CycleDetails {
cycle: string[]
cycle_description: string
cycle_field_names?: string[]
}
interface CustomFieldEditorProps {
projectId: string
@@ -40,6 +47,7 @@ export function CustomFieldEditor({
const [formula, setFormula] = useState(field?.formula || '')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [circularError, setCircularError] = useState<CycleDetails | null>(null)
const modalOverlayRef = useRef<HTMLDivElement>(null)
// A11Y: Handle Escape key to close modal
@@ -74,6 +82,7 @@ export function CustomFieldEditor({
setFormula('')
}
setError(null)
setCircularError(null)
}, [field])
const handleOverlayClick = (e: React.MouseEvent) => {
@@ -125,6 +134,7 @@ export function CustomFieldEditor({
setSaving(true)
setError(null)
setCircularError(null)
try {
if (isEditing && field) {
@@ -164,10 +174,19 @@ export function CustomFieldEditor({
onSave()
} catch (err: unknown) {
const errorMessage =
(err as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||
t('customFields.saveError')
setError(errorMessage)
const error = err as { response?: { data?: { detail?: unknown } } }
const errorDetail = error?.response?.data?.detail
// Check if this is a circular reference error
const { isCircular, cycleDetails } = parseCircularError(errorDetail)
if (isCircular && cycleDetails) {
setCircularError(cycleDetails)
setError(null)
} else {
const errorMessage =
typeof errorDetail === 'string' ? errorDetail : t('customFields.saveError')
setError(errorMessage)
}
} finally {
setSaving(false)
}
@@ -194,7 +213,15 @@ export function CustomFieldEditor({
</div>
<div style={styles.content}>
{error && <div style={styles.errorMessage}>{error}</div>}
{circularError && (
<CircularDependencyError
errorType="formula"
cycleDetails={circularError}
onDismiss={() => setCircularError(null)}
/>
)}
{error && !circularError && <div style={styles.errorMessage}>{error}</div>}
{/* Field Name */}
<div style={styles.formGroup}>

View File

@@ -1,7 +1,15 @@
import { useEffect, useRef, useState, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import Gantt, { GanttTask, ViewMode } from 'frappe-gantt'
import api from '../services/api'
import { dependenciesApi, TaskDependency, DependencyType } from '../services/dependencies'
import { CircularDependencyError, parseCircularError } from './CircularDependencyError'
interface CycleDetails {
cycle: string[]
cycle_description: string
cycle_task_titles?: string[]
}
interface Task {
id: string
@@ -20,6 +28,7 @@ interface Task {
subtask_count: number
parent_task_id: string | null
progress?: number
version?: number
}
interface TaskStatus {
@@ -52,6 +61,7 @@ export function GanttChart({
onTaskClick,
onTaskUpdate,
}: GanttChartProps) {
const { t } = useTranslation(['tasks', 'common'])
const ganttRef = useRef<HTMLDivElement>(null)
const ganttInstance = useRef<Gantt | null>(null)
const [viewMode, setViewMode] = useState<ViewMode>('Week')
@@ -65,6 +75,7 @@ export function GanttChart({
const [selectedPredecessor, setSelectedPredecessor] = useState<string>('')
const [selectedDependencyType, setSelectedDependencyType] = useState<DependencyType>('FS')
const [dependencyError, setDependencyError] = useState<string | null>(null)
const [circularError, setCircularError] = useState<CycleDetails | null>(null)
// Task data mapping for quick lookup
const taskMap = useRef<Map<string, Task>>(new Map())
@@ -257,16 +268,32 @@ export function GanttChart({
const dueDate = formatLocalDate(end)
try {
await api.patch(`/tasks/${taskId}`, {
// Find the task to get its version
const task = tasks.find(t => t.id === taskId)
const payload: Record<string, unknown> = {
start_date: startDate,
due_date: dueDate,
})
}
// Include version for optimistic locking
if (task?.version) {
payload.version = task.version
}
await api.patch(`/tasks/${taskId}`, payload)
onTaskUpdate()
} catch (err: unknown) {
console.error('Failed to update task dates:', err)
const error = err as { response?: { data?: { detail?: string } } }
const errorMessage = error.response?.data?.detail || 'Failed to update task dates'
setError(errorMessage)
const error = err as { response?: { status?: number; data?: { detail?: string | { message?: string } } } }
// Handle 409 Conflict - version mismatch
if (error.response?.status === 409) {
const detail = error.response?.data?.detail
const errorMessage = typeof detail === 'object' ? detail?.message : 'Task has been modified by another user'
setError(errorMessage || 'Task has been modified by another user')
} else {
const errorMessage = typeof error.response?.data?.detail === 'string'
? error.response?.data?.detail
: 'Failed to update task dates'
setError(errorMessage)
}
// Refresh to rollback visual changes
onTaskUpdate()
} finally {
@@ -286,6 +313,7 @@ export function GanttChart({
if (!selectedTaskForDependency || !selectedPredecessor) return
setDependencyError(null)
setCircularError(null)
try {
await dependenciesApi.addDependency(selectedTaskForDependency.id, {
@@ -299,9 +327,21 @@ export function GanttChart({
setSelectedDependencyType('FS')
} catch (err: unknown) {
console.error('Failed to add dependency:', err)
const error = err as { response?: { data?: { detail?: string } } }
const errorMessage = error.response?.data?.detail || 'Failed to add dependency'
setDependencyError(errorMessage)
const error = err as { response?: { data?: { detail?: unknown } } }
const errorDetail = error.response?.data?.detail
// Check if this is a circular dependency error
const { isCircular, cycleDetails } = parseCircularError(errorDetail)
if (isCircular && cycleDetails) {
setCircularError(cycleDetails)
setDependencyError(null)
} else {
const errorMessage =
typeof errorDetail === 'string'
? errorDetail
: t('dependencies.error.addFailed')
setDependencyError(errorMessage)
}
}
}
@@ -321,6 +361,7 @@ export function GanttChart({
setSelectedTaskForDependency(task)
setSelectedPredecessor('')
setDependencyError(null)
setCircularError(null)
setShowDependencyModal(true)
}
@@ -465,7 +506,15 @@ export function GanttChart({
Manage Dependencies for "{selectedTaskForDependency.title}"
</h2>
{dependencyError && (
{circularError && (
<CircularDependencyError
errorType="task"
cycleDetails={circularError}
onDismiss={() => setCircularError(null)}
/>
)}
{dependencyError && !circularError && (
<div style={styles.modalError}>{dependencyError}</div>
)}
@@ -546,11 +595,12 @@ export function GanttChart({
setShowDependencyModal(false)
setSelectedTaskForDependency(null)
setDependencyError(null)
setCircularError(null)
setSelectedDependencyType('FS')
}}
style={styles.closeButton}
>
Close
{t('common:buttons.close')}
</button>
</div>
</div>

View File

@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useState, useRef, useCallback, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { CustomValueResponse } from '../services/customFields'
@@ -19,6 +19,7 @@ interface Task {
subtask_count: number
parent_task_id: string | null
custom_values?: CustomValueResponse[]
version?: number
}
interface TaskStatus {
@@ -35,16 +36,37 @@ interface KanbanBoardProps {
onTaskClick: (task: Task) => void
}
// Touch event detection
const isTouchDevice = () => {
return 'ontouchstart' in window || navigator.maxTouchPoints > 0
}
export function KanbanBoard({
tasks,
statuses,
onStatusChange,
onTaskClick,
}: KanbanBoardProps) {
const { t } = useTranslation('tasks')
const { t, i18n } = useTranslation('tasks')
const [draggedTaskId, setDraggedTaskId] = useState<string | null>(null)
const [dragOverColumnId, setDragOverColumnId] = useState<string | null>(null)
// Touch drag state
const [touchDragTask, setTouchDragTask] = useState<Task | null>(null)
const [touchDragPosition, setTouchDragPosition] = useState<{ x: number; y: number } | null>(null)
const touchStartRef = useRef<{ x: number; y: number; time: number } | null>(null)
const longPressTimerRef = useRef<number | null>(null)
const boardRef = useRef<HTMLDivElement>(null)
// Clean up long press timer on unmount
useEffect(() => {
return () => {
if (longPressTimerRef.current) {
clearTimeout(longPressTimerRef.current)
}
}
}, [])
// Group tasks by status
const tasksByStatus: Record<string, Task[]> = {}
statuses.forEach((status) => {
@@ -53,6 +75,7 @@ export function KanbanBoard({
// Tasks without status
const unassignedTasks = tasks.filter((task) => !task.status_id)
// Desktop drag handlers
const handleDragStart = (e: React.DragEvent, taskId: string) => {
setDraggedTaskId(taskId)
e.dataTransfer.effectAllowed = 'move'
@@ -97,6 +120,120 @@ export function KanbanBoard({
setDragOverColumnId(null)
}
// Touch drag handlers for mobile
const handleTouchStart = useCallback((e: React.TouchEvent, task: Task) => {
const touch = e.touches[0]
touchStartRef.current = {
x: touch.clientX,
y: touch.clientY,
time: Date.now(),
}
// Start long press timer for drag initiation
longPressTimerRef.current = window.setTimeout(() => {
// Vibrate for haptic feedback if available
if (navigator.vibrate) {
navigator.vibrate(50)
}
setTouchDragTask(task)
setTouchDragPosition({ x: touch.clientX, y: touch.clientY })
}, 300) // 300ms long press to start drag
}, [])
const handleTouchMove = useCallback((e: React.TouchEvent) => {
const touch = e.touches[0]
// Cancel long press if moved too far before timer fires
if (touchStartRef.current && !touchDragTask) {
const dx = Math.abs(touch.clientX - touchStartRef.current.x)
const dy = Math.abs(touch.clientY - touchStartRef.current.y)
if (dx > 10 || dy > 10) {
if (longPressTimerRef.current) {
clearTimeout(longPressTimerRef.current)
longPressTimerRef.current = null
}
}
}
// Update drag position
if (touchDragTask) {
e.preventDefault() // Prevent scrolling while dragging
setTouchDragPosition({ x: touch.clientX, y: touch.clientY })
// Find column under touch point
const columnElements = boardRef.current?.querySelectorAll('[data-status-id]')
columnElements?.forEach((col) => {
const rect = col.getBoundingClientRect()
if (
touch.clientX >= rect.left &&
touch.clientX <= rect.right &&
touch.clientY >= rect.top &&
touch.clientY <= rect.bottom
) {
const statusId = col.getAttribute('data-status-id')
if (statusId && dragOverColumnId !== statusId) {
setDragOverColumnId(statusId)
}
}
})
}
}, [touchDragTask, dragOverColumnId])
const handleTouchEnd = useCallback(() => {
// Clear long press timer
if (longPressTimerRef.current) {
clearTimeout(longPressTimerRef.current)
longPressTimerRef.current = null
}
// Handle drop on touch end
if (touchDragTask && dragOverColumnId) {
if (touchDragTask.status_id !== dragOverColumnId) {
onStatusChange(touchDragTask.id, dragOverColumnId)
}
}
// Reset touch drag state
setTouchDragTask(null)
setTouchDragPosition(null)
setDragOverColumnId(null)
touchStartRef.current = null
}, [touchDragTask, dragOverColumnId, onStatusChange])
const handleTouchCancel = useCallback(() => {
if (longPressTimerRef.current) {
clearTimeout(longPressTimerRef.current)
longPressTimerRef.current = null
}
setTouchDragTask(null)
setTouchDragPosition(null)
setDragOverColumnId(null)
touchStartRef.current = null
}, [])
// Handle click/tap - prevent click if dragging
const handleCardClick = useCallback((e: React.MouseEvent | React.TouchEvent, task: Task) => {
// If there was a touch drag, don't trigger click
if (touchDragTask) {
e.preventDefault()
return
}
// For touch events, check if it was a quick tap
if (touchStartRef.current) {
const elapsed = Date.now() - touchStartRef.current.time
if (elapsed < 300) {
// Quick tap - trigger click
onTaskClick(task)
}
touchStartRef.current = null
return
}
// Desktop click
onTaskClick(task)
}, [touchDragTask, onTaskClick])
const getPriorityColor = (priority: string): string => {
const colors: Record<string, string> = {
low: '#808080',
@@ -107,54 +244,115 @@ export function KanbanBoard({
return colors[priority] || colors.medium
}
const renderTaskCard = (task: Task) => (
<div
key={task.id}
style={{
...styles.taskCard,
borderLeftColor: getPriorityColor(task.priority),
opacity: draggedTaskId === task.id ? 0.5 : 1,
}}
draggable
onDragStart={(e) => handleDragStart(e, task.id)}
onDragEnd={handleDragEnd}
onClick={() => onTaskClick(task)}
>
<div style={styles.taskTitle}>{task.title}</div>
{task.description && (
<div style={styles.taskDescription}>
{task.description.length > 80
? task.description.substring(0, 80) + '...'
: task.description}
// Format date according to locale
const formatDate = (dateString: string): string => {
const date = new Date(dateString)
return date.toLocaleDateString(i18n.language, {
month: 'short',
day: 'numeric',
})
}
const renderTaskCard = (task: Task) => {
const isDragging = draggedTaskId === task.id || touchDragTask?.id === task.id
return (
<div
key={task.id}
style={{
...styles.taskCard,
borderLeftColor: getPriorityColor(task.priority),
opacity: isDragging ? 0.5 : 1,
transform: isDragging ? 'scale(1.02)' : 'none',
}}
draggable={!isTouchDevice()}
onDragStart={(e) => handleDragStart(e, task.id)}
onDragEnd={handleDragEnd}
onClick={(e) => handleCardClick(e, task)}
onTouchStart={(e) => handleTouchStart(e, task)}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
onTouchCancel={handleTouchCancel}
>
<div style={styles.taskTitle}>{task.title}</div>
{task.description && (
<div style={styles.taskDescription}>
{task.description.length > 80
? task.description.substring(0, 80) + '...'
: task.description}
</div>
)}
<div style={styles.taskMeta}>
{task.assignee_name && (
<span style={styles.assigneeBadge}>{task.assignee_name}</span>
)}
{task.due_date && (
<span style={styles.dueDate}>
{formatDate(task.due_date)}
</span>
)}
{task.subtask_count > 0 && (
<span style={styles.subtaskBadge}>{t('subtasks.count', { count: task.subtask_count })}</span>
)}
{/* Display custom field values (limit to first 2 for compact display) */}
{task.custom_values?.slice(0, 2).map((cv) => (
<span key={cv.field_id} style={styles.customValueBadge}>
{cv.field_name}: {cv.display_value || cv.value || '-'}
</span>
))}
</div>
)}
<div style={styles.taskMeta}>
{task.assignee_name && (
<span style={styles.assigneeBadge}>{task.assignee_name}</span>
{/* Touch-friendly quick action button */}
{isTouchDevice() && (
<div style={styles.touchActions}>
<select
value={task.status_id || ''}
onChange={(e) => {
e.stopPropagation()
onStatusChange(task.id, e.target.value)
}}
onClick={(e) => e.stopPropagation()}
onTouchEnd={(e) => e.stopPropagation()}
style={styles.statusSelectMini}
>
{statuses.map((status) => (
<option key={status.id} value={status.id}>
{status.name}
</option>
))}
</select>
</div>
)}
{task.due_date && (
<span style={styles.dueDate}>
{new Date(task.due_date).toLocaleDateString()}
</span>
)}
{task.subtask_count > 0 && (
<span style={styles.subtaskBadge}>{t('subtasks.count', { count: task.subtask_count })}</span>
)}
{/* Display custom field values (limit to first 2 for compact display) */}
{task.custom_values?.slice(0, 2).map((cv) => (
<span key={cv.field_id} style={styles.customValueBadge}>
{cv.field_name}: {cv.display_value || cv.value || '-'}
</span>
))}
</div>
</div>
)
)
}
return (
<div style={styles.board}>
<div ref={boardRef} style={styles.board}>
{/* Touch drag ghost element */}
{touchDragTask && touchDragPosition && (
<div
style={{
...styles.dragGhost,
left: touchDragPosition.x - 120,
top: touchDragPosition.y - 40,
}}
>
<div style={styles.dragGhostContent}>
<div
style={{
...styles.dragGhostPriority,
backgroundColor: getPriorityColor(touchDragTask.priority),
}}
/>
<span style={styles.dragGhostTitle}>{touchDragTask.title}</span>
</div>
</div>
)}
{/* Unassigned column (if there are tasks without status) */}
{unassignedTasks.length > 0 && (
<div style={styles.column}>
<div style={styles.column} data-status-id="unassigned">
<div
style={{
...styles.columnHeader,
@@ -174,6 +372,7 @@ export function KanbanBoard({
{statuses.map((status) => (
<div
key={status.id}
data-status-id={status.id}
style={{
...styles.column,
...(dragOverColumnId === status.id ? styles.columnDragOver : {}),
@@ -214,6 +413,8 @@ const styles: Record<string, React.CSSProperties> = {
overflowX: 'auto',
paddingBottom: '16px',
minHeight: '500px',
WebkitOverflowScrolling: 'touch',
position: 'relative',
},
column: {
flex: '0 0 280px',
@@ -222,7 +423,7 @@ const styles: Record<string, React.CSSProperties> = {
display: 'flex',
flexDirection: 'column',
maxHeight: 'calc(100vh - 200px)',
transition: 'background-color 0.2s ease',
transition: 'background-color 0.2s ease, box-shadow 0.2s ease',
},
columnDragOver: {
backgroundColor: '#e3f2fd',
@@ -236,6 +437,7 @@ const styles: Record<string, React.CSSProperties> = {
borderRadius: '8px 8px 0 0',
color: 'white',
fontWeight: 600,
minHeight: '48px',
},
columnTitle: {
fontSize: '14px',
@@ -243,8 +445,10 @@ const styles: Record<string, React.CSSProperties> = {
taskCount: {
fontSize: '12px',
backgroundColor: 'rgba(255, 255, 255, 0.3)',
padding: '2px 8px',
padding: '4px 10px',
borderRadius: '10px',
minWidth: '24px',
textAlign: 'center',
},
taskList: {
flex: 1,
@@ -252,16 +456,19 @@ const styles: Record<string, React.CSSProperties> = {
overflowY: 'auto',
display: 'flex',
flexDirection: 'column',
gap: '8px',
gap: '10px',
WebkitOverflowScrolling: 'touch',
},
taskCard: {
backgroundColor: 'white',
borderRadius: '6px',
padding: '12px',
borderRadius: '8px',
padding: '14px',
boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
cursor: 'grab',
cursor: 'pointer',
borderLeft: '4px solid',
transition: 'box-shadow 0.2s ease, transform 0.2s ease',
touchAction: 'manipulation',
userSelect: 'none',
},
taskTitle: {
fontSize: '14px',
@@ -284,19 +491,21 @@ const styles: Record<string, React.CSSProperties> = {
assigneeBadge: {
backgroundColor: '#e3f2fd',
color: '#1565c0',
padding: '2px 6px',
padding: '4px 8px',
borderRadius: '4px',
},
dueDate: {
color: '#666',
padding: '4px 0',
},
subtaskBadge: {
color: '#767676', // WCAG AA compliant
padding: '4px 0',
},
customValueBadge: {
backgroundColor: '#f3e5f5',
color: '#7b1fa2',
padding: '2px 6px',
padding: '4px 8px',
borderRadius: '4px',
fontSize: '10px',
maxWidth: '100px',
@@ -312,6 +521,51 @@ const styles: Record<string, React.CSSProperties> = {
border: '2px dashed #ddd',
borderRadius: '6px',
},
// Touch-friendly action area
touchActions: {
marginTop: '10px',
paddingTop: '10px',
borderTop: '1px solid #eee',
},
statusSelectMini: {
width: '100%',
padding: '10px 12px',
border: '1px solid #ddd',
borderRadius: '6px',
fontSize: '13px',
backgroundColor: 'white',
minHeight: '44px',
},
// Drag ghost for touch
dragGhost: {
position: 'fixed',
zIndex: 1000,
pointerEvents: 'none',
width: '240px',
backgroundColor: 'white',
borderRadius: '8px',
boxShadow: '0 8px 24px rgba(0, 0, 0, 0.2)',
padding: '12px',
opacity: 0.9,
},
dragGhostContent: {
display: 'flex',
alignItems: 'center',
gap: '10px',
},
dragGhostPriority: {
width: '4px',
height: '24px',
borderRadius: '2px',
flexShrink: 0,
},
dragGhostTitle: {
fontSize: '14px',
fontWeight: 500,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
}
export default KanbanBoard

View File

@@ -1,4 +1,4 @@
import { ReactNode } from 'react'
import { ReactNode, useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useAuth } from '../contexts/AuthContext'
@@ -9,45 +9,121 @@ interface LayoutProps {
children: ReactNode
}
const MOBILE_BREAKPOINT = 768
export default function Layout({ children }: LayoutProps) {
const { t } = useTranslation('common')
const { user, logout } = useAuth()
const navigate = useNavigate()
const location = useLocation()
// Sidebar state management
const [isMobile, setIsMobile] = useState(false)
const [sidebarOpen, setSidebarOpen] = useState(false)
// Detect mobile viewport
useEffect(() => {
const checkMobile = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
checkMobile()
window.addEventListener('resize', checkMobile)
return () => window.removeEventListener('resize', checkMobile)
}, [])
// Close sidebar on route change (mobile only)
useEffect(() => {
if (isMobile) {
setSidebarOpen(false)
}
}, [location.pathname, isMobile])
// Handle escape key to close sidebar on mobile
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isMobile && sidebarOpen) {
setSidebarOpen(false)
}
}
document.addEventListener('keydown', handleKeyDown)
return () => document.removeEventListener('keydown', handleKeyDown)
}, [isMobile, sidebarOpen])
const handleLogout = async () => {
await logout()
}
const toggleMobileSidebar = () => {
setSidebarOpen(!sidebarOpen)
}
const handleNavClick = (path: string) => {
navigate(path)
if (isMobile) {
setSidebarOpen(false)
}
}
const navItems = [
{ path: '/', labelKey: 'nav.dashboard' },
{ path: '/spaces', labelKey: 'nav.spaces' },
{ path: '/workload', labelKey: 'nav.workload' },
{ path: '/project-health', labelKey: 'nav.health' },
...(user?.is_system_admin ? [{ path: '/audit', labelKey: 'nav.audit' }] : []),
{ path: '/', labelKey: 'nav.dashboard', icon: 'dashboard' },
{ path: '/spaces', labelKey: 'nav.spaces', icon: 'folder' },
{ path: '/workload', labelKey: 'nav.workload', icon: 'chart' },
{ path: '/project-health', labelKey: 'nav.health', icon: 'health' },
...(user?.is_system_admin ? [{ path: '/audit', labelKey: 'nav.audit', icon: 'audit' }] : []),
]
// Render navigation icon
const renderIcon = (icon: string) => {
const icons: Record<string, string> = {
dashboard: '\u25A0', // Square
folder: '\u25A1', // Empty square
chart: '\u25B2', // Triangle
health: '\u25CF', // Circle
audit: '\u25C6', // Diamond
}
return icons[icon] || '\u25CF'
}
return (
<div style={styles.container}>
{/* Header */}
<header style={styles.header}>
<div style={styles.headerLeft}>
{/* Hamburger menu for mobile */}
{isMobile && (
<button
onClick={toggleMobileSidebar}
style={styles.hamburgerButton}
aria-label={t('nav.toggleMenu')}
aria-expanded={sidebarOpen}
>
<span style={styles.hamburgerLine}></span>
<span style={styles.hamburgerLine}></span>
<span style={styles.hamburgerLine}></span>
</button>
)}
<h1 style={styles.logo} onClick={() => navigate('/')}>
Project Control
</h1>
<nav style={styles.nav}>
{navItems.map((item) => (
<button
key={item.path}
onClick={() => navigate(item.path)}
style={{
...styles.navItem,
...(location.pathname === item.path ? styles.navItemActive : {}),
}}
>
{t(item.labelKey)}
</button>
))}
</nav>
{/* Desktop navigation in header */}
{!isMobile && (
<nav style={styles.nav}>
{navItems.map((item) => (
<button
key={item.path}
onClick={() => navigate(item.path)}
style={{
...styles.navItem,
...(location.pathname === item.path ? styles.navItemActive : {}),
}}
>
{t(item.labelKey)}
</button>
))}
</nav>
)}
</div>
<div style={styles.headerRight}>
<LanguageSwitcher />
@@ -60,13 +136,71 @@ export default function Layout({ children }: LayoutProps) {
{user?.name}
</button>
{user?.is_system_admin && (
<span style={styles.badge}>Admin</span>
<span style={styles.badge}>{t('labels.admin')}</span>
)}
<button onClick={handleLogout} style={styles.logoutButton}>
{t('nav.logout')}
</button>
</div>
</header>
{/* Mobile sidebar overlay */}
{isMobile && sidebarOpen && (
<div
style={styles.overlay}
onClick={() => setSidebarOpen(false)}
aria-hidden="true"
/>
)}
{/* Mobile slide-out sidebar */}
{isMobile && (
<aside
style={{
...styles.mobileSidebar,
transform: sidebarOpen ? 'translateX(0)' : 'translateX(-100%)',
}}
aria-hidden={!sidebarOpen}
>
<div style={styles.sidebarHeader}>
<h2 style={styles.sidebarTitle}>{t('nav.dashboard')}</h2>
<button
onClick={() => setSidebarOpen(false)}
style={styles.closeSidebarButton}
aria-label={t('buttons.close')}
>
X
</button>
</div>
<nav style={styles.sidebarNav}>
{navItems.map((item) => (
<button
key={item.path}
onClick={() => handleNavClick(item.path)}
style={{
...styles.sidebarNavItem,
...(location.pathname === item.path ? styles.sidebarNavItemActive : {}),
}}
>
<span style={styles.navIcon}>{renderIcon(item.icon)}</span>
<span>{t(item.labelKey)}</span>
</button>
))}
</nav>
<div style={styles.sidebarFooter}>
<button
onClick={() => {
handleNavClick('/my-settings')
}}
style={styles.sidebarNavItem}
>
<span style={styles.navIcon}>{'\u2699'}</span>
<span>{t('nav.settings')}</span>
</button>
</div>
</aside>
)}
<main style={styles.main}>{children}</main>
</div>
)
@@ -84,11 +218,35 @@ const styles: { [key: string]: React.CSSProperties } = {
padding: '12px 24px',
backgroundColor: 'white',
boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
position: 'sticky',
top: 0,
zIndex: 100,
},
headerLeft: {
display: 'flex',
alignItems: 'center',
gap: '24px',
gap: '16px',
},
hamburgerButton: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
width: '44px',
height: '44px',
padding: '8px',
backgroundColor: 'transparent',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
gap: '5px',
},
hamburgerLine: {
display: 'block',
width: '24px',
height: '3px',
backgroundColor: '#333',
borderRadius: '2px',
},
logo: {
fontSize: '18px',
@@ -102,13 +260,16 @@ const styles: { [key: string]: React.CSSProperties } = {
gap: '4px',
},
navItem: {
padding: '8px 16px',
padding: '10px 16px',
backgroundColor: 'transparent',
border: 'none',
borderRadius: '4px',
borderRadius: '6px',
cursor: 'pointer',
fontSize: '14px',
color: '#666',
minHeight: '44px',
minWidth: '44px',
transition: 'background-color 0.2s, color 0.2s',
},
navItemActive: {
backgroundColor: '#e3f2fd',
@@ -126,27 +287,120 @@ const styles: { [key: string]: React.CSSProperties } = {
color: '#0066cc',
fontSize: '14px',
cursor: 'pointer',
padding: '4px 8px',
borderRadius: '4px',
padding: '10px 12px',
borderRadius: '6px',
textDecoration: 'underline',
minHeight: '44px',
minWidth: '44px',
},
badge: {
backgroundColor: '#0066cc',
color: 'white',
padding: '2px 8px',
padding: '4px 10px',
borderRadius: '4px',
fontSize: '11px',
fontWeight: 500,
},
logoutButton: {
padding: '8px 16px',
padding: '10px 16px',
backgroundColor: '#f5f5f5',
border: '1px solid #ddd',
borderRadius: '4px',
borderRadius: '6px',
cursor: 'pointer',
fontSize: '14px',
minHeight: '44px',
minWidth: '44px',
transition: 'background-color 0.2s',
},
main: {
minHeight: 'calc(100vh - 60px)',
},
// Mobile sidebar styles
overlay: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
zIndex: 200,
},
mobileSidebar: {
position: 'fixed',
top: 0,
left: 0,
width: '280px',
maxWidth: '85vw',
height: '100vh',
backgroundColor: 'white',
boxShadow: '4px 0 16px rgba(0, 0, 0, 0.15)',
zIndex: 300,
display: 'flex',
flexDirection: 'column',
transition: 'transform 0.3s ease-in-out',
},
sidebarHeader: {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: '16px 20px',
borderBottom: '1px solid #eee',
},
sidebarTitle: {
margin: 0,
fontSize: '18px',
fontWeight: 600,
color: '#333',
},
closeSidebarButton: {
width: '44px',
height: '44px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'transparent',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
fontSize: '18px',
color: '#666',
},
sidebarNav: {
flex: 1,
padding: '16px 12px',
display: 'flex',
flexDirection: 'column',
gap: '4px',
overflowY: 'auto',
},
sidebarNavItem: {
display: 'flex',
alignItems: 'center',
gap: '12px',
padding: '14px 16px',
backgroundColor: 'transparent',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
fontSize: '15px',
color: '#333',
textAlign: 'left',
width: '100%',
minHeight: '48px',
transition: 'background-color 0.2s',
},
sidebarNavItemActive: {
backgroundColor: '#e3f2fd',
color: '#0066cc',
fontWeight: 500,
},
navIcon: {
fontSize: '18px',
width: '24px',
textAlign: 'center',
},
sidebarFooter: {
padding: '12px',
borderTop: '1px solid #eee',
},
}

View File

@@ -0,0 +1,469 @@
import { useState, useEffect, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { projectMembersApi, ProjectMember } from '../services/projectMembers'
import { useToast } from '../contexts/ToastContext'
import { Skeleton } from './Skeleton'
import { ConfirmModal } from './ConfirmModal'
import { AddMemberModal } from './AddMemberModal'
interface ProjectMemberListProps {
projectId: string
}
export function ProjectMemberList({ projectId }: ProjectMemberListProps) {
const { t } = useTranslation('settings')
const { showToast } = useToast()
const [members, setMembers] = useState<ProjectMember[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [isAddModalOpen, setIsAddModalOpen] = useState(false)
const [memberToRemove, setMemberToRemove] = useState<ProjectMember | null>(null)
const [editingMemberId, setEditingMemberId] = useState<string | null>(null)
const [actionLoading, setActionLoading] = useState(false)
const loadMembers = useCallback(async () => {
try {
setLoading(true)
setError(null)
const response = await projectMembersApi.list(projectId)
setMembers(response.members)
} catch (err) {
console.error('Failed to load project members:', err)
setError(t('members.loadError'))
} finally {
setLoading(false)
}
}, [projectId, t])
useEffect(() => {
loadMembers()
}, [loadMembers])
const handleAddMember = async (userId: string, role: 'member' | 'admin') => {
try {
setActionLoading(true)
const newMember = await projectMembersApi.add(projectId, { user_id: userId, role })
setMembers((prev) => [...prev, newMember])
setIsAddModalOpen(false)
showToast(t('members.memberAdded'), 'success')
} catch (err: unknown) {
console.error('Failed to add member:', err)
const errorMessage = err instanceof Error ? err.message : t('members.addError')
const axiosError = err as { response?: { data?: { detail?: string } } }
if (axiosError.response?.data?.detail) {
showToast(axiosError.response.data.detail, 'error')
} else {
showToast(errorMessage, 'error')
}
} finally {
setActionLoading(false)
}
}
const handleRemoveMember = async () => {
if (!memberToRemove) return
try {
setActionLoading(true)
await projectMembersApi.remove(projectId, memberToRemove.id)
setMembers((prev) => prev.filter((m) => m.id !== memberToRemove.id))
setMemberToRemove(null)
showToast(t('messages.memberRemoved'), 'success')
} catch (err) {
console.error('Failed to remove member:', err)
showToast(t('members.removeError'), 'error')
} finally {
setActionLoading(false)
}
}
const handleRoleChange = async (member: ProjectMember, newRole: 'member' | 'admin') => {
if (member.role === newRole) {
setEditingMemberId(null)
return
}
try {
setActionLoading(true)
const updatedMember = await projectMembersApi.updateRole(projectId, member.id, {
role: newRole,
})
setMembers((prev) =>
prev.map((m) => (m.id === member.id ? updatedMember : m))
)
setEditingMemberId(null)
showToast(t('messages.roleChanged'), 'success')
} catch (err) {
console.error('Failed to update member role:', err)
showToast(t('members.roleChangeError'), 'error')
} finally {
setActionLoading(false)
}
}
const formatDate = (dateString: string) => {
const date = new Date(dateString)
return date.toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
})
}
if (loading) {
return (
<div style={styles.section}>
<div style={styles.headerRow}>
<Skeleton variant="text" width={150} height={24} />
<Skeleton variant="rect" width={120} height={36} />
</div>
<div style={styles.memberList}>
{[1, 2, 3].map((i) => (
<div key={i} style={styles.memberItem}>
<Skeleton variant="rect" width={40} height={40} style={{ borderRadius: '50%' }} />
<div style={{ flex: 1 }}>
<Skeleton variant="text" width={150} height={18} />
<Skeleton variant="text" width={200} height={14} style={{ marginTop: 4 }} />
</div>
<Skeleton variant="rect" width={80} height={28} />
</div>
))}
</div>
</div>
)
}
if (error) {
return (
<div style={styles.section}>
<div style={styles.errorContainer}>
<p style={styles.errorText}>{error}</p>
<button onClick={loadMembers} style={styles.retryButton}>
{t('customFields.retry')}
</button>
</div>
</div>
)
}
return (
<div style={styles.section}>
<div style={styles.headerRow}>
<h2 style={styles.sectionTitle}>{t('members.title')}</h2>
<button
onClick={() => setIsAddModalOpen(true)}
style={styles.addButton}
aria-label={t('members.addMember')}
>
{t('members.addMember')}
</button>
</div>
<p style={styles.description}>{t('members.description')}</p>
{members.length === 0 ? (
<div style={styles.emptyState}>
<p style={styles.emptyText}>{t('members.empty')}</p>
<p style={styles.emptyHint}>{t('members.emptyHint')}</p>
</div>
) : (
<div style={styles.memberList}>
<div style={styles.tableHeader}>
<span style={styles.headerCell}>{t('members.user')}</span>
<span style={styles.headerCellSmall}>{t('members.role')}</span>
<span style={styles.headerCellSmall}>{t('members.joinedAt')}</span>
<span style={styles.headerCellActions}>{t('common:labels.actions')}</span>
</div>
{members.map((member) => (
<div key={member.id} style={styles.memberItem}>
<div style={styles.userInfo}>
<div style={styles.avatar}>
{member.user.name.charAt(0).toUpperCase()}
</div>
<div style={styles.userDetails}>
<span style={styles.userName}>{member.user.name}</span>
<span style={styles.userEmail}>{member.user.email}</span>
</div>
</div>
<div style={styles.roleCell}>
{editingMemberId === member.id ? (
<select
value={member.role}
onChange={(e) =>
handleRoleChange(member, e.target.value as 'member' | 'admin')
}
onBlur={() => setEditingMemberId(null)}
style={styles.roleSelect}
autoFocus
disabled={actionLoading}
>
<option value="member">{t('members.roles.member')}</option>
<option value="admin">{t('members.roles.admin')}</option>
</select>
) : (
<span
style={{
...styles.roleBadge,
...(member.role === 'admin' ? styles.adminBadge : styles.memberBadge),
}}
>
{t(`members.roles.${member.role}`)}
</span>
)}
</div>
<div style={styles.dateCell}>
<span style={styles.dateText}>{formatDate(member.joined_at)}</span>
</div>
<div style={styles.actionsCell}>
<button
onClick={() => setEditingMemberId(member.id)}
style={styles.actionButton}
title={t('members.changeRole')}
disabled={actionLoading}
>
{t('members.changeRole')}
</button>
<button
onClick={() => setMemberToRemove(member)}
style={styles.removeButton}
title={t('members.remove')}
disabled={actionLoading}
>
{t('members.remove')}
</button>
</div>
</div>
))}
</div>
)}
<AddMemberModal
isOpen={isAddModalOpen}
onClose={() => setIsAddModalOpen(false)}
onAdd={handleAddMember}
existingMemberIds={members.map((m) => m.user_id)}
loading={actionLoading}
/>
<ConfirmModal
isOpen={!!memberToRemove}
title={t('members.removeConfirmTitle')}
message={t('members.removeConfirmMessage', {
name: memberToRemove?.user.name,
})}
confirmText={t('members.remove')}
cancelText={t('common:buttons.cancel')}
confirmStyle="danger"
onConfirm={handleRemoveMember}
onCancel={() => setMemberToRemove(null)}
/>
</div>
)
}
const styles: Record<string, React.CSSProperties> = {
section: {
backgroundColor: 'white',
borderRadius: '8px',
padding: '24px',
boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
},
headerRow: {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '16px',
},
sectionTitle: {
fontSize: '18px',
fontWeight: 600,
margin: 0,
},
description: {
fontSize: '14px',
color: '#666',
marginBottom: '20px',
},
addButton: {
padding: '8px 16px',
backgroundColor: '#0066cc',
color: 'white',
border: 'none',
borderRadius: '6px',
cursor: 'pointer',
fontSize: '14px',
fontWeight: 500,
},
memberList: {
display: 'flex',
flexDirection: 'column',
gap: '0',
},
tableHeader: {
display: 'grid',
gridTemplateColumns: '1fr 120px 120px 180px',
gap: '16px',
padding: '12px 16px',
backgroundColor: '#f8f9fa',
borderRadius: '6px 6px 0 0',
borderBottom: '1px solid #e9ecef',
},
headerCell: {
fontSize: '13px',
fontWeight: 600,
color: '#495057',
textTransform: 'uppercase',
letterSpacing: '0.5px',
},
headerCellSmall: {
fontSize: '13px',
fontWeight: 600,
color: '#495057',
textTransform: 'uppercase',
letterSpacing: '0.5px',
},
headerCellActions: {
fontSize: '13px',
fontWeight: 600,
color: '#495057',
textTransform: 'uppercase',
letterSpacing: '0.5px',
textAlign: 'right',
},
memberItem: {
display: 'grid',
gridTemplateColumns: '1fr 120px 120px 180px',
gap: '16px',
alignItems: 'center',
padding: '16px',
borderBottom: '1px solid #eee',
},
userInfo: {
display: 'flex',
alignItems: 'center',
gap: '12px',
},
avatar: {
width: '40px',
height: '40px',
borderRadius: '50%',
backgroundColor: '#0066cc',
color: 'white',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '16px',
fontWeight: 600,
},
userDetails: {
display: 'flex',
flexDirection: 'column',
gap: '2px',
},
userName: {
fontSize: '14px',
fontWeight: 500,
color: '#212529',
},
userEmail: {
fontSize: '13px',
color: '#6c757d',
},
roleCell: {
display: 'flex',
alignItems: 'center',
},
roleBadge: {
padding: '4px 10px',
borderRadius: '12px',
fontSize: '12px',
fontWeight: 500,
},
adminBadge: {
backgroundColor: '#e7f5ff',
color: '#1971c2',
},
memberBadge: {
backgroundColor: '#f1f3f4',
color: '#495057',
},
roleSelect: {
padding: '6px 10px',
fontSize: '13px',
borderRadius: '6px',
border: '1px solid #ddd',
backgroundColor: 'white',
cursor: 'pointer',
minWidth: '100px',
},
dateCell: {
display: 'flex',
alignItems: 'center',
},
dateText: {
fontSize: '13px',
color: '#6c757d',
},
actionsCell: {
display: 'flex',
justifyContent: 'flex-end',
gap: '8px',
},
actionButton: {
padding: '6px 12px',
backgroundColor: '#f8f9fa',
color: '#495057',
border: '1px solid #dee2e6',
borderRadius: '4px',
fontSize: '13px',
cursor: 'pointer',
},
removeButton: {
padding: '6px 12px',
backgroundColor: '#fff5f5',
color: '#c92a2a',
border: '1px solid #ffc9c9',
borderRadius: '4px',
fontSize: '13px',
cursor: 'pointer',
},
emptyState: {
textAlign: 'center',
padding: '40px 20px',
backgroundColor: '#f8f9fa',
borderRadius: '8px',
},
emptyText: {
fontSize: '14px',
color: '#495057',
margin: '0 0 8px 0',
},
emptyHint: {
fontSize: '13px',
color: '#868e96',
margin: 0,
},
errorContainer: {
textAlign: 'center',
padding: '40px 20px',
},
errorText: {
fontSize: '14px',
color: '#c92a2a',
marginBottom: '16px',
},
retryButton: {
padding: '8px 16px',
backgroundColor: '#f8f9fa',
color: '#495057',
border: '1px solid #dee2e6',
borderRadius: '6px',
cursor: 'pointer',
fontSize: '14px',
},
}
export default ProjectMemberList

View File

@@ -26,6 +26,7 @@ interface Task {
subtask_count: number
parent_task_id: string | null
custom_values?: CustomValueResponse[]
version?: number
}
interface TaskStatus {
@@ -52,9 +53,14 @@ export function TaskDetailModal({
onUpdate,
onSubtaskClick,
}: TaskDetailModalProps) {
const { t } = useTranslation('tasks')
const { t, i18n } = useTranslation('tasks')
const [isEditing, setIsEditing] = useState(false)
const [saving, setSaving] = useState(false)
const [conflictError, setConflictError] = useState<{
message: string
currentVersion: number
yourVersion: number
} | null>(null)
const [editForm, setEditForm] = useState({
title: task.title,
description: task.description || '',
@@ -153,6 +159,7 @@ export function TaskDetailModal({
const handleSave = async () => {
setSaving(true)
setConflictError(null)
try {
const payload: Record<string, unknown> = {
title: editForm.title,
@@ -160,6 +167,11 @@ export function TaskDetailModal({
priority: editForm.priority,
}
// Include version for optimistic locking
if (task.version) {
payload.version = task.version
}
// Always send status_id (null to clear, or the value)
payload.status_id = editForm.status_id || null
// Always send assignee_id (null to clear, or the value)
@@ -194,13 +206,34 @@ export function TaskDetailModal({
await api.patch(`/tasks/${task.id}`, payload)
setIsEditing(false)
onUpdate()
} catch (err) {
} catch (err: unknown) {
// Handle 409 Conflict - version mismatch
if (err && typeof err === 'object' && 'response' in err) {
const axiosError = err as { response?: { status?: number; data?: { detail?: { error?: string; message?: string; current_version?: number; your_version?: number } } } }
if (axiosError.response?.status === 409) {
const detail = axiosError.response?.data?.detail
if (detail?.error === 'conflict') {
setConflictError({
message: detail.message || t('conflict.message'),
currentVersion: detail.current_version || 0,
yourVersion: detail.your_version || 0,
})
return
}
}
}
console.error('Failed to update task:', err)
} finally {
setSaving(false)
}
}
const handleRefreshTask = () => {
setConflictError(null)
setIsEditing(false)
onUpdate()
}
const handleCustomFieldChange = (fieldId: string, value: string | number | null) => {
setEditCustomValues((prev) => ({
...prev,
@@ -289,6 +322,22 @@ export function TaskDetailModal({
</div>
</div>
{/* Conflict Error Banner */}
{conflictError && (
<div style={styles.conflictBanner}>
<div style={styles.conflictContent}>
<div style={styles.conflictIcon}>!</div>
<div style={styles.conflictText}>
<div style={styles.conflictTitle}>{t('conflict.title')}</div>
<div style={styles.conflictMessage}>{t('conflict.message')}</div>
</div>
</div>
<button onClick={handleRefreshTask} style={styles.conflictRefreshButton}>
{t('common:buttons.refresh')}
</button>
</div>
)}
<div style={styles.content}>
<div style={styles.mainSection}>
{/* Description */}
@@ -424,7 +473,11 @@ export function TaskDetailModal({
) : (
<div style={styles.dueDateDisplay}>
{task.due_date
? new Date(task.due_date).toLocaleDateString()
? new Date(task.due_date).toLocaleDateString(i18n.language, {
year: 'numeric',
month: 'short',
day: 'numeric',
})
: t('status.noDueDate')}
</div>
)}
@@ -742,6 +795,54 @@ const styles: Record<string, React.CSSProperties> = {
color: '#888',
fontStyle: 'italic',
},
conflictBanner: {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '12px 24px',
backgroundColor: '#fff3cd',
borderBottom: '1px solid #ffc107',
},
conflictContent: {
display: 'flex',
alignItems: 'center',
gap: '12px',
},
conflictIcon: {
width: '24px',
height: '24px',
borderRadius: '50%',
backgroundColor: '#ff9800',
color: 'white',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontWeight: 'bold',
fontSize: '14px',
},
conflictText: {
flex: 1,
},
conflictTitle: {
fontWeight: 600,
fontSize: '14px',
color: '#856404',
},
conflictMessage: {
fontSize: '13px',
color: '#856404',
marginTop: '2px',
},
conflictRefreshButton: {
padding: '8px 16px',
backgroundColor: '#ff9800',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '14px',
fontWeight: 500,
},
}
export default TaskDetailModal

View File

@@ -81,13 +81,14 @@ export function NotificationProvider({ children }: { children: ReactNode }) {
if (!token) return
// Use env var if available, otherwise derive from current location
// Note: Token is NOT included in URL for security (use first-message auth instead)
let wsUrl: string
const envWsUrl = import.meta.env.VITE_WS_URL
if (envWsUrl) {
wsUrl = `${envWsUrl}/ws/notifications?token=${token}`
wsUrl = `${envWsUrl}/ws/notifications`
} else {
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
wsUrl = `${wsProtocol}//${window.location.host}/ws/notifications?token=${token}`
wsUrl = `${wsProtocol}//${window.location.host}/ws/notifications`
}
try {
@@ -95,13 +96,11 @@ export function NotificationProvider({ children }: { children: ReactNode }) {
wsRef.current = ws
ws.onopen = () => {
console.log('WebSocket connected')
// Start ping interval
pingIntervalRef.current = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }))
}
}, WS_PING_INTERVAL)
console.log('WebSocket opened, sending authentication...')
// Send authentication message as first message (more secure than query parameter)
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'auth', token }))
}
}
ws.onmessage = (event) => {
@@ -109,8 +108,21 @@ export function NotificationProvider({ children }: { children: ReactNode }) {
const message = JSON.parse(event.data)
switch (message.type) {
case 'auth_required':
// Server requests authentication, send token
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'auth', token }))
}
break
case 'connected':
console.log('WebSocket authenticated:', message.data.message)
// Start ping interval after successful authentication
pingIntervalRef.current = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }))
}
}, WS_PING_INTERVAL)
break
case 'unread_sync':

View File

@@ -96,37 +96,55 @@ export function ProjectSyncProvider({ children }: { children: React.ReactNode })
// Close existing connection
cleanup()
// Build WebSocket URL
// Build WebSocket URL (without token in query parameter for security)
let wsUrl: string
const envWsUrl = import.meta.env.VITE_WS_URL
if (envWsUrl) {
wsUrl = `${envWsUrl}/ws/projects/${projectId}?token=${token}`
wsUrl = `${envWsUrl}/ws/projects/${projectId}`
} else {
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
wsUrl = `${wsProtocol}//${window.location.host}/ws/projects/${projectId}?token=${token}`
wsUrl = `${wsProtocol}//${window.location.host}/ws/projects/${projectId}`
}
try {
const ws = new WebSocket(wsUrl)
ws.onopen = () => {
reconnectAttemptsRef.current = 0 // Reset on successful connection
setIsConnected(true)
setCurrentProjectId(projectId)
devLog(`Connected to project ${projectId} sync`)
// Start ping interval to keep connection alive
pingIntervalRef.current = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }))
}
}, WS_PING_INTERVAL)
devLog(`WebSocket opened for project ${projectId}, sending auth...`)
// Send authentication message as first message (more secure than query parameter)
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'auth', token }))
}
}
ws.onmessage = (event) => {
try {
const message = JSON.parse(event.data)
// Handle auth_required - send auth token
if (message.type === 'auth_required') {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'auth', token }))
}
return
}
// Handle successful authentication
if (message.type === 'connected') {
reconnectAttemptsRef.current = 0 // Reset on successful connection
setIsConnected(true)
setCurrentProjectId(projectId)
devLog(`Authenticated and connected to project ${projectId} sync`)
// Start ping interval to keep connection alive
pingIntervalRef.current = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }))
}
}, WS_PING_INTERVAL)
return
}
// Handle ping/pong
if (message.type === 'ping') {
if (ws.readyState === WebSocket.OPEN) {
@@ -134,7 +152,7 @@ export function ProjectSyncProvider({ children }: { children: React.ReactNode })
}
return
}
if (message.type === 'pong' || message.type === 'connected') {
if (message.type === 'pong') {
return
}

View File

@@ -3,6 +3,7 @@ import { useParams, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import api from '../services/api'
import { CustomFieldList } from '../components/CustomFieldList'
import { ProjectMemberList } from '../components/ProjectMemberList'
import { useToast } from '../contexts/ToastContext'
import { Skeleton } from '../components/Skeleton'
@@ -22,7 +23,7 @@ export default function ProjectSettings() {
const { showToast } = useToast()
const [project, setProject] = useState<Project | null>(null)
const [loading, setLoading] = useState(true)
const [activeTab, setActiveTab] = useState<'general' | 'custom-fields'>('custom-fields')
const [activeTab, setActiveTab] = useState<'general' | 'members' | 'custom-fields'>('custom-fields')
useEffect(() => {
loadProject()
@@ -111,6 +112,15 @@ export default function ProjectSettings() {
>
{t('tabs.general')}
</button>
<button
onClick={() => setActiveTab('members')}
style={{
...styles.navItem,
...(activeTab === 'members' ? styles.navItemActive : {}),
}}
>
{t('tabs.members')}
</button>
<button
onClick={() => setActiveTab('custom-fields')}
style={{
@@ -150,6 +160,10 @@ export default function ProjectSettings() {
</div>
)}
{activeTab === 'members' && (
<ProjectMemberList projectId={projectId!} />
)}
{activeTab === 'custom-fields' && (
<CustomFieldList projectId={projectId!} />
)}

View File

@@ -24,6 +24,31 @@ interface Space {
name: string
}
interface TaskStatusDef {
name: string
color: string
is_done: boolean
position: number
}
interface CustomFieldDef {
name: string
field_type: string
options?: string[]
formula?: string
}
interface ProjectTemplate {
id: string
name: string
description?: string
is_public: boolean
task_statuses: TaskStatusDef[]
custom_fields: CustomFieldDef[]
created_by: string
created_at: string
}
export default function Projects() {
const { t } = useTranslation('projects')
const { spaceId } = useParams()
@@ -40,6 +65,9 @@ export default function Projects() {
security_level: 'department',
})
const [creating, setCreating] = useState(false)
const [templates, setTemplates] = useState<ProjectTemplate[]>([])
const [templatesLoading, setTemplatesLoading] = useState(false)
const [selectedTemplateId, setSelectedTemplateId] = useState<string | null>(null)
const [showDeleteModal, setShowDeleteModal] = useState(false)
const [projectToDelete, setProjectToDelete] = useState<Project | null>(null)
const [deleting, setDeleting] = useState(false)
@@ -94,14 +122,46 @@ export default function Projects() {
}
}
const loadTemplates = async () => {
setTemplatesLoading(true)
try {
const response = await api.get('/templates')
// API returns {templates: [], total: number}
setTemplates(response.data.templates || [])
} catch (err) {
console.error('Failed to load templates:', err)
showToast(t('template.loadFailed'), 'error')
} finally {
setTemplatesLoading(false)
}
}
const handleOpenCreateModal = () => {
setShowCreateModal(true)
setSelectedTemplateId(null)
loadTemplates()
}
const handleCreateProject = async () => {
if (!newProject.title.trim()) return
setCreating(true)
try {
await api.post(`/spaces/${spaceId}/projects`, newProject)
if (selectedTemplateId) {
// Create project from template
await api.post('/templates/create-project', {
template_id: selectedTemplateId,
space_id: spaceId,
title: newProject.title,
description: newProject.description || undefined,
})
} else {
// Create blank project
await api.post(`/spaces/${spaceId}/projects`, newProject)
}
setShowCreateModal(false)
setNewProject({ title: '', description: '', security_level: 'department' })
setSelectedTemplateId(null)
loadData()
showToast(t('messages.created'), 'success')
} catch (err) {
@@ -178,7 +238,7 @@ export default function Projects() {
<div style={styles.header}>
<h1 style={styles.title}>{t('title')}</h1>
<button onClick={() => setShowCreateModal(true)} style={styles.createButton}>
<button onClick={handleOpenCreateModal} style={styles.createButton}>
+ {t('newProject')}
</button>
</div>
@@ -245,6 +305,73 @@ export default function Projects() {
>
<div style={styles.modal}>
<h2 id="create-project-title" style={styles.modalTitle}>{t('createProject')}</h2>
{/* Template Selection */}
<label style={styles.label}>{t('template.label')}</label>
{templatesLoading ? (
<div style={styles.templatesLoading}>{t('template.loadingTemplates')}</div>
) : (
<div style={styles.templateGrid}>
{/* Blank Project Option */}
<div
style={{
...styles.templateCard,
...(selectedTemplateId === null ? styles.templateCardSelected : {}),
}}
onClick={() => setSelectedTemplateId(null)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
setSelectedTemplateId(null)
}
}}
role="radio"
aria-checked={selectedTemplateId === null}
tabIndex={0}
>
<div style={styles.templateName}>{t('template.blankProject')}</div>
<div style={styles.templateDescription}>{t('template.blankProjectDescription')}</div>
</div>
{/* Template Options */}
{templates.map((template) => (
<div
key={template.id}
style={{
...styles.templateCard,
...(selectedTemplateId === template.id ? styles.templateCardSelected : {}),
}}
onClick={() => setSelectedTemplateId(template.id)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
setSelectedTemplateId(template.id)
}
}}
role="radio"
aria-checked={selectedTemplateId === template.id}
tabIndex={0}
>
<div style={styles.templateHeader}>
<div style={styles.templateName}>{template.name}</div>
{template.is_public && (
<span style={styles.templatePublicBadge}>{t('template.publicTemplate')}</span>
)}
</div>
{template.description && (
<div style={styles.templateDescription}>{template.description}</div>
)}
<div style={styles.templateMeta}>
<span>{t('template.statusCount', { count: template.task_statuses.length })}</span>
{template.custom_fields.length > 0 && (
<span>{t('template.fieldCount', { count: template.custom_fields.length })}</span>
)}
</div>
</div>
))}
</div>
)}
<label htmlFor="project-title" style={styles.visuallyHidden}>
{t('fields.title')}
</label>
@@ -267,16 +394,21 @@ export default function Projects() {
onChange={(e) => setNewProject({ ...newProject, description: e.target.value })}
style={styles.textarea}
/>
<label style={styles.label}>{t('securityLevel.label')}</label>
<select
value={newProject.security_level}
onChange={(e) => setNewProject({ ...newProject, security_level: e.target.value })}
style={styles.select}
>
<option value="public">{t('securityLevel.public')}</option>
<option value="department">{t('securityLevel.department')}</option>
<option value="confidential">{t('securityLevel.confidential')}</option>
</select>
{/* Only show security level for blank projects */}
{!selectedTemplateId && (
<>
<label style={styles.label}>{t('securityLevel.label')}</label>
<select
value={newProject.security_level}
onChange={(e) => setNewProject({ ...newProject, security_level: e.target.value })}
style={styles.select}
>
<option value="public">{t('securityLevel.public')}</option>
<option value="department">{t('securityLevel.department')}</option>
<option value="confidential">{t('securityLevel.confidential')}</option>
</select>
</>
)}
<div style={styles.modalActions}>
<button onClick={() => setShowCreateModal(false)} style={styles.cancelButton}>
{t('common:buttons.cancel')}
@@ -442,8 +574,10 @@ const styles: { [key: string]: React.CSSProperties } = {
backgroundColor: 'white',
padding: '24px',
borderRadius: '8px',
width: '400px',
width: '560px',
maxWidth: '90%',
maxHeight: '90vh',
overflowY: 'auto',
},
modalTitle: {
marginBottom: '16px',
@@ -548,4 +682,62 @@ const styles: { [key: string]: React.CSSProperties } = {
borderRadius: '4px',
cursor: 'pointer',
},
templatesLoading: {
padding: '16px',
textAlign: 'center',
color: '#666',
fontSize: '14px',
marginBottom: '12px',
},
templateGrid: {
display: 'grid',
gridTemplateColumns: 'repeat(2, 1fr)',
gap: '12px',
marginBottom: '16px',
},
templateCard: {
padding: '12px',
border: '2px solid #e5e7eb',
borderRadius: '8px',
cursor: 'pointer',
transition: 'border-color 0.2s, background-color 0.2s',
backgroundColor: '#fff',
},
templateCardSelected: {
borderColor: '#0066cc',
backgroundColor: '#f0f7ff',
},
templateHeader: {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-start',
gap: '8px',
},
templateName: {
fontSize: '14px',
fontWeight: 600,
color: '#333',
marginBottom: '4px',
},
templateDescription: {
fontSize: '12px',
color: '#666',
marginBottom: '8px',
lineHeight: 1.4,
},
templateMeta: {
display: 'flex',
gap: '8px',
fontSize: '11px',
color: '#888',
},
templatePublicBadge: {
padding: '2px 6px',
backgroundColor: '#e8f5e9',
color: '#2e7d32',
borderRadius: '4px',
fontSize: '10px',
fontWeight: 500,
whiteSpace: 'nowrap',
},
}

View File

@@ -30,6 +30,7 @@ interface Task {
subtask_count: number
parent_task_id: string | null
custom_values?: CustomValueResponse[]
version?: number
}
interface TaskStatus {
@@ -49,6 +50,7 @@ type ViewMode = 'list' | 'kanban' | 'calendar' | 'gantt'
const VIEW_MODE_STORAGE_KEY = 'tasks-view-mode'
const COLUMN_VISIBILITY_STORAGE_KEY = 'tasks-column-visibility'
const MOBILE_BREAKPOINT = 768
// Get column visibility settings from localStorage
const getColumnVisibility = (projectId: string): Record<string, boolean> => {
@@ -66,7 +68,7 @@ const saveColumnVisibility = (projectId: string, visibility: Record<string, bool
}
export default function Tasks() {
const { t } = useTranslation('tasks')
const { t, i18n } = useTranslation('tasks')
const { projectId } = useParams()
const navigate = useNavigate()
const { subscribeToProject, unsubscribeFromProject, addTaskEventListener, isConnected } = useProjectSync()
@@ -75,6 +77,7 @@ export default function Tasks() {
const [statuses, setStatuses] = useState<TaskStatus[]>([])
const [loading, setLoading] = useState(true)
const [showCreateModal, setShowCreateModal] = useState(false)
const [isMobile, setIsMobile] = useState(false)
const [viewMode, setViewMode] = useState<ViewMode>(() => {
const saved = localStorage.getItem(VIEW_MODE_STORAGE_KEY)
return (saved === 'kanban' || saved === 'list' || saved === 'calendar' || saved === 'gantt') ? saved : 'list'
@@ -105,6 +108,17 @@ export default function Tasks() {
const columnMenuRef = useRef<HTMLDivElement>(null)
const createModalOverlayRef = useRef<HTMLDivElement>(null)
// Detect mobile viewport
useEffect(() => {
const checkMobile = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
checkMobile()
window.addEventListener('resize', checkMobile)
return () => window.removeEventListener('resize', checkMobile)
}, [])
useEffect(() => {
loadData()
}, [projectId])
@@ -464,20 +478,112 @@ export default function Tasks() {
}
}
const getPriorityStyle = (priority: string): React.CSSProperties => {
const getPriorityColor = (priority: string): string => {
const colors: { [key: string]: string } = {
low: '#808080',
medium: '#0066cc',
high: '#ff9800',
urgent: '#f44336',
}
return colors[priority] || colors.medium
}
const getPriorityStyle = (priority: string): React.CSSProperties => {
return {
width: '4px',
backgroundColor: colors[priority] || colors.medium,
backgroundColor: getPriorityColor(priority),
borderRadius: '2px',
}
}
// Format date according to locale
const formatDate = (dateString: string): string => {
const date = new Date(dateString)
return date.toLocaleDateString(i18n.language, {
year: 'numeric',
month: 'short',
day: 'numeric',
})
}
// Render task card for mobile view
const renderTaskCard = (task: Task) => (
<div
key={task.id}
style={styles.taskCard}
onClick={() => handleTaskClick(task)}
>
<div style={styles.taskCardHeader}>
<div
style={{
...styles.taskCardPriority,
backgroundColor: getPriorityColor(task.priority),
}}
/>
<h3 style={styles.taskCardTitle}>{task.title}</h3>
</div>
{task.description && (
<p style={styles.taskCardDescription}>
{task.description.length > 100
? task.description.substring(0, 100) + '...'
: task.description}
</p>
)}
<div style={styles.taskCardMeta}>
{task.assignee_name && (
<span style={styles.taskCardAssignee}>{task.assignee_name}</span>
)}
{task.due_date && (
<span style={styles.taskCardDueDate}>
{t('fields.dueDate')}: {formatDate(task.due_date)}
</span>
)}
</div>
<div style={styles.taskCardFooter}>
<div
style={{
...styles.taskCardStatus,
backgroundColor: task.status_color || '#e0e0e0',
}}
>
{task.status_name || t('status.noStatus')}
</div>
{task.subtask_count > 0 && (
<span style={styles.taskCardSubtasks}>
{t('subtasks.count', { count: task.subtask_count })}
</span>
)}
{task.time_estimate && (
<span style={styles.taskCardEstimate}>
{t('fields.hours', { count: task.time_estimate })}
</span>
)}
</div>
{/* Mobile status change action */}
<div style={styles.taskCardActions}>
<select
value={task.status_id || ''}
onChange={(e) => {
e.stopPropagation()
handleStatusChange(task.id, e.target.value)
}}
onClick={(e) => e.stopPropagation()}
style={styles.taskCardStatusSelect}
>
{statuses.map((status) => (
<option key={status.id} value={status.id}>
{status.name}
</option>
))}
</select>
</div>
</div>
)
if (loading) {
return (
<div style={styles.container}>
@@ -494,7 +600,7 @@ export default function Tasks() {
}
return (
<div style={styles.container}>
<div style={isMobile ? styles.containerMobile : styles.container}>
<div style={styles.breadcrumb}>
<span onClick={() => navigate('/spaces')} style={styles.breadcrumbLink}>
{t('common:nav.spaces')}
@@ -510,65 +616,70 @@ export default function Tasks() {
<span>{project?.title}</span>
</div>
<div style={styles.header}>
<div style={isMobile ? styles.headerMobile : styles.header}>
<div style={styles.titleContainer}>
<h1 style={styles.title}>{t('title')}</h1>
<h1 style={isMobile ? styles.titleMobile : styles.title}>{t('title')}</h1>
{isConnected ? (
<span style={styles.liveIndicator} title={t('common:labels.active')}>
Live
{'\u25CF'} {t('common:labels.live')}
</span>
) : projectId ? (
<span style={styles.offlineIndicator} title={t('common:labels.inactive')}>
Offline
{'\u25CB'} {t('common:labels.offline')}
</span>
) : null}
</div>
<div style={styles.headerActions}>
<div style={isMobile ? styles.headerActionsMobile : styles.headerActions}>
{/* View Toggle */}
<div style={styles.viewToggle}>
<div style={isMobile ? styles.viewToggleMobile : styles.viewToggle}>
<button
onClick={() => setViewMode('list')}
style={{
...styles.viewButton,
...(isMobile ? styles.viewButtonMobile : {}),
...(viewMode === 'list' ? styles.viewButtonActive : {}),
}}
aria-label={t('views.list')}
>
{t('views.list')}
{isMobile ? '\u2630' : t('views.list')}
</button>
<button
onClick={() => setViewMode('kanban')}
style={{
...styles.viewButton,
...(isMobile ? styles.viewButtonMobile : {}),
...(viewMode === 'kanban' ? styles.viewButtonActive : {}),
}}
aria-label={t('views.kanban')}
>
{t('views.kanban')}
{isMobile ? '\u25A6' : t('views.kanban')}
</button>
<button
onClick={() => setViewMode('calendar')}
style={{
...styles.viewButton,
...(isMobile ? styles.viewButtonMobile : {}),
...(viewMode === 'calendar' ? styles.viewButtonActive : {}),
}}
aria-label={t('views.calendar')}
>
{t('views.calendar')}
</button>
<button
onClick={() => setViewMode('gantt')}
style={{
...styles.viewButton,
...(viewMode === 'gantt' ? styles.viewButtonActive : {}),
}}
aria-label={t('views.gantt')}
>
{t('views.gantt')}
{isMobile ? '\u25A1' : t('views.calendar')}
</button>
{!isMobile && (
<button
onClick={() => setViewMode('gantt')}
style={{
...styles.viewButton,
...(viewMode === 'gantt' ? styles.viewButtonActive : {}),
}}
aria-label={t('views.gantt')}
>
{t('views.gantt')}
</button>
)}
</div>
{/* Column Visibility Toggle - only show when there are custom fields and in list view */}
{viewMode === 'list' && customFields.length > 0 && (
{!isMobile && viewMode === 'list' && customFields.length > 0 && (
<div style={styles.columnMenuContainer} ref={columnMenuRef}>
<button
onClick={() => setShowColumnMenu(!showColumnMenu)}
@@ -598,97 +709,119 @@ export default function Tasks() {
)}
</div>
)}
{!isMobile && (
<button
onClick={() => navigate(`/projects/${projectId}/settings`)}
style={styles.settingsButton}
aria-label={t('common:nav.settings')}
>
{t('common:nav.settings')}
</button>
)}
<button
onClick={() => navigate(`/projects/${projectId}/settings`)}
style={styles.settingsButton}
aria-label={t('common:nav.settings')}
onClick={() => setShowCreateModal(true)}
style={isMobile ? styles.createButtonMobile : styles.createButton}
>
{t('common:nav.settings')}
</button>
<button onClick={() => setShowCreateModal(true)} style={styles.createButton}>
+ {t('createTask')}
{isMobile ? '+' : `+ ${t('createTask')}`}
</button>
</div>
</div>
{/* Conditional rendering based on view mode */}
{viewMode === 'list' && (
<div style={styles.taskList}>
{tasks.map((task) => (
<div
key={task.id}
style={styles.taskRow}
onClick={() => handleTaskClick(task)}
>
<div style={getPriorityStyle(task.priority)} />
<div style={styles.taskContent}>
<div style={styles.taskTitle}>{task.title}</div>
<div style={styles.taskMeta}>
{task.assignee_name && (
<span style={styles.assignee}>{task.assignee_name}</span>
)}
{task.due_date && (
<span style={styles.dueDate}>
Due: {new Date(task.due_date).toLocaleDateString()}
</span>
)}
{task.time_estimate && (
<span style={styles.timeEstimate}>
Est: {task.time_estimate}h
</span>
)}
{task.subtask_count > 0 && (
<span style={styles.subtaskCount}>
{task.subtask_count} subtasks
</span>
)}
{/* Display visible custom field values */}
{task.custom_values &&
task.custom_values
.filter((cv) => isColumnVisible(cv.field_id))
.map((cv) => (
<span key={cv.field_id} style={styles.customValueBadge}>
{cv.field_name}: {cv.display_value || cv.value || '-'}
</span>
))}
</div>
isMobile ? (
// Mobile card view
<div style={styles.taskCardList}>
{tasks.map(renderTaskCard)}
{tasks.length === 0 && (
<div style={styles.empty}>
<p>{t('empty.description')}</p>
</div>
<select
value={task.status_id || ''}
onChange={(e) => {
e.stopPropagation()
handleStatusChange(task.id, e.target.value)
}}
onClick={(e) => e.stopPropagation()}
style={{
...styles.statusSelect,
backgroundColor: task.status_color || '#f5f5f5',
}}
>
{statuses.map((status) => (
<option key={status.id} value={status.id}>
{status.name}
</option>
))}
</select>
</div>
))}
)}
</div>
) : (
// Desktop list view with horizontal scroll for wide tables
<div style={styles.tableWrapper}>
<div style={styles.taskList}>
{tasks.map((task) => (
<div
key={task.id}
style={styles.taskRow}
onClick={() => handleTaskClick(task)}
>
<div style={getPriorityStyle(task.priority)} />
<div style={styles.taskContent}>
<div style={styles.taskTitle}>{task.title}</div>
<div style={styles.taskMeta}>
{task.assignee_name && (
<span style={styles.assignee}>{task.assignee_name}</span>
)}
{task.due_date && (
<span style={styles.dueDate}>
{t('fields.dueDate')}: {formatDate(task.due_date)}
</span>
)}
{task.time_estimate && (
<span style={styles.timeEstimate}>
{t('fields.hours', { count: task.time_estimate })}
</span>
)}
{task.subtask_count > 0 && (
<span style={styles.subtaskCount}>
{t('subtasks.count', { count: task.subtask_count })}
</span>
)}
{/* Display visible custom field values */}
{task.custom_values &&
task.custom_values
.filter((cv) => isColumnVisible(cv.field_id))
.map((cv) => (
<span key={cv.field_id} style={styles.customValueBadge}>
{cv.field_name}: {cv.display_value || cv.value || '-'}
</span>
))}
</div>
</div>
<select
value={task.status_id || ''}
onChange={(e) => {
e.stopPropagation()
handleStatusChange(task.id, e.target.value)
}}
onClick={(e) => e.stopPropagation()}
style={{
...styles.statusSelect,
backgroundColor: task.status_color || '#f5f5f5',
}}
>
{statuses.map((status) => (
<option key={status.id} value={status.id}>
{status.name}
</option>
))}
</select>
</div>
))}
{tasks.length === 0 && (
<div style={styles.empty}>
<p>{t('empty.description')}</p>
{tasks.length === 0 && (
<div style={styles.empty}>
<p>{t('empty.description')}</p>
</div>
)}
</div>
)}
</div>
</div>
)
)}
{viewMode === 'kanban' && (
<KanbanBoard
tasks={tasks}
statuses={statuses}
onStatusChange={handleStatusChange}
onTaskClick={handleTaskClick}
/>
<div style={styles.kanbanWrapper}>
<KanbanBoard
tasks={tasks}
statuses={statuses}
onStatusChange={handleStatusChange}
onTaskClick={handleTaskClick}
/>
</div>
)}
{viewMode === 'calendar' && projectId && (
@@ -700,7 +833,7 @@ export default function Tasks() {
/>
)}
{viewMode === 'gantt' && projectId && (
{viewMode === 'gantt' && projectId && !isMobile && (
<GanttChart
projectId={projectId}
tasks={tasks}
@@ -720,7 +853,7 @@ export default function Tasks() {
aria-modal="true"
aria-labelledby="create-task-title"
>
<div style={styles.modal}>
<div style={isMobile ? styles.modalMobile : styles.modal}>
<h2 id="create-task-title" style={styles.modalTitle}>{t('createTask')}</h2>
<label htmlFor="task-title" style={styles.visuallyHidden}>
{t('fields.title')}
@@ -786,7 +919,7 @@ export default function Tasks() {
type="number"
min="0"
step="0.5"
placeholder="e.g., 2.5"
placeholder={t('fields.estimatedHours')}
value={newTask.time_estimate}
onChange={(e) => setNewTask({ ...newTask, time_estimate: e.target.value })}
style={styles.input}
@@ -860,14 +993,22 @@ const styles: { [key: string]: React.CSSProperties } = {
maxWidth: '1200px',
margin: '0 auto',
},
containerMobile: {
padding: '16px',
maxWidth: '100%',
margin: '0 auto',
},
breadcrumb: {
marginBottom: '16px',
fontSize: '14px',
color: '#666',
overflowX: 'auto',
whiteSpace: 'nowrap',
},
breadcrumbLink: {
color: '#0066cc',
cursor: 'pointer',
padding: '4px',
},
breadcrumbSeparator: {
margin: '0 8px',
@@ -877,6 +1018,14 @@ const styles: { [key: string]: React.CSSProperties } = {
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '24px',
flexWrap: 'wrap',
gap: '12px',
},
headerMobile: {
display: 'flex',
flexDirection: 'column',
gap: '12px',
marginBottom: '16px',
},
titleContainer: {
display: 'flex',
@@ -888,6 +1037,11 @@ const styles: { [key: string]: React.CSSProperties } = {
fontWeight: 600,
margin: 0,
},
titleMobile: {
fontSize: '20px',
fontWeight: 600,
margin: 0,
},
liveIndicator: {
display: 'inline-flex',
alignItems: 'center',
@@ -915,6 +1069,14 @@ const styles: { [key: string]: React.CSSProperties } = {
display: 'flex',
gap: '12px',
alignItems: 'center',
flexWrap: 'wrap',
},
headerActionsMobile: {
display: 'flex',
gap: '8px',
alignItems: 'center',
justifyContent: 'space-between',
width: '100%',
},
viewToggle: {
display: 'flex',
@@ -922,14 +1084,28 @@ const styles: { [key: string]: React.CSSProperties } = {
borderRadius: '6px',
overflow: 'hidden',
},
viewToggleMobile: {
display: 'flex',
border: '1px solid #ddd',
borderRadius: '6px',
overflow: 'hidden',
flex: 1,
},
viewButton: {
padding: '8px 16px',
padding: '10px 16px',
backgroundColor: 'white',
border: 'none',
cursor: 'pointer',
fontSize: '14px',
color: '#666',
transition: 'background-color 0.2s, color 0.2s',
minHeight: '44px',
minWidth: '44px',
},
viewButtonMobile: {
flex: 1,
padding: '12px 8px',
fontSize: '16px',
},
viewButtonActive: {
backgroundColor: '#0066cc',
@@ -943,6 +1119,8 @@ const styles: { [key: string]: React.CSSProperties } = {
borderRadius: '6px',
cursor: 'pointer',
fontSize: '14px',
minHeight: '44px',
minWidth: '44px',
},
createButton: {
padding: '10px 20px',
@@ -953,12 +1131,38 @@ const styles: { [key: string]: React.CSSProperties } = {
cursor: 'pointer',
fontSize: '14px',
fontWeight: 500,
minHeight: '44px',
minWidth: '44px',
},
createButtonMobile: {
padding: '12px 20px',
backgroundColor: '#0066cc',
color: 'white',
border: 'none',
borderRadius: '6px',
cursor: 'pointer',
fontSize: '18px',
fontWeight: 600,
minHeight: '48px',
minWidth: '48px',
},
// Table wrapper for horizontal scroll
tableWrapper: {
overflowX: 'auto',
WebkitOverflowScrolling: 'touch',
},
taskList: {
backgroundColor: 'white',
borderRadius: '8px',
boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
overflow: 'hidden',
minWidth: '600px', // Ensure minimum width for horizontal scroll
},
// Kanban wrapper for horizontal scroll
kanbanWrapper: {
overflowX: 'auto',
WebkitOverflowScrolling: 'touch',
paddingBottom: '16px',
},
taskRow: {
display: 'flex',
@@ -968,20 +1172,26 @@ const styles: { [key: string]: React.CSSProperties } = {
gap: '12px',
cursor: 'pointer',
transition: 'background-color 0.15s ease',
minHeight: '60px',
},
taskContent: {
flex: 1,
minWidth: 0, // Enable text truncation
},
taskTitle: {
fontSize: '14px',
fontWeight: 500,
marginBottom: '4px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
taskMeta: {
display: 'flex',
gap: '12px',
fontSize: '12px',
color: '#666',
flexWrap: 'wrap',
},
assignee: {
backgroundColor: '#f0f0f0',
@@ -996,12 +1206,103 @@ const styles: { [key: string]: React.CSSProperties } = {
color: '#767676', // WCAG AA compliant
},
statusSelect: {
padding: '6px 12px',
padding: '8px 12px',
border: 'none',
borderRadius: '4px',
fontSize: '12px',
cursor: 'pointer',
color: 'white',
minHeight: '36px',
minWidth: '100px',
},
// Mobile card view styles
taskCardList: {
display: 'flex',
flexDirection: 'column',
gap: '12px',
},
taskCard: {
backgroundColor: 'white',
borderRadius: '8px',
boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
padding: '16px',
cursor: 'pointer',
},
taskCardHeader: {
display: 'flex',
alignItems: 'flex-start',
gap: '12px',
marginBottom: '8px',
},
taskCardPriority: {
width: '4px',
height: '24px',
borderRadius: '2px',
flexShrink: 0,
},
taskCardTitle: {
margin: 0,
fontSize: '16px',
fontWeight: 500,
lineHeight: 1.4,
flex: 1,
},
taskCardDescription: {
margin: '0 0 12px 0',
fontSize: '14px',
color: '#666',
lineHeight: 1.4,
},
taskCardMeta: {
display: 'flex',
flexWrap: 'wrap',
gap: '8px',
marginBottom: '12px',
fontSize: '13px',
},
taskCardAssignee: {
backgroundColor: '#e3f2fd',
color: '#1565c0',
padding: '4px 8px',
borderRadius: '4px',
},
taskCardDueDate: {
color: '#666',
},
taskCardFooter: {
display: 'flex',
alignItems: 'center',
gap: '8px',
flexWrap: 'wrap',
},
taskCardStatus: {
padding: '4px 10px',
borderRadius: '4px',
fontSize: '12px',
fontWeight: 500,
color: 'white',
},
taskCardSubtasks: {
fontSize: '12px',
color: '#767676',
},
taskCardEstimate: {
fontSize: '12px',
color: '#0066cc',
},
taskCardActions: {
marginTop: '12px',
paddingTop: '12px',
borderTop: '1px solid #eee',
},
taskCardStatusSelect: {
width: '100%',
padding: '12px',
border: '1px solid #ddd',
borderRadius: '6px',
fontSize: '14px',
backgroundColor: 'white',
minHeight: '48px',
},
empty: {
textAlign: 'center',
@@ -1025,36 +1326,47 @@ const styles: { [key: string]: React.CSSProperties } = {
justifyContent: 'center',
alignItems: 'center',
zIndex: 1000,
padding: '16px',
},
modal: {
backgroundColor: 'white',
padding: '24px',
borderRadius: '8px',
width: '450px',
maxWidth: '90%',
maxWidth: '100%',
maxHeight: '90vh',
overflowY: 'auto',
},
modalMobile: {
backgroundColor: 'white',
padding: '20px',
borderRadius: '12px',
width: '100%',
maxWidth: '100%',
maxHeight: '85vh',
overflowY: 'auto',
},
modalTitle: {
marginBottom: '16px',
},
input: {
width: '100%',
padding: '10px',
padding: '12px',
marginBottom: '12px',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '14px',
borderRadius: '6px',
fontSize: '16px',
boxSizing: 'border-box',
minHeight: '48px',
},
textarea: {
width: '100%',
padding: '10px',
padding: '12px',
marginBottom: '12px',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '14px',
minHeight: '80px',
borderRadius: '6px',
fontSize: '16px',
minHeight: '100px',
resize: 'vertical',
boxSizing: 'border-box',
},
@@ -1066,12 +1378,13 @@ const styles: { [key: string]: React.CSSProperties } = {
},
select: {
width: '100%',
padding: '10px',
padding: '12px',
marginBottom: '12px',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '14px',
borderRadius: '6px',
fontSize: '16px',
boxSizing: 'border-box',
minHeight: '48px',
},
fieldSpacer: {
height: '12px',
@@ -1083,19 +1396,25 @@ const styles: { [key: string]: React.CSSProperties } = {
marginTop: '16px',
},
cancelButton: {
padding: '10px 20px',
padding: '12px 20px',
backgroundColor: '#f5f5f5',
border: '1px solid #ddd',
borderRadius: '4px',
borderRadius: '6px',
cursor: 'pointer',
fontSize: '14px',
minHeight: '48px',
minWidth: '80px',
},
submitButton: {
padding: '10px 20px',
padding: '12px 20px',
backgroundColor: '#0066cc',
color: 'white',
border: 'none',
borderRadius: '4px',
borderRadius: '6px',
cursor: 'pointer',
fontSize: '14px',
minHeight: '48px',
minWidth: '80px',
},
customFieldsDivider: {
height: '1px',
@@ -1137,6 +1456,7 @@ const styles: { [key: string]: React.CSSProperties } = {
display: 'flex',
alignItems: 'center',
gap: '6px',
minHeight: '44px',
},
columnMenuDropdown: {
position: 'absolute',
@@ -1163,14 +1483,15 @@ const styles: { [key: string]: React.CSSProperties } = {
columnMenuItem: {
display: 'flex',
alignItems: 'center',
padding: '10px 16px',
padding: '12px 16px',
cursor: 'pointer',
transition: 'background-color 0.15s',
gap: '10px',
minHeight: '44px',
},
columnCheckbox: {
width: '16px',
height: '16px',
width: '18px',
height: '18px',
cursor: 'pointer',
},
columnLabel: {

View File

@@ -1,7 +1,11 @@
import axios from 'axios'
// API base URL - using legacy routes until v1 migration is complete
// TODO: Switch to /api/v1 when all routes are migrated
const API_BASE_URL = '/api'
const api = axios.create({
baseURL: '/api',
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},

View File

@@ -0,0 +1,75 @@
import api from './api'
export interface ProjectMember {
id: string
project_id: string
user_id: string
role: 'member' | 'admin'
joined_at: string
user: {
id: string
name: string
email: string
}
}
export interface ProjectMemberListResponse {
members: ProjectMember[]
total: number
}
export interface AddMemberRequest {
user_id: string
role: 'member' | 'admin'
}
export interface UpdateMemberRoleRequest {
role: 'member' | 'admin'
}
export const projectMembersApi = {
/**
* List all members of a project
*/
list: async (projectId: string): Promise<ProjectMemberListResponse> => {
const response = await api.get<ProjectMemberListResponse>(
`/projects/${projectId}/members`
)
return response.data
},
/**
* Add a new member to a project
*/
add: async (projectId: string, data: AddMemberRequest): Promise<ProjectMember> => {
const response = await api.post<ProjectMember>(
`/projects/${projectId}/members`,
data
)
return response.data
},
/**
* Update a member's role
*/
updateRole: async (
projectId: string,
memberId: string,
data: UpdateMemberRoleRequest
): Promise<ProjectMember> => {
const response = await api.patch<ProjectMember>(
`/projects/${projectId}/members/${memberId}`,
data
)
return response.data
},
/**
* Remove a member from a project
*/
remove: async (projectId: string, memberId: string): Promise<void> => {
await api.delete(`/projects/${projectId}/members/${memberId}`)
},
}
export default projectMembersApi