This commit is contained in:
lubiana 2025-07-28 19:54:33 +02:00
commit ad8c238e78
Signed by: lubiana
SSH key fingerprint: SHA256:vW1EA0fRR3Fw+dD/sM0K+x3Il2gSry6YRYHqOeQwrfk
53 changed files with 10091 additions and 0 deletions

24
frontend/.gitignore vendored Normal file
View file

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

69
frontend/README.md Normal file
View file

@ -0,0 +1,69 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
...tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
...tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
...tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

23
frontend/eslint.config.js Normal file
View file

@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { globalIgnores } from 'eslint/config'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
frontend/index.html Normal file
View file

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cheekylist</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

5672
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

44
frontend/package.json Normal file
View file

@ -0,0 +1,44 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/colors": "^3.0.0",
"@radix-ui/react-checkbox": "^1.3.2",
"@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-dropdown-menu": "^2.1.15",
"@radix-ui/react-icons": "^1.3.2",
"@radix-ui/react-select": "^2.2.5",
"@radix-ui/react-switch": "^1.2.5",
"@radix-ui/react-tooltip": "^1.2.7",
"@radix-ui/themes": "^3.2.1",
"@tailwindcss/vite": "^4.1.11",
"@types/react-datepicker": "^6.2.0",
"react": "^19.1.0",
"react-datepicker": "^8.4.0",
"react-dom": "^19.1.0",
"react-router-dom": "^7.7.0",
"tailwindcss": "^4.1.11"
},
"devDependencies": {
"@eslint/js": "^9.30.1",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react-swc": "^3.10.2",
"eslint": "^9.30.1",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0",
"typescript": "~5.8.3",
"typescript-eslint": "^8.35.1",
"vite": "^7.0.4",
"vite-plugin-compression2": "^2.2.0"
}
}

View file

@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<text x="50" y="70" font-family="Arial, sans-serif" font-size="60" text-anchor="middle" fill="#000000">📝</text>
</svg>

After

Width:  |  Height:  |  Size: 187 B

18
frontend/src/App.tsx Normal file
View file

@ -0,0 +1,18 @@
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import Home from './pages/Home'
import Checklist from './pages/Checklist'
function App() {
return (
<Router>
<div className="App">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/:uuid" element={<Checklist />} />
</Routes>
</div>
</Router>
)
}
export default App

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4 KiB

View file

@ -0,0 +1,388 @@
import { useState, useRef, useEffect } from 'react'
import type { ChecklistItem as ChecklistItemType } from '../types'
import DependencyManager from './DependencyManager'
import { DateConstraintManager } from './DateConstraintManager'
import { Checkbox, Flex, Box, Text, IconButton, Badge, Tooltip } from '@radix-ui/themes'
import { LockClosedIcon, TrashIcon, ClockIcon, LinkBreak2Icon } from '@radix-ui/react-icons'
interface ChecklistItemProps {
item: ChecklistItemType
onUpdate: (id: number, updates: Partial<ChecklistItemType>) => Promise<void>
onDelete: (id: number) => Promise<void>
onLock: (id: number, user: string) => Promise<void>
depth?: number
children?: ChecklistItemType[]
allItems?: ChecklistItemType[]
}
export default function ChecklistItem({
item,
onUpdate,
onDelete,
onLock,
depth = 0,
children = [],
allItems = []
}: ChecklistItemProps) {
const [isEditing, setIsEditing] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const [isDependencyModalOpen, setIsDependencyModalOpen] = useState(false)
const [isDateConstraintModalOpen, setIsDateConstraintModalOpen] = useState(false)
const [userName, setUserName] = useState('')
const contentRef = useRef<HTMLDivElement>(null)
const isLocked = item.locked_by && item.lock_until && new Date(item.lock_until) > new Date()
const isLockedByMe = isLocked && item.locked_by === userName
// Check if all dependencies are completed
const dependenciesCompleted = item.dependencies?.every(depId => {
const depItem = allItems.find(i => i.id === depId)
return depItem?.checked
}) ?? true
// Check date constraints
const now = new Date()
const notBeforeDate = item.not_before ? new Date(item.not_before) : null
const notAfterDate = item.not_after ? new Date(item.not_after) : null
const dateConstraintsMet = (!notBeforeDate || now >= notBeforeDate) && (!notAfterDate || now <= notAfterDate)
// Check if item can be completed (all dependencies met and date constraints met)
const canComplete = (dependenciesCompleted && dateConstraintsMet) || item.checked
// Get dependency items for display
const dependencyItems = item.dependencies?.map(depId =>
allItems.find(i => i.id === depId)
).filter(Boolean) ?? []
useEffect(() => {
// Generate a random user name if not set
if (!userName) {
const randomName = `user_${Math.random().toString(36).substr(2, 9)}`
setUserName(randomName)
}
}, [userName])
useEffect(() => {
if (isEditing && contentRef.current) {
contentRef.current.focus()
// Select all text when entering edit mode
const range = document.createRange()
range.selectNodeContents(contentRef.current)
const selection = window.getSelection()
selection?.removeAllRanges()
selection?.addRange(range)
}
}, [isEditing])
const handleEdit = async () => {
if (isLocked && !isLockedByMe) {
alert('This item is being edited by someone else')
return
}
if (!isLockedByMe) {
try {
await onLock(item.id, userName)
} catch (error) {
console.error('Failed to lock item:', error)
return
}
}
setIsEditing(true)
}
const handleSave = async () => {
const newContent = contentRef.current?.textContent?.trim() || ''
if (newContent === '') return
try {
await onUpdate(item.id, { content: newContent })
setIsEditing(false)
} catch (error) {
console.error('Failed to update item:', error)
}
}
const handleCancel = () => {
if (contentRef.current) {
contentRef.current.textContent = item.content
}
setIsEditing(false)
}
const handleDelete = async () => {
if (confirm('Are you sure you want to delete this item?')) {
try {
setIsDeleting(true)
await onDelete(item.id)
} catch (error) {
console.error('Failed to delete item:', error)
} finally {
setIsDeleting(false)
}
}
}
const handleToggleCheck = async () => {
// Don't allow unchecking if already checked
if (item.checked) {
try {
await onUpdate(item.id, { checked: false })
} catch (error) {
console.error('Failed to uncheck item:', error)
}
return
}
// Check if dependencies are met before allowing completion
if (!dependenciesCompleted) {
alert(`Cannot complete this item. The following dependencies must be completed first:\n\n${dependencyItems.map(dep => `${dep?.content}`).join('\n')}`)
return
}
// Check if date constraints are met
if (!dateConstraintsMet) {
let message = 'Cannot complete this item due to date constraints:\n\n'
if (notBeforeDate && now < notBeforeDate) {
message += `• Cannot complete before ${notBeforeDate.toLocaleString()}\n`
}
if (notAfterDate && now > notAfterDate) {
message += `• Cannot complete after ${notAfterDate.toLocaleString()}\n`
}
alert(message)
return
}
try {
await onUpdate(item.id, { checked: true })
} catch (error) {
console.error('Failed to toggle item:', error)
if (error instanceof Error && error.message.includes('cannot complete item:')) {
alert(error.message)
}
}
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
e.preventDefault()
handleSave()
} else if (e.key === 'Escape') {
e.preventDefault()
handleCancel()
}
}
const handleBlur = () => {
// Small delay to allow for button clicks
setTimeout(() => {
if (isEditing) {
handleSave()
}
}, 100)
}
const handleDateConstraintSave = async (notBefore?: string, notAfter?: string) => {
try {
await onUpdate(item.id, { not_before: notBefore, not_after: notAfter })
setIsDateConstraintModalOpen(false)
} catch (error) {
console.error('Failed to update date constraints:', error)
}
}
return (
<Box asChild>
<li style={{ listStyle: 'none' }}>
<Flex
gap="3"
align="start"
p="3"
className="group rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-all duration-200 border border-transparent hover:border-gray-200 dark:hover:border-gray-700"
>
<Box mt="1">
<Checkbox
checked={item.checked}
onCheckedChange={handleToggleCheck}
disabled={Boolean(isLocked && !isLockedByMe) || (!item.checked && !canComplete)}
size="2"
/>
</Box>
<Box style={{ flex: 1, minWidth: 0 }}>
{isEditing ? (
<Box
ref={contentRef}
contentEditable={true}
suppressContentEditableWarning={true}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
className="px-3 py-2 border-2 border-blue-500 rounded-md focus:ring-2 focus:ring-blue-200 dark:focus:ring-blue-800 bg-white dark:bg-gray-800 shadow-sm outline-none"
style={{ minHeight: '28px' }}
>
{item.content}
</Box>
) : (
<Text
size="2"
onClick={handleEdit}
className={`cursor-pointer hover:text-blue-600 dark:hover:text-blue-400 ${
item.checked ? 'line-through opacity-75' : ''
} ${
!item.checked && !canComplete ? 'opacity-60' : ''
}`}
color={item.checked ? "gray" : undefined}
>
{item.content}
</Text>
)}
{/* Consolidated status indicators - only show when item cannot be completed */}
{!item.checked && !canComplete && (
<Flex gap="1" mt="1" align="center">
{/* Single consolidated status indicator */}
<Badge
color="orange"
variant="soft"
size="1"
className="flex items-center gap-1 opacity-80"
>
<span className="text-xs"></span>
<span className="text-xs font-medium">
{dependencyItems.length > 0 && !dateConstraintsMet
? `${dependencyItems.length} deps + time locked`
: dependencyItems.length > 0
? `${dependencyItems.length} deps`
: 'Time locked'
}
</span>
</Badge>
</Flex>
)}
</Box>
<Flex gap="2" align="center" className="sm:opacity-0 sm:group-hover:opacity-100 transition-opacity duration-200">
{/* Only show essential status indicators in hover area */}
{!item.checked && !canComplete && (
<Tooltip content={
<Box p="3" className="max-w-xs">
<Flex direction="column" gap="2">
<Text size="2" weight="medium" color="gray">
Cannot complete this item:
</Text>
{dependencyItems.length > 0 && (
<Flex gap="2" align="center">
<span className="text-orange-500">🔗</span>
<Text size="1" color="orange">
Depends on: {dependencyItems.map(dep => dep?.content).join(', ')}
</Text>
</Flex>
)}
{!dateConstraintsMet && (
<Flex gap="2" align="center">
<span className="text-red-500">🕐</span>
<Text size="1" color="red">
{notBeforeDate && now < notBeforeDate
? `Cannot complete before ${notBeforeDate.toLocaleString()}`
: notAfterDate && now > notAfterDate
? `Cannot complete after ${notAfterDate.toLocaleString()}`
: 'Date constraint not met'
}
</Text>
</Flex>
)}
</Flex>
</Box>
}>
<Badge
color="orange"
variant="soft"
size="1"
className="cursor-help hover:opacity-80 transition-opacity"
>
<span className="text-xs"></span>
</Badge>
</Tooltip>
)}
{isLocked && !isLockedByMe && (
<Badge color="red" variant="surface" size="1">
<LockClosedIcon width="12" height="12" />
{item.locked_by}
</Badge>
)}
{!isEditing && (
<>
<Tooltip content="Manage dependencies">
<IconButton
size="1"
variant="ghost"
onClick={() => setIsDependencyModalOpen(true)}
>
<LinkBreak2Icon width="16" height="16" />
</IconButton>
</Tooltip>
<Tooltip content="Manage date constraints">
<IconButton
size="1"
variant="ghost"
onClick={() => setIsDateConstraintModalOpen(true)}
>
<ClockIcon width="16" height="16" />
</IconButton>
</Tooltip>
<Tooltip content="Delete item">
<IconButton
size="1"
variant="ghost"
color="red"
onClick={handleDelete}
disabled={isDeleting}
>
<TrashIcon width="16" height="16" />
</IconButton>
</Tooltip>
</>
)}
</Flex>
</Flex>
{children.length > 0 && (
<Box ml="8" mt="2" pl="4" className="space-y-2 border-l-2 border-gray-200 dark:border-gray-700">
{children.map(child => (
<ChecklistItem
key={child.id}
item={child}
onUpdate={onUpdate}
onDelete={onDelete}
onLock={onLock}
depth={depth + 1}
allItems={allItems}
/>
))}
</Box>
)}
{/* Dependency Manager Modal */}
<DependencyManager
item={item}
allItems={allItems}
onUpdate={onUpdate}
onClose={() => setIsDependencyModalOpen(false)}
isOpen={isDependencyModalOpen}
/>
{/* Date Constraint Manager Modal */}
{isDateConstraintModalOpen && (
<DateConstraintManager
item={item}
onSave={handleDateConstraintSave}
onCancel={() => setIsDateConstraintModalOpen(false)}
/>
)}
</li>
</Box>
)
}

View file

@ -0,0 +1,132 @@
import { useState, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { importChecklistFromJSON } from '../hooks/useLocalStorage'
import { Card, Heading, Text, TextField, Button, Flex, Box, Separator } from '@radix-ui/themes'
import { UploadIcon } from '@radix-ui/react-icons'
interface CreateChecklistProps {
className?: string
}
export default function CreateChecklist({ className = '' }: CreateChecklistProps) {
const [checklistName, setChecklistName] = useState('')
const [isCreating, setIsCreating] = useState(false)
const [isImporting, setIsImporting] = useState(false)
const fileInputRef = useRef<HTMLInputElement>(null)
const navigate = useNavigate()
const createChecklist = async () => {
if (!checklistName.trim()) return
setIsCreating(true)
try {
const response = await fetch('/api/checklists', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: checklistName.trim() }),
})
if (response.ok) {
const data = await response.json()
// Navigate to the new checklist
navigate(`/${data.uuid}`)
} else {
alert('Failed to create checklist')
}
} catch (error) {
console.error('Error creating checklist:', error)
alert('Failed to create checklist')
} finally {
setIsCreating(false)
setChecklistName('')
}
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
createChecklist()
}
}
const handleImportChecklist = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (!file) return
setIsImporting(true)
try {
const newUuid = await importChecklistFromJSON(file)
navigate(`/${newUuid}`)
} catch (error) {
console.error('Error importing checklist:', error)
alert('Failed to import checklist. Please check the file format.')
} finally {
setIsImporting(false)
// Reset the file input
if (fileInputRef.current) {
fileInputRef.current.value = ''
}
}
}
const triggerFileInput = () => {
fileInputRef.current?.click()
}
return (
<Card size="3" className={className}>
<Heading size="5" mb="5">Create New Checklist</Heading>
<Flex direction={{ initial: 'column', sm: 'row' }} gap="3" mb="5">
<Box style={{ flex: 1 }}>
<TextField.Root
size="3"
placeholder="Enter checklist name..."
value={checklistName}
onChange={(e) => setChecklistName(e.target.value)}
onKeyDown={handleKeyDown}
disabled={isCreating || isImporting}
/>
</Box>
<Button
onClick={createChecklist}
disabled={isCreating || isImporting || !checklistName.trim()}
size="3"
>
{isCreating ? 'Creating...' : 'Create'}
</Button>
</Flex>
<Separator size="4" />
<Box pt="5">
<Heading size="4" mb="3">Import Checklist</Heading>
<Flex direction={{ initial: 'column', sm: 'row' }} gap="3" align={{ sm: 'end' }}>
<Box style={{ flex: 1 }}>
<Text size="2" color="gray">
Import a previously exported checklist JSON file
</Text>
<input
ref={fileInputRef}
type="file"
accept=".json"
onChange={handleImportChecklist}
className="hidden"
/>
</Box>
<Button
onClick={triggerFileInput}
disabled={isCreating || isImporting}
size="3"
color="green"
>
<UploadIcon />
{isImporting ? 'Importing...' : 'Import JSON'}
</Button>
</Flex>
</Box>
</Card>
)
}

View file

@ -0,0 +1,232 @@
import React, { useState, useEffect } from 'react'
import type { ChecklistItem } from '../types'
import { Dialog, Flex, Text, Button, Heading, Card, Box, IconButton } from '@radix-ui/themes'
import { Cross2Icon, CalendarIcon, ClockIcon } from '@radix-ui/react-icons'
interface DateConstraintManagerProps {
item: ChecklistItem
onSave: (notBefore?: string, notAfter?: string) => void
onCancel: () => void
}
export const DateConstraintManager: React.FC<DateConstraintManagerProps> = ({
item,
onSave,
onCancel
}) => {
// Parse existing dates to local datetime format for inputs
const formatDateTimeLocal = (date: Date | null): string => {
if (!date) return ''
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
return `${year}-${month}-${day}T${hours}:${minutes}`
}
const [notBeforeValue, setNotBeforeValue] = useState<string>(
item.not_before ? formatDateTimeLocal(new Date(item.not_before)) : ''
)
const [notAfterValue, setNotAfterValue] = useState<string>(
item.not_after ? formatDateTimeLocal(new Date(item.not_after)) : ''
)
// Get current datetime in local format for min attribute
const now = new Date()
const minDateTime = formatDateTimeLocal(now)
const handleSave = () => {
const notBeforeDate = notBeforeValue ? new Date(notBeforeValue).toISOString() : undefined
const notAfterDate = notAfterValue ? new Date(notAfterValue).toISOString() : undefined
onSave(notBeforeDate, notAfterDate)
}
const handleClear = () => {
setNotBeforeValue('')
setNotAfterValue('')
}
// Update min value for notAfter when notBefore changes
useEffect(() => {
if (notBeforeValue && notAfterValue) {
const notBeforeDate = new Date(notBeforeValue)
const notAfterDate = new Date(notAfterValue)
if (notBeforeDate > notAfterDate) {
setNotAfterValue(notBeforeValue)
}
}
}, [notBeforeValue, notAfterValue])
return (
<Dialog.Root open={true} onOpenChange={onCancel}>
<Dialog.Content style={{ maxWidth: 450 }}>
<Dialog.Title>Manage Date Constraints</Dialog.Title>
<Dialog.Description size="2" mb="4">
Set when this item can be completed. Leave empty to remove constraints.
</Dialog.Description>
<Flex direction="column" gap="4">
<Box>
<Flex align="center" gap="2" mb="2">
<CalendarIcon />
<Text size="2" weight="medium">
Not Before (Earliest completion time)
</Text>
</Flex>
<Box position="relative">
<input
type="datetime-local"
value={notBeforeValue}
onChange={(e) => setNotBeforeValue(e.target.value)}
min={minDateTime}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
style={{
colorScheme: 'dark',
WebkitAppearance: 'none',
MozAppearance: 'none'
}}
/>
{notBeforeValue && (
<IconButton
size="1"
variant="ghost"
color="gray"
onClick={() => setNotBeforeValue('')}
style={{
position: 'absolute',
right: '8px',
top: '50%',
transform: 'translateY(-50%)'
}}
>
<Cross2Icon />
</IconButton>
)}
</Box>
</Box>
<Box>
<Flex align="center" gap="2" mb="2">
<ClockIcon />
<Text size="2" weight="medium">
Not After (Latest completion time)
</Text>
</Flex>
<Box position="relative">
<input
type="datetime-local"
value={notAfterValue}
onChange={(e) => setNotAfterValue(e.target.value)}
min={notBeforeValue || minDateTime}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
style={{
colorScheme: 'dark',
WebkitAppearance: 'none',
MozAppearance: 'none'
}}
/>
{notAfterValue && (
<IconButton
size="1"
variant="ghost"
color="gray"
onClick={() => setNotAfterValue('')}
style={{
position: 'absolute',
right: '8px',
top: '50%',
transform: 'translateY(-50%)'
}}
>
<Cross2Icon />
</IconButton>
)}
</Box>
</Box>
{/* Quick select buttons for common time periods */}
<Box>
<Text size="2" weight="medium" mb="2">
Quick select:
</Text>
<Flex gap="2" wrap="wrap">
<Button
size="1"
variant="soft"
onClick={() => {
const tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
tomorrow.setHours(9, 0, 0, 0)
setNotBeforeValue(formatDateTimeLocal(tomorrow))
}}
>
Tomorrow 9AM
</Button>
<Button
size="1"
variant="soft"
onClick={() => {
const nextWeek = new Date()
nextWeek.setDate(nextWeek.getDate() + 7)
nextWeek.setHours(9, 0, 0, 0)
setNotBeforeValue(formatDateTimeLocal(nextWeek))
}}
>
Next week
</Button>
<Button
size="1"
variant="soft"
onClick={() => {
const endOfWeek = new Date()
const daysUntilFriday = (5 - endOfWeek.getDay() + 7) % 7 || 7
endOfWeek.setDate(endOfWeek.getDate() + daysUntilFriday)
endOfWeek.setHours(17, 0, 0, 0)
setNotAfterValue(formatDateTimeLocal(endOfWeek))
}}
>
End of week
</Button>
</Flex>
</Box>
</Flex>
{(notBeforeValue || notAfterValue) && (
<Card size="2" mt="4">
<Heading size="2" mb="2">Preview:</Heading>
<Flex direction="column" gap="1">
{notBeforeValue && (
<Text size="2" color="gray"> Can complete after: {new Date(notBeforeValue).toLocaleString()}</Text>
)}
{notAfterValue && (
<Text size="2" color="gray"> Can complete before: {new Date(notAfterValue).toLocaleString()}</Text>
)}
{notBeforeValue && notAfterValue && (
<Text size="2" color="blue" weight="medium">
Time window: {Math.round((new Date(notAfterValue).getTime() - new Date(notBeforeValue).getTime()) / (1000 * 60 * 60 * 24))} days
</Text>
)}
</Flex>
</Card>
)}
<Flex gap="3" mt="4" justify="between">
<Button variant="ghost" onClick={handleClear}>
Clear All
</Button>
<Flex gap="2">
<Dialog.Close>
<Button variant="soft" color="gray">
Cancel
</Button>
</Dialog.Close>
<Button onClick={handleSave}>
Save
</Button>
</Flex>
</Flex>
</Dialog.Content>
</Dialog.Root>
)
}

View file

@ -0,0 +1,118 @@
import { useState, useEffect } from 'react'
import type { ChecklistItem } from '../types'
import { Dialog, Flex, Text, Button, Checkbox, ScrollArea, Badge, Separator } from '@radix-ui/themes'
interface DependencyManagerProps {
item: ChecklistItem
allItems: ChecklistItem[]
onUpdate: (id: number, updates: Partial<ChecklistItem>) => Promise<void>
onClose: () => void
isOpen: boolean
}
export default function DependencyManager({
item,
allItems,
onUpdate,
onClose,
isOpen
}: DependencyManagerProps) {
const [selectedDependencies, setSelectedDependencies] = useState<number[]>([])
const [isUpdating, setIsUpdating] = useState(false)
useEffect(() => {
if (isOpen) {
setSelectedDependencies(item.dependencies || [])
}
}, [isOpen, item.dependencies])
const handleSave = async () => {
setIsUpdating(true)
try {
await onUpdate(item.id, { dependencies: selectedDependencies })
onClose()
} catch (error) {
console.error('Failed to update dependencies:', error)
} finally {
setIsUpdating(false)
}
}
const toggleDependency = (depId: number) => {
setSelectedDependencies(prev =>
prev.includes(depId)
? prev.filter(id => id !== depId)
: [...prev, depId]
)
}
const availableItems = allItems.filter(otherItem =>
otherItem.id !== item.id &&
!otherItem.dependencies?.includes(item.id) // Prevent circular dependencies
)
return (
<Dialog.Root open={isOpen} onOpenChange={onClose}>
<Dialog.Content style={{ maxWidth: 450 }}>
<Dialog.Title>Manage Dependencies</Dialog.Title>
<Dialog.Description size="2" mb="4">
Select items that must be completed before "{item.content}" can be completed:
</Dialog.Description>
<ScrollArea type="auto" scrollbars="vertical" style={{ height: 300 }}>
{availableItems.length === 0 ? (
<Flex align="center" justify="center" p="4">
<Text color="gray">No available items to depend on</Text>
</Flex>
) : (
<Flex direction="column" gap="1">
{availableItems.map((otherItem, index) => (
<div key={otherItem.id}>
<Flex
align="center"
gap="3"
p="3"
className="hover:bg-gray-50 dark:hover:bg-gray-800 cursor-pointer rounded-md"
onClick={() => toggleDependency(otherItem.id)}
>
<Checkbox
checked={selectedDependencies.includes(otherItem.id)}
onCheckedChange={() => toggleDependency(otherItem.id)}
/>
<Text
size="2"
style={{
textDecoration: otherItem.checked ? 'line-through' : 'none',
opacity: otherItem.checked ? 0.6 : 1,
flex: 1
}}
>
{otherItem.content}
</Text>
{otherItem.checked && (
<Badge color="green" size="1">
Done
</Badge>
)}
</Flex>
{index < availableItems.length - 1 && <Separator size="4" />}
</div>
))}
</Flex>
)}
</ScrollArea>
<Flex gap="3" mt="4" justify="end">
<Dialog.Close>
<Button variant="soft" color="gray">
Cancel
</Button>
</Dialog.Close>
<Button onClick={handleSave} disabled={isUpdating}>
{isUpdating ? 'Saving...' : 'Save'}
</Button>
</Flex>
</Dialog.Content>
</Dialog.Root>
)
}

View file

@ -0,0 +1,109 @@
import React, { useState, useRef, useEffect } from 'react'
import { TextField, Button, Flex, Text } from '@radix-ui/themes'
import { Pencil1Icon } from '@radix-ui/react-icons'
interface EditableTitleProps {
title: string
onSave: (newTitle: string) => Promise<void>
className?: string
}
export const EditableTitle: React.FC<EditableTitleProps> = ({
title,
onSave,
className = ''
}) => {
const [isEditing, setIsEditing] = useState(false)
const [editValue, setEditValue] = useState(title)
const [isSaving, setIsSaving] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
setEditValue(title)
}, [title])
useEffect(() => {
if (isEditing && inputRef.current) {
inputRef.current.focus()
inputRef.current.select()
}
}, [isEditing])
const handleStartEdit = () => {
setIsEditing(true)
setEditValue(title)
}
const handleSave = async () => {
const trimmedValue = editValue.trim()
if (trimmedValue === title || trimmedValue === '') {
setIsEditing(false)
return
}
setIsSaving(true)
try {
await onSave(trimmedValue)
setIsEditing(false)
} catch (error) {
console.error('Failed to save title:', error)
// Reset to original value on error
setEditValue(title)
} finally {
setIsSaving(false)
}
}
const handleCancel = () => {
setIsEditing(false)
setEditValue(title)
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
e.preventDefault()
handleSave()
} else if (e.key === 'Escape') {
e.preventDefault()
handleCancel()
}
}
if (isEditing) {
return (
<Flex align="center" gap="2" className={className}>
<TextField.Root
ref={inputRef}
size="2"
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={handleSave}
disabled={isSaving}
style={{ fontWeight: 'bold' }}
maxLength={100}
/>
{isSaving && (
<Text size="2" color="gray">
Saving...
</Text>
)}
</Flex>
)
}
return (
<Button
onClick={handleStartEdit}
variant="ghost"
size="2"
className={`group ${className}`}
title="Click to edit title"
>
<Text weight="bold" size="3">
{title}
</Text>
<Pencil1Icon className="opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
</Button>
)
}

View file

@ -0,0 +1,109 @@
import { Link } from 'react-router-dom'
import { loadSavedChecklists, exportChecklistToJSON } from '../hooks/useLocalStorage'
import { useState } from 'react'
import { Card, Heading, Text, Button, Flex, Box } from '@radix-ui/themes'
import { Share1Icon, DownloadIcon, TrashIcon } from '@radix-ui/react-icons'
interface SavedChecklistsProps {
className?: string
}
export default function SavedChecklists({ className = '' }: SavedChecklistsProps) {
const [savedChecklists, setSavedChecklists] = useState<{ uuid: string; name: string; lastOpened?: string }[]>(loadSavedChecklists())
const [exportingChecklist, setExportingChecklist] = useState<string | null>(null)
const handleForgetCheckList = (uuid: string): void => {
const updatedChecklists = savedChecklists.filter((checklist: { uuid: string }) => checklist.uuid !== uuid)
localStorage.setItem('gocheck-saved-checklists', JSON.stringify(updatedChecklists))
setSavedChecklists(updatedChecklists)
}
const handleExportChecklist = async (uuid: string, name: string): Promise<void> => {
setExportingChecklist(uuid)
try {
await exportChecklistToJSON(uuid, name)
} catch {
alert('Failed to export checklist')
} finally {
setExportingChecklist(null)
}
}
if (savedChecklists.length === 0) {
return (
<Card size="3" className={className}>
<Flex direction="column" align="center" justify="center" py="9">
<Text size="9" color="gray" mb="4">📋</Text>
<Heading size="5" mb="2">No checklists yet</Heading>
<Text color="gray">Create your first checklist above to get started!</Text>
</Flex>
</Card>
)
}
return (
<Card size="3" className={className}>
<Heading size="5" mb="5">Your Checklists</Heading>
<Flex direction="column" gap="3">
{savedChecklists.map((checklist) => (
<Card key={checklist.uuid} size="2">
<Flex direction={{ initial: 'column', sm: 'row' }} justify="between" gap="3">
<Box>
<Heading size="3" mb="1">{checklist.name}</Heading>
<Text size="2" color="gray">
Last opened: {checklist.lastOpened ? new Date(checklist.lastOpened).toLocaleString() : 'Never'}
</Text>
</Box>
<Flex gap="2" wrap="wrap">
<Link to={`/${checklist.uuid}`}>
<Button size="2">
Open
</Button>
</Link>
<Button
size="2"
color="green"
onClick={() => {
const url = `${window.location.origin}/${checklist.uuid}`
navigator.clipboard.writeText(url).then(() => {
alert('Checklist link copied to clipboard! ' + url)
}).catch(() => {
const textArea = document.createElement('textarea')
textArea.value = url
document.body.appendChild(textArea)
textArea.select()
document.execCommand('copy')
document.body.removeChild(textArea)
alert('Checklist link copied to clipboard!')
})
}}
>
<Share1Icon />
Share
</Button>
<Button
size="2"
color="violet"
onClick={() => handleExportChecklist(checklist.uuid, checklist.name)}
disabled={exportingChecklist === checklist.uuid}
>
<DownloadIcon />
{exportingChecklist === checklist.uuid ? 'Exporting...' : 'Export'}
</Button>
<Button
size="2"
color="red"
onClick={() => handleForgetCheckList(checklist.uuid)}
>
<TrashIcon />
Forget
</Button>
</Flex>
</Flex>
</Card>
))}
</Flex>
</Card>
)
}

View file

@ -0,0 +1,204 @@
import type { SavedChecklist, ChecklistItem } from '../types'
const STORAGE_KEY = 'gocheck-saved-checklists'
export function saveChecklist(checklist: SavedChecklist) {
try {
const existingChecklists = loadSavedChecklists()
const existingIndex = existingChecklists.findIndex(c => c.uuid === checklist.uuid);
if (existingIndex > -1) {
// Update lastOpened timestamp if checklist already exists
existingChecklists[existingIndex].lastOpened = new Date().toISOString();
existingChecklists[existingIndex].name = checklist.name;
} else {
// Add new checklist with lastOpened timestamp
existingChecklists.push({ ...checklist, lastOpened: new Date().toISOString() });
}
// Sort by lastOpened date in descending order
existingChecklists.sort((a, b) => {
if (!a.lastOpened) return 1;
if (!b.lastOpened) return -1;
return new Date(b.lastOpened).getTime() - new Date(a.lastOpened).getTime();
});
localStorage.setItem(STORAGE_KEY, JSON.stringify(existingChecklists));
} catch (error) {
console.error('Error saving checklist:', error);
}
}
export const loadSavedChecklists = (): SavedChecklist[] => {
const saved = localStorage.getItem(STORAGE_KEY)
if (saved) {
try {
const parsed = JSON.parse(saved);
if (Array.isArray(parsed)) {
return parsed as SavedChecklist[];
}
} catch (error) {
console.error('Error parsing saved checklists:', error);
}
}
return []
}
export const exportChecklistToJSON = async (uuid: string, name: string): Promise<void> => {
try {
const response = await fetch(`/api/checklists/${uuid}/items`)
if (!response.ok) {
throw new Error('Failed to fetch checklist data')
}
const data = await response.json()
if (!data.success || !data.items) {
throw new Error('Invalid response format')
}
const exportData = {
name: name,
uuid: uuid,
exportedAt: new Date().toISOString(),
items: data.items as ChecklistItem[]
}
const jsonString = JSON.stringify(exportData, null, 2)
const blob = new Blob([jsonString], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = `${name.replace(/[^a-z0-9]/gi, '_').toLowerCase()}_${uuid}.json`
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url)
} catch (error) {
console.error('Error exporting checklist:', error)
throw error
}
}
interface ImportData {
name: string
uuid?: string
exportedAt?: string
items: ChecklistItem[]
}
export const importChecklistFromJSON = async (file: File): Promise<string> => {
try {
// Read the file
const text = await file.text()
const importData: ImportData = JSON.parse(text)
// Validate the import data
if (!importData.name || !importData.items || !Array.isArray(importData.items)) {
throw new Error('Invalid import file format')
}
// Create a new checklist
const createResponse = await fetch('/api/checklists', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: importData.name }),
})
if (!createResponse.ok) {
throw new Error('Failed to create checklist')
}
const createData = await createResponse.json()
if (!createData.success || !createData.uuid) {
throw new Error('Invalid response from checklist creation')
}
const newUuid = createData.uuid
// Create a mapping from old item IDs to new item IDs
const idMapping = new Map<number, number>()
// First pass: Add all items and build the ID mapping
for (const item of importData.items) {
const addItemResponse = await fetch(`/api/checklists/${newUuid}/items`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: item.content,
parent_id: null, // We'll handle parent relationships in the second pass
not_before: item.not_before,
not_after: item.not_after,
}),
})
if (!addItemResponse.ok) {
throw new Error(`Failed to add item: ${item.content}`)
}
const addItemData = await addItemResponse.json()
if (!addItemData.success || !addItemData.item) {
throw new Error(`Invalid response when adding item: ${item.content}`)
}
const newItemId = addItemData.item.id
idMapping.set(item.id, newItemId)
}
// Second pass: Update parent relationships and dependencies
for (const item of importData.items) {
const newItemId = idMapping.get(item.id)
if (!newItemId) continue
const updates: Partial<ChecklistItem> = {}
// Handle parent relationships
if (item.parent_id !== null) {
const newParentId = idMapping.get(item.parent_id)
if (newParentId) {
updates.parent_id = newParentId
}
}
// Handle dependencies
if (item.dependencies && item.dependencies.length > 0) {
const newDependencies = item.dependencies
.map(oldDepId => idMapping.get(oldDepId))
.filter(newDepId => newDepId !== undefined) as number[]
if (newDependencies.length > 0) {
updates.dependencies = newDependencies
}
}
// Update item if it was checked in the original
if (item.checked) {
updates.checked = true
}
// Apply updates if there are any
if (Object.keys(updates).length > 0) {
const updateResponse = await fetch(`/api/checklists/${newUuid}/items/${newItemId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updates),
})
if (!updateResponse.ok) {
console.warn(`Failed to update item: ${item.content}`)
}
}
}
return newUuid
} catch (error) {
console.error('Error importing checklist:', error)
throw error
}
}

View file

@ -0,0 +1,126 @@
import { useEffect, useRef, useState } from 'react'
import type { SSEEvent, ChecklistItem } from '../types'
import { saveChecklist } from '../hooks/useLocalStorage'
export function useSSE(uuid: string) {
const [items, setItems] = useState<ChecklistItem[]>([])
const [checkListName, setCheckListName] = useState('')
const [isConnected, setIsConnected] = useState(false)
const [error, setError] = useState<string | null>(null)
const eventSourceRef = useRef<EventSource | null>(null)
useEffect(() => {
if (!uuid) return
const connectSSE = () => {
try {
const eventSource = new EventSource(`/api/checklists/${uuid}/sse`)
eventSourceRef.current = eventSource
eventSource.onopen = () => {
setIsConnected(true)
setError(null)
}
eventSource.onmessage = (event) => {
try {
const data: SSEEvent = JSON.parse(event.data)
switch (data.type) {
case 'checklist_name':
case 'checklist_name_updated':
if (data.name) {
saveChecklist({
uuid,
name: data.name,
createdAt: new Date().toISOString(),
})
setCheckListName(data.name)
}
break
case 'full_state':
if (data.items) {
setItems(data.items)
}
break
case 'item_added':
if (data.item) {
setItems(prev => [...prev, data.item!])
}
break
case 'item_updated':
if (data.item) {
setItems(prev =>
prev.map(item =>
item.id === data.item!.id ? data.item! : item
)
)
}
break
case 'item_deleted':
if (data.id) {
setItems(prev => prev.filter(item => item.id !== data.id))
}
break
case 'item_locked':
if (data.id && data.locked_by && data.expires) {
setItems(prev =>
prev.map(item =>
item.id === data.id
? {
...item,
locked_by: data.locked_by,
lock_until: data.expires
}
: item
)
)
}
break
case 'item_unlocked':
if (data.id) {
setItems(prev =>
prev.map(item =>
item.id === data.id
? { ...item, locked_by: undefined, lock_until: undefined }
: item
)
)
}
break
}
} catch (parseError) {
console.error('Error parsing SSE message:', parseError)
}
}
eventSource.onerror = (error) => {
console.error('SSE Error:', error)
setError('Connection lost. Trying to reconnect...')
setIsConnected(false)
// Close and attempt to reconnect after a delay
eventSource.close()
setTimeout(connectSSE, 3000)
}
} catch (error) {
console.error('Error connecting to SSE:', error)
setError('Failed to connect to server')
setIsConnected(false)
}
}
connectSSE()
return () => {
if (eventSourceRef.current) {
eventSourceRef.current.close()
eventSourceRef.current = null
}
setIsConnected(false)
}
}, [uuid])
return { items, checkListName, isConnected, error }
}

64
frontend/src/index.css Normal file
View file

@ -0,0 +1,64 @@
@import "tailwindcss";
/* Remove list styling from checklist items */
li {
list-style: none;
}
/* Radix UI Theme adjustments */
.radix-themes {
--default-font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
/* Custom scrollbar for Radix ScrollArea */
[data-radix-scroll-area-viewport] {
scrollbar-width: thin;
scrollbar-color: var(--gray-a6) transparent;
}
[data-radix-scroll-area-viewport]::-webkit-scrollbar {
width: 8px;
height: 8px;
}
[data-radix-scroll-area-viewport]::-webkit-scrollbar-track {
background: transparent;
}
[data-radix-scroll-area-viewport]::-webkit-scrollbar-thumb {
background-color: var(--gray-a6);
border-radius: 4px;
}
[data-radix-scroll-area-viewport]::-webkit-scrollbar-thumb:hover {
background-color: var(--gray-a8);
}
/* Native datetime input styling */
input[type="datetime-local"] {
position: relative;
font-family: inherit;
}
input[type="datetime-local"]::-webkit-calendar-picker-indicator {
cursor: pointer;
opacity: 0.6;
filter: invert(0.8);
}
input[type="datetime-local"]::-webkit-calendar-picker-indicator:hover {
opacity: 1;
}
.dark input[type="datetime-local"]::-webkit-calendar-picker-indicator {
filter: invert(0.8);
}
/* Ensure good mobile tap targets */
@media (max-width: 640px) {
input[type="datetime-local"] {
font-size: 16px; /* Prevents zoom on iOS */
min-height: 44px; /* Apple's recommended touch target size */
}
}

14
frontend/src/main.tsx Normal file
View file

@ -0,0 +1,14 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import '@radix-ui/themes/styles.css'
import './index.css'
import { Theme } from '@radix-ui/themes'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<Theme accentColor="violet" grayColor="sand" radius="medium" scaling="100%">
<App />
</Theme>
</StrictMode>,
)

View file

@ -0,0 +1,431 @@
import { useState } from 'react'
import { useParams, Link } from 'react-router-dom'
import { useSSE } from '../hooks/useSSE'
import ChecklistItem from '../components/ChecklistItem'
import { EditableTitle } from '../components/EditableTitle'
import { exportChecklistToJSON } from '../hooks/useLocalStorage'
import type { ChecklistItem as ChecklistItemType } from '../types'
import { Flex, Box, Text, Button, TextField, Heading, Badge, Card, IconButton } from '@radix-ui/themes'
import { ArrowLeftIcon, DownloadIcon, ChevronDownIcon, ChevronUpIcon } from '@radix-ui/react-icons'
interface ItemGroup {
title: string
items: ChecklistItemType[]
isCollapsible?: boolean
isCollapsed?: boolean
onToggleCollapse?: () => void
}
export default function Checklist() {
const { uuid } = useParams<{ uuid: string }>()
const { items, checkListName, isConnected, error } = useSSE(uuid || '')
const [newItemContent, setNewItemContent] = useState('')
const [isAddingItem, setIsAddingItem] = useState(false)
const [completedItemsCollapsed, setCompletedItemsCollapsed] = useState(false)
const [isExporting, setIsExporting] = useState(false)
const buildItemTree = (items: ChecklistItemType[]): ChecklistItemType[] => {
const itemMap = new Map<number, ChecklistItemType>()
const rootItems: ChecklistItemType[] = []
// Create a map of all items
items.forEach(item => {
itemMap.set(item.id, { ...item, children: [] })
})
// Build the tree structure
items.forEach(item => {
if (item.parent_id === null) {
rootItems.push(itemMap.get(item.id)!)
} else {
const parent = itemMap.get(item.parent_id)
if (parent) {
if (!parent.children) parent.children = []
parent.children.push(itemMap.get(item.id)!)
}
}
})
return rootItems
}
const categorizeItems = (items: ChecklistItemType[]): ItemGroup[] => {
const now = new Date()
// Helper function to check if an item can be completed
const canComplete = (item: ChecklistItemType): boolean => {
// Check dependencies
const dependenciesCompleted = item.dependencies?.every(depId => {
const depItem = items.find(i => i.id === depId)
return depItem?.checked
}) ?? true
// Check date constraints
const notBeforeDate = item.not_before ? new Date(item.not_before) : null
const notAfterDate = item.not_after ? new Date(item.not_after) : null
const dateConstraintsMet = (!notBeforeDate || now >= notBeforeDate) && (!notAfterDate || now <= notAfterDate)
return dependenciesCompleted && dateConstraintsMet
}
// Helper function to check if an item is locked by constraints
const isLockedByConstraints = (item: ChecklistItemType): boolean => {
if (item.checked) return false
// Check dependencies
const dependenciesCompleted = item.dependencies?.every(depId => {
const depItem = items.find(i => i.id === depId)
return depItem?.checked
}) ?? true
// Check date constraints
const notBeforeDate = item.not_before ? new Date(item.not_before) : null
const notAfterDate = item.not_after ? new Date(item.not_after) : null
const dateConstraintsMet = (!notBeforeDate || now >= notBeforeDate) && (!notAfterDate || now <= notAfterDate)
return !dependenciesCompleted || !dateConstraintsMet
}
const completedItems = items.filter(item => item.checked)
const availableItems = items.filter(item => !item.checked && canComplete(item))
const lockedItems = items.filter(item => !item.checked && isLockedByConstraints(item))
const groups: ItemGroup[] = []
// Completed items (collapsible)
if (completedItems.length > 0) {
groups.push({
title: `Completed (${completedItems.length})`,
items: completedItems,
isCollapsible: true,
isCollapsed: completedItemsCollapsed,
onToggleCollapse: () => setCompletedItemsCollapsed(!completedItemsCollapsed)
})
}
// Available items (can be completed)
if (availableItems.length > 0) {
groups.push({
title: `Available (${availableItems.length})`,
items: availableItems
})
}
// Locked items (cannot be completed due to constraints)
if (lockedItems.length > 0) {
groups.push({
title: `Locked by Constraints (${lockedItems.length})`,
items: lockedItems
})
}
return groups
}
const addItem = async (content: string, parentId?: number) => {
if (!content.trim() || !uuid) return
setIsAddingItem(true)
try {
const response = await fetch(`/api/checklists/${uuid}/items`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: content.trim(),
parent_id: parentId || null
}),
})
if (!response.ok) {
throw new Error('Failed to add item')
}
} catch (error) {
console.error('Error adding item:', error)
alert('Failed to add item')
} finally {
setIsAddingItem(false)
}
}
const updateItem = async (id: number, updates: Partial<ChecklistItemType>) => {
if (!uuid) return
try {
const response = await fetch(`/api/checklists/${uuid}/items/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updates),
})
if (!response.ok) {
throw new Error('Failed to update item')
}
} catch (error) {
console.error('Error updating item:', error)
throw error
}
}
const deleteItem = async (id: number) => {
if (!uuid) return
try {
const response = await fetch(`/api/checklists/${uuid}/items/${id}`, {
method: 'DELETE',
})
if (!response.ok) {
throw new Error('Failed to delete item')
}
} catch (error) {
console.error('Error deleting item:', error)
throw error
}
}
const lockItem = async (id: number, user: string) => {
if (!uuid) return
try {
const response = await fetch(`/api/checklists/${uuid}/items/${id}/lock`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ user }),
})
if (!response.ok) {
throw new Error('Failed to lock item')
}
} catch (error) {
console.error('Error locking item:', error)
throw error
}
}
const updateChecklistName = async (newName: string) => {
if (!uuid) throw new Error('No checklist UUID')
const response = await fetch(`/api/checklists/${uuid}/name`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: newName }),
})
if (!response.ok) {
throw new Error('Failed to update checklist name')
}
}
const handleAddItem = async () => {
await addItem(newItemContent)
setNewItemContent('')
}
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
handleAddItem()
}
}
const handleExportChecklist = async () => {
if (!uuid || !checkListName) return
setIsExporting(true)
try {
await exportChecklistToJSON(uuid, checkListName)
} catch {
alert('Failed to export checklist')
} finally {
setIsExporting(false)
}
}
const renderGroupedItems = (allItems: ChecklistItemType[]) => {
const itemTree = buildItemTree(allItems)
if (itemTree.length === 0) {
return (
<Flex direction="column" align="center" justify="center" py="9">
<Text size="9" color="gray" mb="3">📝</Text>
<Text size="3" weight="medium" color="gray">No items yet</Text>
<Text size="2" color="gray" mt="1">Add your first item above to get started!</Text>
</Flex>
)
}
const groups = categorizeItems(allItems)
return (
<Flex direction="column" gap="5">
{groups.map((group, groupIndex) => (
<Box key={groupIndex}>
<Flex align="center" justify="between" pb="2" className="border-b border-gray-200 dark:border-gray-700">
<Heading
size="2"
color={group.title.includes('Completed') ? "green" : group.title.includes('Available') ? "blue" : "orange"}
>
{group.title}
</Heading>
{group.isCollapsible && (
<IconButton
size="1"
variant="ghost"
onClick={group.onToggleCollapse}
>
{group.isCollapsed ? <ChevronDownIcon /> : <ChevronUpIcon />}
</IconButton>
)}
</Flex>
{(!group.isCollapsible || !group.isCollapsed) && (
<Box
mt="3"
style={{
opacity: group.title.includes('Completed') ? 0.75 : 1
}}
>
<Flex direction="column" gap="2">
{group.items.map(item => {
const findItemWithChildren = (items: ChecklistItemType[], targetId: number): ChecklistItemType | null => {
for (const item of items) {
if (item.id === targetId) {
return item
}
if (item.children) {
const found = findItemWithChildren(item.children, targetId)
if (found) return found
}
}
return null
}
const itemWithChildren = findItemWithChildren(itemTree, item.id)
return (
<ChecklistItem
key={item.id}
item={item}
onUpdate={updateItem}
onDelete={deleteItem}
onLock={lockItem}
children={itemWithChildren?.children || []}
allItems={allItems}
/>
)
})}
</Flex>
</Box>
)}
</Box>
))}
</Flex>
)
}
if (!uuid) {
return (
<Flex align="center" justify="center" style={{ minHeight: '100vh' }}>
<Text size="4" color="red" weight="medium">Invalid checklist ID</Text>
</Flex>
)
}
return (
<Box style={{ minHeight: '100vh' }} className="bg-gray-50 dark:bg-gray-900">
<Box className="bg-white dark:bg-gray-800 shadow-sm border-b border-gray-200 dark:border-gray-700">
<Box style={{ maxWidth: '1024px' }} mx="auto" p="3">
<Flex direction={{ initial: 'column', sm: 'row' }} align="center" justify="between" gap="3">
<Flex align="center" gap="3">
<Link to="/">
<Button variant="ghost" size="2">
<ArrowLeftIcon />
Back
</Button>
</Link>
<EditableTitle
title={checkListName}
onSave={updateChecklistName}
className="text-base"
/>
</Flex>
<Flex align="center" gap="2">
<Button
onClick={handleExportChecklist}
disabled={isExporting || !isConnected}
size="2"
color="violet"
>
<DownloadIcon />
{isExporting ? 'Exporting...' : 'Export'}
</Button>
<Badge
color={isConnected ? "green" : "red"}
variant="surface"
size="2"
>
<Box
width="8px"
height="8px"
className={`rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'}`}
/>
{isConnected ? 'Connected' : 'Disconnected'}
</Badge>
</Flex>
</Flex>
</Box>
</Box>
{error && (
<Box style={{ maxWidth: '1024px' }} mx="auto" px="2" py="2">
<Card size="2" style={{ backgroundColor: 'var(--red-a3)', borderColor: 'var(--red-a6)' }}>
<Flex align="center" gap="2">
<Text color="red"></Text>
<Text color="red" weight="medium">{error}</Text>
</Flex>
</Card>
</Box>
)}
<Box style={{ maxWidth: '1024px' }} mx="auto" px="3" py="4">
<Box mb="4">
<Flex direction={{ initial: 'column', sm: 'row' }} gap="2">
<Box style={{ flex: 1 }}>
<TextField.Root
size="3"
placeholder="Add a new item..."
value={newItemContent}
onChange={(e) => setNewItemContent(e.target.value)}
onKeyDown={handleKeyPress}
disabled={isAddingItem || !isConnected}
/>
</Box>
<Button
onClick={handleAddItem}
disabled={isAddingItem || !newItemContent.trim() || !isConnected}
size="3"
>
{isAddingItem ? 'Adding...' : 'Add'}
</Button>
</Flex>
</Box>
<Box>
{renderGroupedItems(items)}
</Box>
</Box>
</Box>
)
}

View file

@ -0,0 +1,16 @@
import CreateChecklist from '../components/CreateChecklist'
import SavedChecklists from '../components/SavedChecklists'
import { Box, Container } from '@radix-ui/themes'
function Home() {
return (
<Box style={{ minHeight: '100vh' }} className="bg-gray-50 dark:bg-gray-900">
<Container size="3" py="6">
<CreateChecklist className="mb-8" />
<SavedChecklists />
</Container>
</Box>
)
}
export default Home

36
frontend/src/types.ts Normal file
View file

@ -0,0 +1,36 @@
export interface ChecklistItem {
id: number
content: string
checked: boolean
parent_id: number | null
locked_by?: string
lock_until?: string
checklist_uuid: string
children?: ChecklistItem[]
dependencies?: number[]
not_before?: string
not_after?: string
}
export interface SavedChecklist {
uuid: string
name: string
createdAt: string
lastOpened?: string
}
export interface SSEEvent {
type: 'full_state' | 'item_added' | 'item_updated' | 'item_deleted' | 'item_locked' | 'item_unlocked' | 'checklist_name' | 'checklist_name_updated'
name?: string
items?: ChecklistItem[]
item?: ChecklistItem
id?: number
locked_by?: string
expires?: string
}
export interface ApiResponse<T = unknown> {
success: boolean
message: string
[key: string]: T | boolean | string
}

1
frontend/src/vite-env.d.ts vendored Normal file
View file

@ -0,0 +1 @@
/// <reference types="vite/client" />

View file

@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
frontend/tsconfig.json Normal file
View file

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View file

@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

19
frontend/vite.config.ts Normal file
View file

@ -0,0 +1,19 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import tailwindcss from '@tailwindcss/vite'
import { compression } from 'vite-plugin-compression2'
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss(), compression()],
server: {
host: '0.0.0.0', // Allow external access for Docker
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
},
},
},
})